IMVU.namespace( 'Registration' );
IMVU.Registration = function() {}
IMVU.Registration.Global = new function() {
    this.Browser = function() {
        return {
            init : function( config ) {
                this.cookies = config.cookies;
                var u = navigator.userAgent, d = document;
                this.win = /Windows/.test(u);
                this.mac = /Mac/.test(u);
                this.ie5 = d.all && !d.compatMode;
                this.ie6 = d.compatMode;
                this.dom = d.getElementById;
                this.supported = this.ie6 || this.dom || !this.ie5;
                if( this.cookies == '0' ) { // this is not reliable, need to look into another solution
                    /* alert(
                        'Your internet browser software does not appear to have cookies enabled. ' + '\n' +
                          'Correct functioning of the IMVU 3D instant messenger and website requires cookies.' + '\n' +
                          'For more info on how to enable cookies, please visit:' + '\n\n' +
                          'http://www.google.com/cookies.html' + '\n' + ' '
                    ); */
                }
                if( this.mac ) {
                    // need messaging for Apple user agents
                }
            }
        };
    }();
    this.Error = function() {
        return {
            inputs : {
                'avatar-name' : false,
                'avatar-gender' : false
            },
            add : function( name ) {
                this.inputs[name] = true;
            },
            clear : function( name ) {
                if( name ) {
                    this.inputs[name] = false;
                    return;
                }
                for( var i in this.inputs ) {
                    this.inputs[i] = false;
                }
            },
            check : function( name ) {
                return this.inputs[name];
            },
            get : function() {
                for( var i in this.inputs ) {
                    if( this.inputs[i] === true ) {
                        return true;
                    }
                }
                return false;
            }
        };
    }();
};
IMVU.Registration.AvatarNameFinder = new function() {
    var avatarNameMsg = YAHOO.util.Dom.get( 'avatar-name-msg' );
    var avatarNameInput = YAHOO.util.Dom.get( 'f-avatarname' );
    var self = this;
    var toggleDisplayResult = {
        on : function() {
            avatarNameMsg.innerHTML = 'available';
             YAHOO.util.Dom.addClass( 'avatar-name', 'available' );
             YAHOO.util.Dom.removeClass( 'avatar-name', 'taken' );
            IMVU.Registration.Global.Error.clear( 'avatar-name' );
        },
        off : function() {
            avatarNameMsg.innerHTML = 'Avatar name is already registered';
             YAHOO.util.Dom.addClass( 'avatar-name', 'taken' );
             YAHOO.util.Dom.removeClass( 'avatar-name', 'available' );
            IMVU.Registration.Global.Error.add( 'avatar-name' );
        },
        empty : function() {
            avatarNameMsg.innerHTML = '';
             YAHOO.util.Dom.removeClass( 'avatar-name', 'taken' );
             YAHOO.util.Dom.removeClass( 'avatar-name', 'available' );
        },
        searching : function() {
            avatarNameMsg.innerHTML = 'Searching ...';
             YAHOO.util.Dom.removeClass( 'avatar-name', 'taken' );
        }
    };
    var callback = function( result ) {
        var matched = function() {
            if ( result == 0 ) {
                return true;
            }
            return false;
        }();
        if (matched) {
            if( avatarNameInput.value == '' ) {
                toggleDisplayResult.empty();
                return;
            }
            toggleDisplayResult.off();
        } else {
            toggleDisplayResult.on();
        }
        IMVU.Registration.NextButton.toggle();
    };
    this.init = function() {
        var name = 'f-avatarname';
        var avatarFinder = new IMVU.catalog.AvatarFinder(
            name,
            {
              matching : 'exact',
              timeout : 2000
            },
            callback
        );
        avatarFinder.check_name_availability_onload( name );
        return toggleDisplayResult;
    };
};
IMVU.Registration.InputWidget = function( type, caller ) {
    this.type = type;
    this.caller = caller;
    this.elements = [];
    this.init = function() {
        var inputs =  YAHOO.util.Dom.getElementsByClassName( this.type, 'div' );
        for( var i = 0, el; el = inputs[i]; i++ ) {
            var input = el.getElementsByTagName( 'input' )[0];
            this.elements.push( input );
            YAHOO.util.Event.on( el, 'click', this.caller.handleMouseUp );
        }
    };
    this.init();
}
IMVU.Registration.GenderSelection = new function() {
    var self = this;
    this.init = function() {
        if( !this.inputWidget ) {
            this.inputWidget = new IMVU.Registration.InputWidget( 'radio', this );
        }
    };
    this.handleMouseUp = function() {
        self.selectElement( this );
    };
    // called from AvatarCustomization.processResponse()
    this.checkElement = function( gender ) {
        var el =  YAHOO.util.Dom.get( 'f-gender-' + gender ).parentNode;
        this.selectElement( el, this );
    };
    this.selectElement = function( el ) {
        var input = el.getElementsByTagName( 'input' )[0];
        input.checked = true;
         YAHOO.util.Dom.addClass( el, 'checked' );
        for( var i = 0, el; el = self.inputWidget.elements[i]; i++ ) {
            if( !el.checked ) {
                 YAHOO.util.Dom.removeClass( el.parentNode, 'checked' );
            }
        }
        var gender = input.value == 'f' ? '0' : '1';
        IMVU.Registration.AvatarCustomization.chooseAvatar( 'AVATAR', gender );
    };
};
IMVU.Registration.GenderSelectionOutfits = new function() {
    var self = this;
    this.init = function() {
        if( !this.inputWidget ) {
            this.inputWidget = new IMVU.Registration.InputWidget( 'radio', this );
        }
    };
    this.handleMouseUp = function() {
        self.selectElement( this );
    };
    // called from AvatarCustomization.processResponse()
    this.checkElement = function( gender ) {
        var el =  YAHOO.util.Dom.get( 'f-gender-' + gender ).parentNode;
        this.selectElement( el, this );
    };
    this.selectElement = function( el ) {
        var input = el.getElementsByTagName( 'input' )[0];
        input.checked = true;
         YAHOO.util.Dom.addClass( el, 'checked' );
        for( var i = 0, el; el = self.inputWidget.elements[i]; i++ ) {
            if( !el.checked ) {
                 YAHOO.util.Dom.removeClass( el.parentNode, 'checked' );
            }
        }
        var gender = input.value == 'f' ? '0' : '1';
        if (gender == 0) {
             YAHOO.util.Dom.get("outfits-f").style.display = "block";
             YAHOO.util.Dom.get("outfits-m").style.display = "none";
             YAHOO.util.Dom.get("placeholder").style.display = "none";
            if('f' == IMVU.Registration.getGenderFromDNA( YAHOO.util.Dom.get('f-dna').value)) {
                IMVU.Registration.chooseOutfit(IMVU.Registration.DNA2Outfit( YAHOO.util.Dom.get('f-dna').value));
            } else if ( YAHOO.util.Dom.getChildren('outfits-f')[0].id) {
                IMVU.Registration.chooseOutfit( YAHOO.util.Dom.getChildren('outfits-f')[0].id);    
            } else {
                IMVU.Registration.chooseOutfit('female02');
            }
        } else {
             YAHOO.util.Dom.get("outfits-m").style.display = "block";
             YAHOO.util.Dom.get("outfits-f").style.display = "none";
             YAHOO.util.Dom.get("placeholder").style.display = "none";
            if('m' == IMVU.Registration.getGenderFromDNA( YAHOO.util.Dom.get('f-dna').value)) {
                IMVU.Registration.chooseOutfit(IMVU.Registration.DNA2Outfit( YAHOO.util.Dom.get('f-dna').value));
            } else if ( YAHOO.util.Dom.getChildren('outfits-m')[0].id) {
                IMVU.Registration.chooseOutfit( YAHOO.util.Dom.getChildren('outfits-m')[0].id);    
            } else {
                IMVU.Registration.chooseOutfit('male01');
            }
        }
    };
};
IMVU.Registration.Outfits = {
    male01 : "191_101423_238346_335058_929997_1021127_1048078_1162147_1212669_1354639_1365733_1396447_1445763",
    male02 : "191_349616_417236_531069_648247_734936_1318099_1378521_1525675",
    male03 : "191_27126_295529_333682_335854_449449_458157_458164_613701_995267_1302912",
    male04 : "136_191_44913_296164_349616_658506_995267_1017375_1167060",
    male05 : "191_59089_73145_101057_301781_734947_801399_1056922_1158992_1159193_1159318",
    male06 : "191_91470_132708_234587_335854_386566_870001_914322_1018089_1122469",
    male07 : "191_115444_132708_222514_381866_538209_587847_729623_779247_1006511_1111434",
    male08 : "191_58043_429839_606363_934308_936870_1012356_1022933",
    male09 : "191_42700_45996_232588_235224_403575_644569_861895_936870_1059676",
    male10 : "191_15215_260581_302134_416229_474057_1018007_1055595_1158403",
    female01 : "80_132_241080_340820_371400_372416_372450_373024_395925_837927_838100",
    female02 : "80_782687_855964_919018_1050094_1204393_1215971_1286020_1343736_1418667",
    female03 : "80_59412_230065_257332_344269_438430_554785_652488_891269_934869_1099050_1099182",
    female04 : "80_59412_153671_233727_344272_349751_554542_562115_865982_1026491_1057274_1104048",
    female05 : "80_50748_52314_59412_92288_218374_433639_472386_477734_583927_1557796",
    female06 : "80_132_307731_356902_477435_903666_1204365_1420768",
    female07 : "80_156242_218374_219086_686909_1062708_1148311_1149158_1282478_1370479",
    female08 : "80_62099_95631_229610_297781_316679_327489_719171_733066_899106_959393",
    female09 : "80_14538_480632_759866_924700_953791_990338_991532_1141397_1176977",
    female10 : "80_59412_344274_408781_689615_1033975_1076945_1151752_1153109_1257651_1259381"
};
    
