var GaikaiSite = function(){
    
    return {
        
        WEB_DOC_ROOT                        : '/',
        
        newsletterDefaultValue              : 'Enter email address ...',
        wizardCurrentStep                   : 1,
        isRegistrationComplete              : false,
        isKyokaComplete                     : false,
        isDropdownOpen                      : false,
        kyokaFallbackTimer                  : null,
        kyokaFallbackTimeout                : 10000, // milliseconds
        
        init : function(){
            
            this.initLogin(); 
            this.initRegister(); 
            this.initNewsletter(); 
            this.initWizard();
            this.initVideoPlayer();
        },
        
        /**
         * Intializes newsletter signup form
         */
        initNewsletter : function(){
            
            var input                       = $('input.newsletter');
            
            input.attr('value',GaikaiSite.newsletterDefaultValue);
            
            input.focus(function(){
                
                var currentValue            = input.attr('value');
                
                if (currentValue == GaikaiSite.newsletterDefaultValue){
                    $(this).attr('value','');
                }
                
                $(this).addClass('active');
            })
            
            input.blur(function(){
                
                var currentValue            = input.attr('value');
                
                if (currentValue.length == 0){
                    $(this).attr('value',GaikaiSite.newsletterDefaultValue);
                }
                
                $(this).removeClass('active');
            })
        },
        
        /**
         * Initializes registration functionality
         */
        initRegister : function(){
            
            $('.registerLink').click(function(){
                
                $('#tryGaikai .selectedOption').hide();
                
                $('#tryGaikaiWrap').slideToggle('normal',function(){
                    $('#tryGaikai .selectedOption').show();
                });
                
            });
            
            $('#registerButton').click(function(){
                
                $.modal.close();
                $('#tryGaikaiWrap').slideDown();
            })
            
            $('#tryGaikai .selectedOption').click(function(){
                
                if (GaikaiSite.isDropdownOpen === false){
                    
                    GaikaiSite.openDropdown($(this));
                    
                } else {
                    
                    GaikaiSite.closeDropdown();
                }
                
            });
            
            /* userType input is positioned off screen so it can still receive 
             * focus from tabbing between form fields, which then opens a jQuery
             * styled dropdown menu */
            $('#tryGaikai input[name=userType]').focus(function(){
                GaikaiSite.openDropdown($(this));
            });
            
            $('#tryGaikai .dropdown li').click(function(){
                GaikaiSite.selectDropdownOption($(this));
            });
        },
        
        /**
         * Initializes login functionality
         */
        initLogin : function(){
            
            $('.loginLink').click(function(){
                
                $('#loginOverlay').modal({
                    
                    opacity                 : 80,
                    position                : ['15%',null],
                    closeClass              : 'closeOverlay',
                    overlayCss              : {backgroundColor : "#000"}
                });
            });
            
            $('.logoutLink').click(function(){
                GaikaiSite.logout();
            });
            
            $('form[name=loginForm]').submit(function(){
                GaikaiSite.login();
            });
        },
        
        /**
         * Initializes Try Gaikai registration wizard
         */
        initWizard : function(){
            
            $('#tryGaikai a.nextStep').click(function(){
                GaikaiSite.register();
            });
            
            var bg                          = new Image(1500,465); 
            bg.src                          = this.WEB_DOC_ROOT+"/apps/site/common/img/tryGaikai.png"; 
        },
        
        /**
         * Initializes video player overlay
         */
        initVideoPlayer : function() {
            
            $('.launchVideoPlayer').click(function(){
                
                $('#videoPlayerOverlay').modal({
                    
                    opacity                 : 80,
                    position                : ['0',null],
                    overlayCss              : {backgroundColor : "#000"}
                });
            });
        },
        
        /**
         * Logs user into site 
         */
        login : function(){

            var email                       = $('#loginForm input[name=email]').val();
            var password                    = $('#loginForm input[name=password]').val();
            
            if (this.validateLogin(email,password) === true){
                
                $.ajax({
                    type: 'POST',
                    url: GaikaiSite.WEB_DOC_ROOT+'/api/login',
                    data: {
                        'email'             : email,
                        'password'          : password
                    },
                    success: function(result){
                        
                        var success         = result.success;
                        
                        if (success == true){
                            
                            window.location.href = GaikaiSite.WEB_DOC_ROOT+'/demo';
                            
                        } else {
                            
                            alert(result.errorMsg);
                            return false;
                        }
                    },
                    dataType: 'json'
                });
                
                $(this).ajaxError(function(data){

                    alert('Error processing login. Please try again.');
                    return false;
                })
            }
        },
        
        /**
         * Logs user out of site
         */
        logout : function(){
            
            
            $.ajax({
                    type: 'POST',
                    url: GaikaiSite.WEB_DOC_ROOT+'/api/logout',
                    success: function(result){
                        
                        var success         = result.success;
                        
                        if (success == true){
                            
                            top.location.href = GaikaiSite.WEB_DOC_ROOT;
                            
                        } else {
                            
                            alert(result.errorMsg);
                            return false;
                        }
                    },
                    dataType: 'json'
                });
        },
        
        /**
         * Validates email and password
         * 
         * @param string email The email to validate
         * @param string password The password to validate
         * @return boolean
         */
        validateLogin : function(email,password){
            
            if (this.validateEmail(email) === false){
                alert('Invalid email address. Please try again.');
                return false;
            }

            if (password.length === 0){
                alert('Please enter your password.');
                return false;
            }
            
            return true;
        },
        
        /**
         * Validates email address
         * 
         * @param string email The email address to validate
         * @return boolean
         */
        validateEmail : function(email){
            
            if (email.length === 0){
                return false;
            }
            
            var regex                           = /^(([^<>()[\]\\.,;:\+\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ ;
            
            if (!email.match(regex)){
                return false;
            }
            
            return true;
        },
        
        /**
         * Opens wizard's user type dropdown
         * 
         * @param jQuery selectedOption Selected option container
         */
        openDropdown : function(selectedOption){
            
            selectedOption.html('Select category ...');
            
            $('#tryGaikai input[name=userType]').val('');
            
            $('#tryGaikai .dropdownWrap').show();
            
            $('#tryGaikai .dropdown').animate({'margin-top':'0'},500,'easeOutQuart', function(){
                GaikaiSite.isDropdownOpen       = true;
            });
        },
        
        /**
         * Closes wizard's user type dropdown
         */
        closeDropdown : function(){
            
            $('#tryGaikai .dropdown').animate({'margin-top':'-192px'},100,function(){
                
                $('#tryGaikai .dropdownWrap').hide();
                GaikaiSite.isDropdownOpen       = false;
            });
        },
        
        /**
         * Selects option from wizard's user type dropdown
         * 
         * @param jQuery selectedOption Selected option from dropdown
         */
        selectDropdownOption : function(selectedOption){
            
            var thisClass                   = selectedOption.attr('class');
            
            $('#tryGaikai input[name=userType]').val(thisClass);
            $('#tryGaikai .selectedOption').html(selectedOption.html());
            
            this.closeDropdown();
        },
        
        
        /**
         * Moves registration wizard to next step
         */
        wizardNextStep : function(){
            
            var marginLeft                  = this.wizardCurrentStep * 715;
            
            this.wizardCurrentStep++;
            
            /* Update step lights */
            switch (this.wizardCurrentStep){

                case 2:
                
                    if (this.isKyokaComplete == true){
                        this.wizardNextStep();
                        return false;
                    }
                    
                    /* Set fallback timer to proceed to next step in case Kyoka fails/hangs */
                    GaikaiSite.kyokaFallbackTimer = setTimeout('GaikaiSite.kyokaComplete()',GaikaiSite.kyokaFallbackTimeout);
                
                    $('#tryGaikai .stepLights').removeClass('one');
                    $('#tryGaikai .stepLights').addClass('two');
                    
                    break;
                    
                case 3:
                
                    $('#tryGaikai .stepLights').removeClass('two');
                    $('#tryGaikai .stepLights').addClass('three');
                    
                    break;
            }
            
            /* Animate form to next step */
            $('#tryGaikai .wizard').animate({'margin-left':'-'+marginLeft+'px'},500,'easeOutQuart');
            
            /* Hide step one interface elements */
            if (this.wizardCurrentStep > 1){
                $('#tryGaikai a.nextStep').hide();
                $('#tryGaikai .dropdownWrap').hide();
                $('#tryGaikai .selectedOption').hide();
            }
        },
        
        /**
         * Submits user's beta registration
         */
        register : function(){
            
            var email                       = $('#tryGaikai input[name=email]').val();
            var age                         = $('#tryGaikai input[name=age]').val();
            var userType                    = $('#tryGaikai input[name=userType]').val();
            
            if (this.validateRegistration(email,age,userType) === false){
                return false;   
            }
            
            $.ajax({
                type: 'POST',
                url: GaikaiSite.WEB_DOC_ROOT+'/api/register',
                data: {
                    'email'                 : email,
                    'age'                   : age,
                    'userType'              : userType
                },
                success: function(result){
                    
                    var success             = result.success;
                    
                    if (success == false){
                        
                        alert(result.errorMsg);
                        return false;
                    }
                    
                    GaikaiSite.isRegistrationComplete = true;
                    GaikaiSite.wizardNextStep();
                },
                dataType: 'json'
            });
        },
        
        /**
         * Validates the Try Gaikai registration form
         * 
         * @param string email The email address to validate
         * @param integer age The age to validate
         * @param integer userType The userType id to validate
         */
        validateRegistration : function(email,age,userType){
            
            if (this.validateEmail(email) == false){
                alert('Invalid email address. Please try again.');
                return false;
            }
            
            if (!((age - 0) == age && age.length > 0)){
                alert('Invalid age. Please try again.');
                return false;
            }
            
            if (age < 18){
                alert('You must be at least 18 years old to try Gaikai.');
                return false;
            }
            
            if (age > 99){
                alert('You\'re '+age+' years old? Seriously? C\'mon. How old are you, really?');
                return false;
            }
            
            if (userType.length == 0){
                alert('Please select a category that best describes you.');
                return false;
            }
            
            return true;
        },
        
        /**
         * Callback function called by Kyoka once all tests are complete
         */
        kyokaComplete : function(){

            this.isKyokaComplete                                        = true;
            
            clearTimeout(GaikaiSite.kyokaFallbackTimer);
            
            $('#tryGaikai .stepLights').addClass('kyokaComplete');
            
            /* If registration is complete and we're waiting on Kyoka to finish,
             * we can proceed to the next step */
            if (this.isRegistrationComplete == true){
                this.wizardNextStep();
            }
        },

        removeFilter : function(element){
            
            if (element.style.filter && element.style.removeAttribute){
                element.style.removeAttribute('filter');
            }
        }
    }
}();

function playerClosePlayerWindow() {
    $.modal.close();
}