IMVU.Registration.DNA2Outfit = function(dna2find) {
    for (var dna in IMVU.Registration.Outfits) {
        if (IMVU.Registration.Outfits[dna] == dna2find) {
            return dna;
        }
    }
};
IMVU.Registration.chooseOutfit = function(outfit) {
    YAHOO.util.Event.onAvailable("avatar", function() {
        var avatar =  YAHOO.util.Dom.get("avatar");
        if (avatar && avatar.playFile) {
            avatar.playFile(outfit);
        }
    });
    YAHOO.util.Dom.get( 'f-dna' ).value = IMVU.Registration.Outfits[outfit];
};
IMVU.Registration.EmailOptIn = new function() {
     var self = this;
    this.init = function() {
        if( !this.inputWidget ) {
            this.inputWidget = new IMVU.Registration.InputWidget( 'checkbox', this );
        }
    };
    this.handleMouseUp = function( e ) {
        self.selectElement( this );
    }
    this.selectElement = function( el ) {
        var input = el.getElementsByTagName( 'input' )[0];
        if( ! YAHOO.util.Dom.hasClass( el, 'checked' )) {
            input.checked = true;
            if( input.checked ) {
                 YAHOO.util.Dom.addClass( el, 'checked' );
            }
        } else if(  YAHOO.util.Dom.hasClass( el, 'checked' )) {
            input.checked = false;
            if( !input.checked ) {
                 YAHOO.util.Dom.removeClass( el, 'checked' );
            }
        }
    };
};
IMVU.Registration.AvatarCustomization = function() {
    var disableSubmit = function() {
         YAHOO.util.Dom.addClass( 'btn-submit', 'disabled' );
         YAHOO.util.Dom.get( 'btn-submit' ).disabled = true;
        IMVU.Registration.NextButton.toggle();
    };
    var enableSubmit = function() {
         YAHOO.util.Dom.removeClass( 'btn-submit', 'disabled' );
         YAHOO.util.Dom.get( 'btn-submit' ).disabled = false;
        IMVU.Registration.NextButton.toggle();
    };
    return {
        looksetXMLPath : '',
        dna_pointers : '',
        regSet : [],
        pointers : {},
        newAvatar : true,
        avatarPreviewCounter : 0,
        dataLoaded : false,
        staticImgPath : 'http://static.imvu.com/imvufiles/avatars/r4_',
        init : function( config ) {
            var form =  YAHOO.util.Dom.get( 'f-step-1' );
            if( !form ) {
                return;
            }
            this.looksetXMLPath = config.looksetXMLPath;
            this.newAv = config.newAv;
            this.remembering = config.remembering;
            var self = this;
            var bindEvents = function( el ) {
                el =  YAHOO.util.Dom.get( el );
                YAHOO.util.Event.on( el, 'click', self.handleClick, {
                    el : el,
                    self : self
                } );
            };
            var previous =  YAHOO.util.Dom.getElementsByClassName( 'previous', 'span' );
            for( var i = 0, el; el = previous[i]; i++ ) {
                bindEvents( el );
            }
            var next =  YAHOO.util.Dom.getElementsByClassName( 'next', 'span' );
            for( var i = 0, el; el = next[i]; i++ ) {
                bindEvents( el );
            }
            this.fetchData( self );
        },
        handleClick : function( e, obj ) {
            var el = obj.el;
            var tuneAmount = el.className == 'next' ? 1 : -1;
            var tuneType = function() {
                var id = el.parentNode.id.toUpperCase();
                return id.replace( /F-/gi, '' );
            }();
            obj.self.tuneAvatar( tuneType, tuneAmount );
        },
        fetchData : function( obj ) {
            var uri = '/signup/lookset_parser.php?looksetXML=' + this.looksetXMLPath;
            var timeout = 2000;
            var callbackFn = function( response ) {
                var regSetRaw = eval( '(' + response + ')' );
                obj.processResponse( regSetRaw );
            };
            var request = YAHOO.util.Connect.asyncRequest( 'GET', uri, {
                success : function( obj ) {
                    var response = obj.responseText;
                    callbackFn( response );
                },
                failure : function( obj ) {},
                timeout : timeout
            } );
        },
        processResponse : function( regSetRaw ) {
            this.flattenData( regSetRaw );
            if( this.remembering != '' ) {
                this.pointers = eval( '(' + this.remembering + ')' );
                this.updateAvatar(); // is this necessary?
                var gender = ( this.pointers['AVATAR'] == 0 ) ? 'f' : 'm';
                IMVU.Registration.GenderSelection.checkElement( gender );
            }
            this.dataLoaded = true;
        },
        flattenData : function( regSetRaw ) {
            var curAvatarArray = {};
            var avatar = regSetRaw['REGSET']['AVATAR'];
            for( var i = 0, av; av = avatar[i]; i++ ) {
                var curAvatar = av;
                var avatarTuneArray = {};
                var avatarTunePointers = { 'AVATAR' : 0 };
                for( var j in curAvatar ) {
                    var tunesetArray = [];
                    var tunesetPointers = 0;
                    if ( j == 'BASIC' ) {
                        tunesetArray[0] = curAvatar[j]['ATTRIBUTES']['NAME'];
                    } else {
                        for( var k in curAvatar[j] ) {
                            tunesetArray[k] = curAvatar[j][k]['ATTRIBUTES']['NAME'];
                        }
                    }
                    avatarTuneArray[j] = tunesetArray;
                    avatarTunePointers[j] = tunesetPointers;
                }
                curAvatarArray[i] = avatarTuneArray;
            }
            this.regSet = curAvatarArray;
            this.pointers = avatarTunePointers;
            // now preload the first two images
            this.preloadInitialAvatar();
        },
        tuneAvatar : function( tuneType, tuneAmount ) {
            if( this.newAvatar ) {
                IMVU.Registration.GenderSelection.checkElement( 'f' );
                this.newAvatar = false;
            } else {
                this.pointers[tuneType] = this.pointers[tuneType] + tuneAmount + this.regSet[this.pointers['AVATAR']][tuneType].length;
                this.pointers[tuneType] = this.pointers[tuneType] % this.regSet[this.pointers['AVATAR']][tuneType].length;
            }
            this.updateAvatar();
        },
        chooseAvatar : function( tuneType, index ) {
            if( !this.dataLoaded ) {
                var self = this;
                setTimeout(
                    function() {
                        self.chooseAvatar( tuneType, index );
                    },
                    200
                );
            }
            this.pointers[tuneType] = parseInt( index, 10 );
            this.updateAvatar();
            this.newAvatar = false;
        },
        updateAvatar : function() {
            var self = this;
            var dna = [];
            var avatar = this.regSet[this.pointers['AVATAR']];
            if (! avatar) {
               return;
            }
            disableSubmit();
            // adjust null pointers if needed
            for( var i in avatar ) {
                this.pointers[i] = this.pointers[i] % avatar[i].length;
            }
            for( var i in avatar ) {
                dna.push( avatar[i][this.pointers[i]] );
            }
            var compare = function( a, b ) {
                return a - b;
            };
            dna = dna.join( '_' );
            dna = dna.replace( /null_/gi, '' );
            dna = dna.split( '_' );
            dna = dna.sort( compare );
            dna = dna.join( '_' );
            var imgURI = this.staticImgPath + dna + '.jpeg';
            var defaultImg =  YAHOO.util.Dom.get( 'default-img' );
            var loadImg = function() {
                 YAHOO.util.Dom.setStyle( 'ajax-load', 'display', 'block' );
                var preloader =  YAHOO.util.Dom.get( 'static-img-preloader' );
                preloader.src = imgURI;
                preloader.onload = function() {
                     YAHOO.util.Dom.setStyle( 'ajax-load', 'display', 'none' );
                    self.avatarPreviewCounter++;
                    var insertImg = document.createElement( 'img' );
                    insertImg.id = 'insert-image-' + self.avatarPreviewCounter;
                    insertImg.className = 'insert-image';
                    insertImg.src = preloader.src;
                     YAHOO.util.Dom.get( 'avatar-model' ).appendChild( insertImg );
                    var fi = new YAHOO.util.Anim( insertImg.id, { opacity: { from: 0, to: 1 } }, 0.3, YAHOO.util.Easing.easeIn );
                    fi.animate();
                    fi.onComplete.subscribe(
                        function() {
                             YAHOO.util.Dom.setStyle( defaultImg, 'display', 'none' );
                            var previousImg =  YAHOO.util.Dom.get( 'insert-image-' + ( self.avatarPreviewCounter -1 ));
                            if( previousImg ) {
                                 YAHOO.util.Dom.get( 'avatar-model' ).removeChild( previousImg );
                            }
                            enableSubmit();
                        }
                    );
                };
            }();
             YAHOO.util.Dom.get( 'f-dna' ).value = dna;
             YAHOO.util.Dom.get( 'f-pointers' ).value = JSON.stringify( this.pointers );
        },
        preloadInitialAvatar : function() {
            var avatars = [
                '80_133_12458_13984_47721_50748_61995_533046_554784_644222.jpeg',
                '138_191_265_12131_14096_109675_333682_349905.jpeg'
            ];
            for( var i = 0, src; img = avatars[i]; i++ ) {
                var img = new Image();
                img.src = this.staticImgPath + avatars[i];
            }
        }
    }
}();
IMVU.Registration.StarterPack = new function() {
    var pids = [];
    var selectedPid = null;
    var selectedPidIndex = 0;
    var TOTAL_ITEMS = 0;
    var item = 1;
    var by = 814;
    var jumpStack = {};
    var jumping = false;
    var updateControls = function() {
        if( item == 1 ) {
             YAHOO.util.Dom.setStyle( 'pagination', 'background-position', '0px 0px' );
             YAHOO.util.Dom.setStyle( 'sp-previous', 'visibility', 'hidden' );
        }
        if( item > 1 ) {
             YAHOO.util.Dom.setStyle( 'pagination', 'background-position', '0px -48px' );
             YAHOO.util.Dom.setStyle( 'sp-previous', 'visibility', 'visible' );
        }
        if( item < TOTAL_ITEMS ) {
             YAHOO.util.Dom.setStyle( 'sp-next', 'visibility', 'visible' );
        }
        if( item == TOTAL_ITEMS ) {
             YAHOO.util.Dom.setStyle( 'pagination', 'background-position', '0px -96px' );
             YAHOO.util.Dom.setStyle( 'sp-next', 'visibility', 'hidden' );
        }
    };
    var move = function( pArray, duration, easing ) {
        if (! duration) {
            duration = .7;
        }
        if (! easing) {
            easing = YAHOO.util.Easing.easeOutStrong;
        }
        var timer = {};
        var o = new YAHOO.util.Motion( 'items', { points : { by : pArray }}, duration, easing );
        o.onStart.subscribe(
            function() {
                jumping = true;
                 YAHOO.util.Dom.addClass( 'btn-submit', 'disabled' );
                timer = setTimeout(
                    function() {
                         YAHOO.util.Dom.removeClass( 'btn-submit', 'disabled' );
                    },
                    300
                );
            }
        );
        o.onComplete.subscribe(
            function() {
                jumping = false;
                clearTimeout( timer );
            }
        );
        o.animate();
    };
    var updateViewToCurrentPack = function() {
        var screen = selectedPidIndex * by;
         YAHOO.util.Dom.setStyle('items', 'left', (-screen) + 'px');
         YAHOO.util.Dom.batch( jumpStack, function( el ) {
            el.className = '';
        } );
        item += selectedPidIndex;
         YAHOO.util.Dom.get( 'wrp' ).value = pids[item-1];
         YAHOO.util.Dom.addClass( jumpStack[item-1], 'active' );
        updateControls();
    };
    this.init = function( config ) {
        var form =  YAHOO.util.Dom.get( 'f-step-2' );
        if( !form ) {
            return;
        }
        pids = config.pids;
        selectedPid = config.selectedPid;
        selectedPidIndex = parseInt( config.selectedPidIndex, 10 );
        TOTAL_ITEMS = pids.length;
         YAHOO.util.Dom.get( 'wrp' ).value = pids[0];
        if( selectedPid != -1 ) {
            updateViewToCurrentPack();
        }
        YAHOO.util.Event.on( 'sp-next', 'click', function() {
            if ( jumping || item == TOTAL_ITEMS ) {
                return;
            }
            move( [-by, 0] );
             YAHOO.util.Dom.batch( jumpStack, function( el ) {
                el.className = '';
            } );
            ++item;
             YAHOO.util.Dom.get( 'wrp' ).value = pids[item-1];
             YAHOO.util.Dom.addClass( jumpStack[item-1], 'active' );
            updateControls();
        } );
        YAHOO.util.Event.on( 'sp-previous', 'click',
            function() {
                if ( jumping || item == 1 ) {
                    return;
                }
                move( [by, 0] );
                 YAHOO.util.Dom.batch( jumpStack, function( el ) {
                    el.className = '';
                } );
                --item;
                 YAHOO.util.Dom.get( 'wrp' ).value = pids[item-1];
                 YAHOO.util.Dom.addClass( jumpStack[item-1], 'active' );
                updateControls();
            }
        );
        setTimeout(function() {
            if ( item == 1 && selectedPid == -1 ) {
                var pos = -((item-1) * by) - 400;
                 YAHOO.util.Dom.setStyle('items', 'left', pos+'px');
                 YAHOO.util.Dom.setStyle('pagination', 'opacity', 0);
                 YAHOO.util.Dom.setStyle('pagination', 'visibility', 'visible');
                var fade = new YAHOO.util.Anim( 'pagination', { opacity : { to : 1 }}, 1, YAHOO.util.Easing.easeIn );
                move ([(400), 0], 1, YAHOO.util.Easing.bounceOut);
                fade.animate();
            } else {
                 YAHOO.util.Dom.setStyle('pagination', 'visibility', 'visible');
            }
        }, 0);
    };
};

IMVU.Registration.ValidateAvatarCustomization = function() {
    // if there is an error in any of the fields,
    // one idea is to make the field pulse with an
    // error treatment
    
    var form =  YAHOO.util.Dom.get( 'f-step-1' );
    if( !form ) {
        return;
    }
    this.validate = function() {
        var gError = IMVU.Registration.Global.Error;
        var toggleFieldErrors = {
            on : function( name, msg ) {
                var el =  YAHOO.util.Dom.get( name );
                var id = name.replace( /-msg/gi, '' );
                el.innerHTML = msg;
                 YAHOO.util.Dom.addClass( id, 'taken' );
                gError.add( id );
            },
            off : function( name ) {
                var el =  YAHOO.util.Dom.get( name );
                var id = name.replace( /-msg/gi, '' );
                el.innerHTML = '';
                 YAHOO.util.Dom.removeClass( id, 'taken' );
                gError.clear( id );
            }
        };
        var gender = function() {
            var radio =  YAHOO.util.Dom.get( 'avatar-gender' ).getElementsByTagName( 'input' );
            var checked = false;
            for( var i = 0, el; el = radio[i]; i++ ) {
                if( el.checked ) {
                    checked = true;
                }
            }
            if( !checked ) {
                toggleFieldErrors.on( 'avatar-gender-msg', 'Please select a gender' );
                return;
            }
            toggleFieldErrors.off( 'avatar-gender-msg' );
        }();
        var avatarName = function() {
            var input =  YAHOO.util.Dom.get( 'f-avatarname' );
            if( input.value == '' ) {
                toggleFieldErrors.on( 'avatar-name-msg', 'Please enter an avatar name' );
                return;
            }
            if( gError.check( 'avatar-name' )) {
                toggleFieldErrors.on( 'avatar-name-msg', 'Avatar name is already registered' );
                return;
            }
            toggleFieldErrors.off( 'avatar-name-msg' );
        }();
        
        if( gError.get() ) {
            return false;
        }
        return true;
    };
    this.submit = function() {
         YAHOO.util.Dom.get( 'btn-submit' ).disabled = false;
        form.submit();
    };
    var that = this;
    return { 
        init : function() {
            YAHOO.util.Event.on( form, 'submit',
                    function( e ) {
                        YAHOO.util.Event.stopEvent( e );
                        if(that.validate()) {
                            that.submit();
                        } else {
                            if('' ==  YAHOO.util.Dom.get('f-avatarname').value || IMVU.Registration.Global.Error.check('avatar-name')) {
                                IMVU.Registration.BlinkEffects.run('avatar-name', 3);
                            }
                        }
                    }
                ); 
            },
        isValid : function() {
            return (
                !IMVU.Registration.Global.Error.check('avatar-name') && 
                !IMVU.Registration.Global.Error.check('avatar-gender') &&
                '' !=  YAHOO.util.Dom.get('f-avatarname').value &&
                ( YAHOO.util.Dom.get('f-gender-f').checked ||  YAHOO.util.Dom.get('f-gender-m').checked)
            );
        },
        validate : function() {
            that.validate();
        }
    };
}();

IMVU.Registration.InviteParams = {
    loginExpanded : false,
    email : ''
};

IMVU.Registration.InviteDetermineService = function(emailAddress) {
    var validServices = {
        'gmail.com'         : 'gmail',
        'googlemail.com'    : 'gmail',
        'data.bg'           : 'gmail',
        'mailbox.hu'        : 'gmail',       
        'hotmail.com'       : 'hotmail',
        'hotmail.co.uk'     : 'hotmail',
        'live.com'          : 'hotmail',
        'live.co.uk'        : 'hotmail',
        'yahoo.com'         : 'yahoo',
        'ymail.com'         : 'yahoo',
        'rocketmail.com'    : 'yahoo',
        'yahoo.com'         : 'yahoo',
        'yahoo.com.ar'      : 'yahoo',
        'yahoo.com.au'      : 'yahoo',
        'yahoo.com.br'      : 'yahoo',
        'yahoo.com.cn'      : 'yahoo',
        'yahoo.com.hk'      : 'yahoo',
        'yahoo.com.kr'      : 'yahoo',
        'yahoo.com.my'      : 'yahoo',
        'yahoo.com.au'      : 'yahoo',
        'yahoo.com.no'      : 'yahoo',
        'yahoo.com.ph'      : 'yahoo',
        'yahoo.com.ru'      : 'yahoo',
        'yahoo.com.sg'      : 'yahoo',
        'yahoo.com.es'      : 'yahoo',
        'yahoo.com.se'      : 'yahoo',
        'yahoo.com.tw'      : 'yahoo',
        'yahoo.com.mx'      : 'yahoo',
        'yahoo.be'          : 'yahoo',
        'yahoo.at'          : 'yahoo',
        'yahoo.es'          : 'yahoo',
        'yahoo.se'          : 'yahoo',
        'yahoo.ie'          : 'yahoo',
        'yahoo.ca'          : 'yahoo',
        'yahoo.dk'          : 'yahoo',
        'yahoo.fr'          : 'yahoo',
        'yahoo.de'          : 'yahoo',
        'yahoo.gr'          : 'yahoo',
        'yahoo.it'          : 'yahoo',
        'yahoo.in'          : 'yahoo',
        'yahoo.kr'          : 'yahoo',
        'yahoo.ru'          : 'yahoo',
        'yahoo.tw'          : 'yahoo',
        'yahoo.cn'          : 'yahoo',
        'yahoo.co.in'       : 'yahoo',
        'yahoo.co.uk'       : 'yahoo',
        'yahoo.co.kr'       : 'yahoo',
        'yahoo.co.ru'       : 'yahoo',
        'yahoo.co.tw'       : 'yahoo',
        'yahoo.co.th'       : 'yahoo',
        'sbcglobal.net'     : 'yahoo',
        'aol.com'           : 'aol',
        'aim.com' : 'aol', 'netscape.net' : 'aol', 'aol.in' : 'aol', 'aol.co.uk' : 'aol', 'aol.com.br' : 'aol',
        'aol.de' : 'aol', 'aol.fr' : 'aol', 'aol.nl' : 'aol', 'aol.se' : 'aol', 'aol.es' : 'aol', 'aol.it' : 'aol',
        'bestcoolcars.com' : 'aol', 'car-nut.net' : 'aol', 'crazycarfan.com' : 'aol', 'in2autos.net' : 'aol',
        'intomotors.com' : 'aol', 'motor-nut.com' : 'aol', 'bestjobcandidate.com' : 'aol', 'focusedonprofits.com' : 'aol',
        'focusedonreturns.com' : 'aol', 'ilike2invest.com' : 'aol', 'interestedinthejob.com' : 'aol', 'netbusiness.com' : 'aol',
        'right4thejob.com' : 'aol', 'alwayswatchingmovies.com' : 'aol', 'alwayswatchingtv.com' : 'aol', 'beabookworm.com' : 'aol',
        'bigtimereader.com' : 'aol', 'chat-with-me.com' : 'aol', 'crazyaboutfilms.net' : 'aol', 'crazymoviefan.com' : 'aol',
        'fanofbooks.com' : 'aol', 'games.com' : 'aol', 'getintobooks.com' : 'aol', 'i-dig-movies.com' : 'aol',
        'idigvideos.com' : 'aol', 'iwatchrealitytv.com' : 'aol', 'moviefan.com' : 'aol', 'news-fanatic.com' : 'aol',
        'newspaperfan.com' : 'aol', 'onlinevideosrock.com' : 'aol', 'realitytvaddict.net' : 'aol', 'realitytvnut.com' : 'aol',
        'reallyintomusic.com' : 'aol', 'thegamefanatic.com' : 'aol', 'totallyintomusic.com' : 'aol', 'totallyintoreading.com' : 'aol',
        'totalmoviefan.com' : 'aol', 'tvchannelsurfer.com' : 'aol', 'videogamesrock.com' : 'aol', 'wild4music.com' : 'aol',
        'alwaysgrilling.com' : 'aol', 'alwaysinthekitchen.com' : 'aol', 'besure2vote.com' : 'aol', 'cheatasrule.com' : 'aol',
        'crazy4homeimprovement.com' : 'aol', 'descriptivemail.com' : 'aol', 'differentmail.com' : 'aol', 'easydoesit.com' : 'aol',
        'expertrenovator.com' : 'aol', 'expressivemail.com' : 'aol', 'fanofcooking.com' : 'aol', 'fieldmail.com' : 'aol',
        'fleetmail.com' : 'aol', 'funkidsemail.com' : 'aol', 'games.com' : 'aol', 'getfanbrand.com' : 'aol',
        'i-love-restaurants.com' : 'aol', 'ilike2helpothers.com' : 'aol', 'ilovehomeprojects.com' : 'aol', 'lovefantasysports.com' : 'aol',
        'luckymail.com' : 'aol', 'mail2me.com' : 'aol', 'mail4me.com' : 'aol', 'majorshopaholic.com' : 'aol',
        'news-fanatic.com' : 'aol', 'realbookfan.com' : 'aol', 'scoutmail.com' : 'aol', 'thefanbrand.com' : 'aol',
        'totally-into-cooking.com' : 'aol', 'totallyintocooking.com' : 'aol', 'totallyintoreading.com' : 'aol', 'totalmoviefan.com' : 'aol',
        'volunteeringisawesome.com' : 'aol', 'voluteer4fun.com' : 'aol', 'wayintocomputers.com' : 'aol', 'whatmail.com' : 'aol',
        'when.com' : 'aol', 'wildaboutelectronics.com' : 'aol', 'workingaroundthehouse.com' : 'aol', 'workingonthehouse.com' : 'aol',
        'writesoon.com' : 'aol', 'xmasmail.com' : 'aol', 'alwaysgrilling.com' : 'aol', 'alwaysinthekitchen.com' : 'aol',
        'beahealthnut.com' : 'aol', 'fanofcooking.com' : 'aol', 'ilike2workout.com' : 'aol', 'ilikeworkingout.com' : 'aol',
        'iloveworkingout.com' : 'aol', 'love2exercise.com' : 'aol', 'love2workout.com' : 'aol', 'lovetoexercise.com' : 'aol',
        'realhealthnut.com' : 'aol', 'totalfoodnut.com' : 'aol', 'acatperson.com' : 'aol', 'adogperson.com' : 'aol',
        'bigtimecatperson.com' : 'aol', 'bigtimedogperson.com' : 'aol', 'cat-person.com' : 'aol', 'catpeoplerule.com' : 'aol',
        'dog-person.com' : 'aol', 'dogpeoplerule.com' : 'aol', 'mycatiscool.com' : 'aol', 'fanofcomputers.com' : 'aol',
        'fanoftheweb.com' : 'aol', 'idigcomputers.com' : 'aol', 'idigelectronics.com' : 'aol', 'ilikeelectronics.com' : 'aol',
        'majortechie.com' : 'aol', 'switched.com' : 'aol', 'total-techie.com' : 'aol', 'wayintocomputers.com' : 'aol',
        'wildaboutelectronics.com' : 'aol', 'allsportsrock.com' : 'aol', 'basketball-email.com' : 'aol', 'beagolfer.com' : 'aol',
        'bigtimesportsfan.com' : 'aol', 'crazy4baseball.com' : 'aol', 'futboladdict.com' : 'aol', 'hail2theskins.com' : 'aol',
        'hitthepuck.com' : 'aol', 'iloveourteam.com' : 'aol', 'lovefantasysports.com' : 'aol', 'luvfishing.com' : 'aol',
        'luvgolfing.com' : 'aol', 'luvsoccer.com' : 'aol', 'majorgolfer.com' : 'aol', 'myfantasyteamrocks.com' : 'aol',
        'myfantasyteamrules.com' : 'aol', 'myteamisbest.com' : 'aol', 'redskinsfancentral.com' : 'aol', 'redskinsultimatefan.com' : 'aol',
        'skins4life.com' : 'aol', 'totallyintobaseball.com' : 'aol', 'totallyintobasketball.com' : 'aol', 'totallyintofootball.com' : 'aol',
        'totallyintogolf.com' : 'aol', 'totallyintohockey.com' : 'aol', 'totallyintosports.com' : 'aol', 'ultimateredskinsfan.com' : 'aol',
        'realtravelfan.com' : 'aol', 'totallyintotravel.com' : 'aol', 'travel2newplaces.com' : 'aol', 'icqmail.com' : 'aol'       
    };
    
    var re = /^(.*)@(.*)$/;
    var domain = re.exec(emailAddress);
    return validServices[domain[2]];
}

IMVU.Registration.JiggleInviteUIElements = function() {
    var serviceStyles = ['yahoo','gmail','aol','hotmail'];
    var makeLessOpaque = [];
    var makeOpaque = [];
    for(i = 0; i < serviceStyles.length; i++) {
        if(serviceStyles[i] !=  YAHOO.util.Dom.get("service").value) {
            makeLessOpaque.push(serviceStyles[i]);
        } else {
            makeOpaque.push(serviceStyles[i]);
        }
    }
     YAHOO.util.Dom.setStyle(makeLessOpaque, "opacity", 0.5);
     YAHOO.util.Dom.setStyle(makeOpaque, "opacity", 1);
     YAHOO.util.Dom.setStyle("safety", "display", "block");
    parent. YAHOO.util.Dom.setStyle("invite_arrow_1_wrapper", "opacity", 0.5);
    parent. YAHOO.util.Dom.setStyle("invite_arrow_2", "display", "inline");
    parent. YAHOO.util.Dom.setStyle("step1_text", "display", "none");
    parent. YAHOO.util.Dom.setStyle("step2_text", "display", "block");
};

IMVU.Registration.InviteBehavior = function(target) {
    var me = target;
    if(me.id) {
         YAHOO.util.Dom.get("service").value = me.id;
    } else if('' != IMVU.Registration.InviteParams.email) {
        var service = IMVU.Registration.InviteDetermineService(IMVU.Registration.InviteParams.email);
        if(!service) {
            return false;
        }      
         YAHOO.util.Dom.get("service").value = service;
         YAHOO.util.Dom.get("username_" + service).value = IMVU.Registration.InviteParams.email;
    }

    if (IMVU.Registration.InviteParams.loginExpanded) {
        var an_collapse = new YAHOO.util.Anim( 's4-invite-login', { height: { to: 0 } }, .2, YAHOO.util.Easing.easeOut );
        an_collapse.animate();
        an_collapse.onComplete.subscribe(
          function() {
            var an = new YAHOO.util.Anim( 's4-invite-login', { height: { to: 280 } }, .7, YAHOO.util.Easing.bounceOut );
             YAHOO.util.Dom.setStyle(['login_yahoo','login_gmail','login_aol','login_hotmail'], "display", "none");
             YAHOO.util.Dom.get("login_" +  YAHOO.util.Dom.get("service").value).style.display = "block";
            an.animate();
            an.onComplete.subscribe(
                function() {
                    IMVU.Registration.InviteParams.loginExpanded = true;
                }
            );
            }
        );
    } else {
        var an = new YAHOO.util.Anim( 's4-invite-login', { height: { to: 280 } }, .7, YAHOO.util.Easing.bounceOut );
         YAHOO.util.Dom.setStyle(['login_yahoo','login_gmail','login_aol','login_hotmail'], "display", "none");
         YAHOO.util.Dom.get("login_" +  YAHOO.util.Dom.get("service").value).style.display = "block";
        an.onComplete.subscribe(
            function() {
                IMVU.Registration.InviteParams.loginExpanded = true;
            }
        );
        an.animate();
    }
    IMVU.Registration.JiggleInviteUIElements();
};



IMVU.Registration.invite_panel_loaded = false;
IMVU.Registration.Invite = new function() {
    this.init = function() {
        YAHOO.util.Event.on( 
            ['yahoo','gmail','aol','hotmail'], 
            'click', 
            function() {
                var that = this;
                IMVU.Registration.InviteBehavior(that);
            }
        );
        
        if('' != IMVU.Registration.InviteParams.email) {
            IMVU.Registration.InviteBehavior('');
        }
    IMVU.Registration.invite_panel_loaded = true;
    };
};


IMVU.Registration.InviteLogin = new function() {
    this.init = function() {
        var login_expanded = false;
        YAHOO.util.Event.on( ['yahoo','gmail','aol','hotmail'], 'click',
            function() {
                var me = this;
                 YAHOO.util.Dom.get("service").value = me.id;
                if (login_expanded) {
                    var an_collapse = new YAHOO.util.Anim( 's4-invite-login', { height: { to: 0 } }, .2, YAHOO.util.Easing.easeOut );
                    an_collapse.animate();
                    an_collapse.onComplete.subscribe(
                      function() {
                        var an = new YAHOO.util.Anim( 's4-invite-login', { height: { to: 180 } }, .7, YAHOO.util.Easing.bounceOut );
                         YAHOO.util.Dom.setStyle(['login_yahoo','login_gmail','login_aol','login_hotmail'], "display", "none");
                         YAHOO.util.Dom.get("login_" + me.id).style.display = "block";
                        an.animate();
                        an.onComplete.subscribe(
                            function() {
                                login_expanded = true;
                            }
                        );
                    }
                    );
                } else {
                    var an = new YAHOO.util.Anim( 's4-invite-login', { height: { to: 180 } }, .7, YAHOO.util.Easing.bounceOut );
                     YAHOO.util.Dom.setStyle(['login_yahoo','login_gmail','login_aol','login_hotmail'], "display", "none");
                     YAHOO.util.Dom.get("login_" + me.id).style.display = "block";
                    an.onComplete.subscribe(
                        function() {
                            login_expanded = true;
                        }
                    );
                    an.animate();
                }
            }
        );
    };
};

IMVU.Registration.BlinkEffects = function() {
    var intervalIds = {};
    
    var blinkBase = function(id) {
        if( YAHOO.util.Dom.hasClass(id, 'taken')) {
             YAHOO.util.Dom.removeClass(id, 'taken');
        } else {
             YAHOO.util.Dom.addClass(id, 'taken');
        }
    };
    
    return {
        stop : function(id) {
            clearInterval(intervalIds[id].interval);
        },
        run : function(id, times) {
            if(null == intervalIds[id]) {
                intervalIds[id] = {};
                intervalIds[id].count = 0;
                intervalIds[id].interval = setInterval(
                        function() {
                            blinkBase(id);
                            intervalIds[id].count++;
                            if(intervalIds[id].count >= 2*times) {
                                clearInterval(intervalIds[id].interval);
                                intervalIds[id] = null;
                            }
                        }, 
                        200
                    );
                }
        }
    };  
}();

IMVU.Registration.NextButton = function() {
    var on = function() {
         YAHOO.util.Dom.setStyle('btn-submit', 'opacity', '1.0');
         YAHOO.util.Dom.setStyle('btn-submit', 'filter', 'alpha(opacity:100)');
         YAHOO.util.Dom.setStyle('btn-submit', 'cursor', 'pointer');
    };
    var off = function() {
         YAHOO.util.Dom.setStyle('btn-submit', 'opacity', '0.5');
         YAHOO.util.Dom.setStyle('btn-submit', 'filter', 'alpha(opacity:50)');
         YAHOO.util.Dom.setStyle('btn-submit', 'cursor', 'default');
    };
    return {
        toggle : function() {
            IMVU.Registration.ValidateAvatarCustomization.isValid() ? on() : off();
            return true;
        }
    };
}();

IMVU.Registration.getGenderFromDNA = function(dna) {
    var bp = dna.split('_');
    if('80' == bp[0]) {
        return 'f';
    }
    return 'm';
}

