
(function ($) {
    function RegisterLoginController() {
        // Set default properties.
        this.name = ("registerLoginController-" + (new Date()).getTime());
        this.dialogRetrieved = false;
        this.linkAccountDialogRetrieved = false;
        // The Starz AJAX Service Path
        this.servicePath = AppVars.RegisterServiceEndpoint;
        this.debug = true;

    }
    //--------------------------------------------------------------------------//
    // Check if Screen Name Exists
    //----------------------------------//
    RegisterLoginController.prototype.DoesScreenNameExist = function (screenName) {
        var ScreenNameExist;
        ScreenNameExistRunning = true;
        if (jQuery.trim(screenName) == "") {
            ScreenNameExistRunning = false;
            jQuery("#RegScreenName").addClass("error");
            jQuery("#RegScreenName").parent().validate().showLabel(jQuery("#RegScreenName"), 'This field is required');
        }
        else {
            $.ajax({
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                url: socialController.servicePath + "DoesScreenNameExist",
                data: '{screenName:"' + jQuery.trim(screenName) + '"}',
                timeout: 30000,
                type: 'POST',
                async: false,
                cache: false,
                success: function (response) {
                    var screenNameTaken = response.d;
                    if (screenNameTaken == true) {
                        ScreenNameExist = true;
                        jQuery("#RegScreenName").addClass("error");
                        jQuery("#RegScreenName").parent().validate().showLabel(jQuery("#RegScreenName"), 'Screen name is taken');
                        ScreenNameExistRunning = false;
                    }
                    else {
                        ScreenNameExistRunning = false;
                        ScreenNameExist = false;
                    }

                }
            });
        }
        while (ScreenNameExistRunning == true) {
            setTimeout(function () { }, 1000);
        }
        return ScreenNameExist;
    };
    //------------------------------------------------------------------------ //
    // Login States
    //------------------------------------------------------------------------ //
    // OUT: A user is logged out of both gigya and starz
    // LINKED: A user is logged in to both gigya and starz LINKED
    // UNLINKED: A user is logged in to both gigya and starz UNLINKED
    // GIGYA: A user is logged in to gigya only
    // STARZ: A user is logged in to starz only
    // LINKKING: A linked user just logged into gigya, and is now being auto logged into starz
    // DISCONNECTED: A user has previously linked an account, and has now removed all connections via editConnectionsUI plugin ( but hasn't removed the link ! )
    RegisterLoginController.prototype.states = {
        OUT: 0,
        STARZ: 1,
        GIGYA: 2,
        LINKED: 3,
        UNLINKED: 4,
        LINKING: 5,
        DISCONNECTED: 6
    };

    //------------------------------------------------------------------------ //
    // Logout States
    //------------------------------------------------------------------------ //
    // BOTH: A user is logged into of both gigya and starz and now needs to logout of both
    // GIGYA: A user is logged in to gigya only and only needs to logout of gigya
    // STARZ: A user is logged in to starz only and only needs to logout of starz
    RegisterLoginController.prototype.logoutStates = { BOTH: 0, STARZ: 1, GIGYA: 2 };
    RegisterLoginController.prototype.currentLogoutType = { BOTH: 0, STARZ: 1, GIGYA: 2 };

    // ----------------------------------------------------------------------- //
    // Console Logging
    // ----------------------------------------------------------------------- //
    RegisterLoginController.prototype.consoleLog = function (logTxt) {
        if (window.console != undefined && this.debug == true) {
            console.log(logTxt);
        }
    };

    // ----------------------------------------------------------------------- //
    // Setup Listeners
    // ----------------------------------------------------------------------- //
    RegisterLoginController.prototype.setupListeners = function () {
        $("#login_link, .regLoginLink").live("click", function (event) {
            event.preventDefault();
            if (!registerLoginController.isLoggedIntoStarz()) {
                registerLoginController.showRegisterLogin("");

            }
            else {
                window.location = "/My-Starz/myaccount";
            }
        });
    };

    // ----------------------------------------------------------------------- //
    // Get Parameter By Name
    // ----------------------------------------------------------------------- //
    RegisterLoginController.prototype.getParameterByName = function (name) {
        name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
        var regexS = "[\\?&]" + name + "=([^&#]*)";
        var regex = new RegExp(regexS);
        var results = regex.exec(window.location.href);
        if (results == null)
            return "";
        else
            return decodeURIComponent(results[1].replace(/\+/g, " "));
    };

    // ----------------------------------------------------------------------- //
    // Show Register Login
    // ----------------------------------------------------------------------- //
    RegisterLoginController.prototype.showRegisterLogin = function (eventObj) {
        if (this.dialogRetrieved) {
            this.showDialog();
        }
        else {
            this.getRegisterLoginView(eventObj);

        }
    };

    // ----------------------------------------------------------------------- //
    // Add Logout and My Starz
    // ----------------------------------------------------------------------- //
    RegisterLoginController.prototype.addLogoutMyStarz = function () {
        $("#LoginBug").html("");
        var codeToInject = '<a id="logout" href="#">Logout</a><span class="separator">|</span><a href="/My-Starz/myaccount">My STARZ</a>';
        $("#LoginBug").html(codeToInject);
        registerLoginController.addLogoutListener();
    };

    // ----------------------------------------------------------------------- //
    // Not yet linked logout
    // ----------------------------------------------------------------------- //
    RegisterLoginController.prototype.addLogoutMyStarzLink = function () {
        $("#LoginBug").html("");
        var codeToInject = '<a id="logout" href="#">Logout</a><span class="separator">|</span><a id="link_accounts" href="#">Link Accounts</a><span class="separator">|</span><a href="/My-Starz/myaccount">My STARZ</a>';
        $("#LoginBug").html(codeToInject);
        registerLoginController.addLogoutListener();
        registerLoginController.addLinkAccountsListener();
    };

    // ----------------------------------------------------------------------- //
    // Logout Listener
    // ----------------------------------------------------------------------- //
    RegisterLoginController.prototype.addLogoutListener = function () {
        $("#logout").click(function (event) {
            event.preventDefault();
            registerLoginController.logout();
        });
    };

    // ----------------------------------------------------------------------- //
    // Link Accounts Listener
    // ----------------------------------------------------------------------- //
    RegisterLoginController.prototype.addLinkAccountsListener = function () {
        $("#link_accounts").click(function (event) {
            event.preventDefault();
            registerLoginController.showLinkAccount();
        });
    };

    // ----------------------------------------------------------------------- //
    // Logout 
    // ----------------------------------------------------------------------- //
    RegisterLoginController.prototype.logout = function (action) {

        var tState = this.getLoginState();

        switch (tState) {

            case this.states.OUT:
                // no need to logout
                if (action == "force_reload") {
                    window.location.href = "/";
                }
                break;

            case this.states.LINKED:
            case this.states.UNLINKED:
            case this.states.LINKING:
            case this.states.DISCONNECTED:
                // need to logout of both
                this.currentLogoutType = registerLoginController.logoutStates.BOTH
                registerLoginController.logoutOfGigya();
                break;

            case this.states.GIGYA:
                // need to logout of gigya only
                this.currentLogoutType = registerLoginController.logoutStates.GIGYA
                registerLoginController.logoutOfGigya();
                break;

            case this.states.STARZ:
                // need to logout of starz only
                this.currentLogoutType = registerLoginController.logoutStates.STARZ
                registerLoginController.logoutOfStarz();
                break;

            default:
                break;

        }
    };

    // ----------------------------------------------------------------------- //
    // Logout out of Gigya
    // ----------------------------------------------------------------------- //
    RegisterLoginController.prototype.logoutOfGigya = function () {
        $('#Container').block();
        gigya.services.socialize.logout(socialController.conf, { callback: registerLoginController.logoutCallBack, forceProvidersLogout: true });
    };

    // ----------------------------------------------------------------------- //
    // Logout of Gigya Call Back
    // ----------------------------------------------------------------------- //
    RegisterLoginController.prototype.logoutCallBack = function (response) {
        if (response.errorCode == 0) {
            if (registerLoginController.currentLogoutType == registerLoginController.logoutStates.BOTH) {
                // now log the user out of starz
                registerLoginController.logoutOfStarz();
            }
            else {
                window.location.href = "/";
            }

        }
        else {
            //alert('Error :' + response.errorMessage);
            alert("We were unable to log you out at this time.");
            $('#Container').unblock();
        }

    };

    // ----------------------------------------------------------------------- //
    // Log Out of Starz
    // ----------------------------------------------------------------------- //
    RegisterLoginController.prototype.logoutOfStarz = function () {
        if (registerLoginController.currentLogoutType == registerLoginController.logoutStates.STARZ) {
            $('#Container').block();
        }

        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            url: socialController.servicePath + "Logout",
            success: function (response) {
                if (!response) return;
                if (response.d == true) {
                    window.location.href = "/";
                }
                else {
                    alert("We were unable to log you out at this time.");
                    $('#Container').unblock();
                }

            },
            error: function (xhr, ajaxOptions, thrownError) {
                // alert(xhr.status);
                // alert(thrownError);
                $('#Container').unblock();
            }
        });
    };

    // ----------------------------------------------------------------------- //
    // Is Logged Into Starz
    // ----------------------------------------------------------------------- //
    RegisterLoginController.prototype.isLoggedIntoStarz = function () {
        return !(masterLoginCookie == null || masterLoginCookie == "");
    };

    // ----------------------------------------------------------------------- //
    // Render The Page Header
    // ----------------------------------------------------------------------- //
    RegisterLoginController.prototype.renderHeader = function () {

        var tState = this.getLoginState();

        switch (tState) {

            case this.states.OUT:
                $("#welcome").html("");
                $("#profile").css("margin-top", "-9px");
                $("#login_link").html("Register/Login");
                $("#profile_name").html("Login with:");
                //$('.search').val("OUT");
                socialController.gigyaShowLoginUI();
                break;

            case this.states.LINKED:
                $("#welcome").html("Welcome");
                $("#profile").css("margin-top", "-14px");
                //$('.search').val("IN Gigya/Starz LINKED");
                this.addLogoutMyStarz();
                socialController.showSocialProfile(socialController.gigyaUser);
                (socialController.isUserConnected()) ? gigya.services.socialize.showAddConnectionsUI(socialController.conf, socialController.loginParams) : socialController.gigyaShowLoginUI();
                break;

            case this.states.UNLINKED:
                $("#welcome").html("Welcome");
                $("#profile").css("margin-top", "-14px");
                //$('.search').val("IN Gigya/Starz UNLINKED");
                this.addLogoutMyStarzLink();

                if (socialController.isUserConnected()) {
                    socialController.showSocialProfile(socialController.gigyaUser);
                }
                else {
                    socialController.hideSocialProfile();
                }

                (socialController.isUserConnected()) ? gigya.services.socialize.showAddConnectionsUI(socialController.conf, socialController.loginParams) : socialController.gigyaShowLoginUI();
                break;

            case this.states.LINKING:
                $('#Container').block();
                $("#welcome").html("Welcome");
                $("#profile").css("margin-top", "-14px");
                $("#LoginBug").html("Please Wait...");
                //$('.search').val("IN Gigya/LINKING");                
                break;

            case this.states.GIGYA:
                $("#welcome").html("Welcome");
                $("#profile").css("margin-top", "-14px");
                $("#LoginBug").html('<a id="logout" href="#">Logout</a><span class="separator">|</span><a id="login_link" href="#">Register/Link Account</a>');
                this.addLogoutListener();
                //$('.search').val("IN Gigya");
                socialController.showSocialProfile(socialController.gigyaUser);
                (socialController.gigyaUser.isConnected) ? gigya.services.socialize.showAddConnectionsUI(socialController.conf, socialController.loginParams) : socialController.gigyaShowLoginUI();
                break;

            case this.states.DISCONNECTED:
            case this.states.STARZ:
                $("#welcome").html("");
                $("#profile").css("margin-top", "-9px");
                //$('.search').val("IN Starz");
                $("#profile_name").html("Login with:");
                this.addLogoutMyStarz();
                socialController.gigyaShowLoginUI();

                // DISCONNECTED USERS WILL STILL SEE THE PROFILE PIC WTF??
                $("#profile_image").hide();

                break;

            default:
                // wtf?
                break;

        }
    };

    // ----------------------------------------------------------------------- //
    // Show Dialog After Gigya Login
    // ----------------------------------------------------------------------- //
    RegisterLoginController.prototype.renderDialogOnGiyaLogin = function (user) {

        //After a gigya login event only these 2 states require a dialog to popup.

        switch (this.getLoginState()) {
            case this.states.UNLINKED:
                this.showLinkAccount();
                break;
            case this.states.GIGYA:
                this.showRegisterLogin(user);
                break;
            default:
                break;
        }
    };

    // ----------------------------------------------------------------------- //
    // Sha1 The password
    // ----------------------------------------------------------------------- //
    RegisterLoginController.prototype.sha1 = function (email, password) {
        var emailPassword = email.trim().toUpperCase() + password.trim().toUpperCase();
        var sha1 = $().crypt({ method: "sha1", source: emailPassword });
        return "0x" + sha1.toUpperCase();
    };

    // ----------------------------------------------------------------------- //
    // Handle Modal Register Login for Use Case
    // ----------------------------------------------------------------------- //
    RegisterLoginController.prototype.handleModalRegisterLoginForLoginState = function (loginState) {
        // case1: A user is logged out of both gigya and starz
        // case2: A user is logged in to both gigya and starz LINKED
        // case3: A user is logged in to both gigya and starz UNLINKED
        // case4: A user is logged in to gigya only
        // case5: A user is logged in to starz only
        switch (loginState) {
            case this.states.OUT:
                $(".modal_login h5").html("LOGIN");
                $("#login_button span").html("LOGIN");
                $("#register_button span").html("REGISTER");
                $("#reg_login_info").show();
                $("#reglink_loginlink_info").hide();
                $("#login_note").show();
                $("#loginlink_note").hide();
                $("#privacy_note").show();
                $("#privacylink_note").hide();
                $("#skip").hide();
                $(".modal_registration .submit").css("margin-left", "120px");
                $("#dialog-form").dialog("option", "height", 550);
                $("#terms_checkbox_holder").hide();
                var modalTracking = new ModalTracking();
                modalTracking.ModalDialogOpen();
                break;
            case this.states.LINKED:
                break;
            case this.states.UNLINKED:
                break;
            case this.states.GIGYA:
                $(".modal_login h5").html("LINK ACCOUNTS");
                $(".modal_login .default_button span").html("LINK ACCOUNTS");
                $(".modal_registration h5").html("REGISTER &amp; LINK ACCOUNTS");
                $("#register_button span").html("REGISTER &amp; LINK ACCOUNTS");
                $("#reg_login_info").hide();
                $("#reglink_loginlink_info").show();
                $("#login_note").hide();
                $("#loginlink_note").show();
                $("#privacy_note").hide();
                $("#privacylink_note").show();
                $("#skip").show();
                $(".modal_registration .submit").css("margin-left", "0px");
                $("#dialog-form").dialog("option", "height", 630);
                $("#terms_checkbox_holder").show();
                break;
            case this.states.STARZ:
                break;
            default:
                break;

        }

    };

    // ----------------------------------------------------------------------- //
    // Get Use Case
    // ----------------------------------------------------------------------- //
    RegisterLoginController.prototype.getLoginState = function () {
        // case1: A user is logged out of both gigya and starz
        if (!this.isLoggedIntoStarz() && !socialController.isLoggedIntoGigya()) {
            return this.states.OUT;
        }

        // case2: A user is logged in to both gigya and starz LINKED
        if (socialController.isLoggedIntoGigya() && socialController.isUserLinked() && socialController.isUserConnected()) {
            if (this.isLoggedIntoStarz()) {
                return this.states.LINKED;
            }
            else {
                socialController.isUserKnown(socialController.gigyaUser);
                return this.states.LINKING;
            }
        }

        // case3: A user is logged in to both gigya and starz UNLINKED
        if (this.isLoggedIntoStarz() && socialController.isLoggedIntoGigya() && !socialController.isUserLinked()) {
            return this.states.UNLINKED;
        }

        // case4: A user is logged in to gigya only
        if (!this.isLoggedIntoStarz() && socialController.isLoggedIntoGigya()) {
            return this.states.GIGYA;
        }

        // case5: A user is logged in to starz only
        if (this.isLoggedIntoStarz() && !socialController.isLoggedIntoGigya()) {
            return this.states.STARZ;
        }

        // case6: A user is logged into starz and gigya, but has removed all connections
        if (socialController.isLoggedIntoGigya() && !socialController.isUserConnected()) {
            return this.states.DISCONNECTED;
        }

        // case?: we have no idea what kind of user this is...
        return "unknown";
    };

    // ----------------------------------------------------------------------- //
    // Show Link Account Dialog
    // ----------------------------------------------------------------------- //
    RegisterLoginController.prototype.showLinkAccount = function (eventObj) {
        if (this.linkAccountDialogRetrieved) {
            this.showLinkAccountDialog();

        }
        else {
            this.getLinkAccountView();
        }
    };

    // ----------------------------------------------------------------------- //
    // Get Link Account View
    // ----------------------------------------------------------------------- //
    RegisterLoginController.prototype.getLinkAccountView = function () {
        // we are getting two login handlers from gigya if the user shares before they login
        registerLoginController.linkAccountDialogRetrieved = true;
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            url: socialController.servicePath + "GetLinkAccountView",
            success: function (response) {
                $("#dialog-form-holder").html(response.d);
                $("#dialog-form").dialog({ title: "Link STARZ Account", width: 485, height: 160, modal: true, opacity: .9 });
                registerLoginController.linkAccountDialogRetrieved = true;
                registerLoginController.setupLinkAccountListeners();
            },
            error: function (xhr, ajaxOptions, thrownError) {
                registerLoginController.linkAccountDialogRetrieved = false;
                // alert(xhr.status);
                // alert(thrownError);
            }
        });
    };

    // ----------------------------------------------------------------------- //
    // Setup Link Account Listeners
    // ----------------------------------------------------------------------- //
    RegisterLoginController.prototype.setupLinkAccountListeners = function () {
        $("#link_account").click(function () {
            socialController.autoLinkAccount();
        });

        $("#dont_link_account").click(function () {
            $("#dialog-form").dialog("close");
        });
    };

    // ----------------------------------------------------------------------- //
    // Get Register Login View
    // ----------------------------------------------------------------------- //
    RegisterLoginController.prototype.getRegisterLoginView = function () {
        // we are getting two login handlers from gigya if the user shares before they login
        registerLoginController.dialogRetrieved = true;

        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            url: socialController.servicePath + "GetRegisterLoginView",
            success: function (response) {
                $("#dialog-form-holder").html(response.d);

                $("#dialog-form").dialog({ title: "Sign Up For My STARZ", width: 820, height: 630, modal: true, opacity: .9 });

                var loginState = registerLoginController.getLoginState();
                registerLoginController.handleModalRegisterLoginForLoginState(loginState);

                registerLoginController.setupLoginListeners();
                registerLoginController.setupRegisterListeners();
                registerLoginController.dialogRetrieved = true;

                if (socialController.gigyaUser != undefined && socialController.gigyaUser != "") {
                    $('#RegEmail').val(socialController.gigyaUser.email);
                    $('#RegMonth').val(socialController.gigyaUser.birthMonth);
                    $('#RegYear').val(socialController.gigyaUser.birthYear);
                    $('#RegDay').val(socialController.gigyaUser.birthDay);
                    if ($.trim(socialController.gigyaUser.nickName) != "") {
                        $("#RegScreenName").val(socialController.gigyaUser.nickName.substring(0, 15));
                    }
                    else {
                        $("#RegScreenName").val((socialController.gigyaUser.firstName + socialController.gigyaUser.lastName).substring(0, 15));
                    }
                }
                else {
                    $("#RegScreenName").val("");
                    $('#RegEmail').val("");
                    $('#RegMonth').val("1");
                    $('#RegYear').val("1");
                    $('#RegDay').val("1");
                }
            },
            error: function (xhr, ajaxOptions, thrownError) {
                registerLoginController.dialogRetrieved = false;
                // alert(xhr.status);
                // alert(thrownError);
            }
        });
    };

    // ----------------------------------------------------------------------- //
    // Setup Register Listeners
    // ----------------------------------------------------------------------- //
    RegisterLoginController.prototype.setupRegisterListeners = function () {
        $("#modal_registration_form input").keypress(function (event) {
            if (event.keyCode == Event.KEY_RETURN) {
                registerLoginController.register();
            }
        });

        $(".modal_registration .default_button").click(function (event) {
            event.preventDefault();
            registerLoginController.register();
        });

        $("#reg_clear").click(function (event) {
            event.preventDefault();
            registerLoginController.clearRegistrationForm();
        });

        $("#skip").live("click", function (event) {
            $("#dialog-form").dialog("close");
        });
    };

    // ----------------------------------------------------------------------- //
    // Clear Registration Form
    // ----------------------------------------------------------------------- //
    RegisterLoginController.prototype.clearRegistrationForm = function () {
        $("#RegEmail").val("");
        $("#RegPassword").val("");
        $("#RegVerify").val("");
        $("#RegScreenName").val("");
        $('#RegMonth').find('option:first').attr('selected', 'selected').parent('select');
        $('#RegYear').find('option:first').attr('selected', 'selected').parent('select');
        $('#RegDay').find('option:first').attr('selected', 'selected').parent('select');
        $('#newsletter').attr('checked', true);
        $('#terms_of_service_cb').attr('checked', false);
        $("#register_errors").hide();
        $("#modal_registration_form").validate().resetForm();
        $("#RegEmail").focus();

        if (socialController.gigyaUser != undefined && socialController.gigyaUser != "") {
            $('#RegEmail').val(socialController.gigyaUser.email);
            $('#RegMonth').val(socialController.gigyaUser.birthMonth);
            $('#RegYear').val(socialController.gigyaUser.birthYear);
            $('#RegDay').val(socialController.gigyaUser.birthDay);
            if ($.trim(socialController.gigyaUser.nickName) != "")
                $("#RegScreenName").val(socialController.gigyaUser.nickName.substring(0, 15));
            else
                $("#RegScreenName").val((socialController.gigyaUser.firstName + socialController.gigyaUser.lastName).substring(0, 15));
        }

        var loginState = registerLoginController.getLoginState();
        registerLoginController.handleModalRegisterLoginForLoginState(loginState);

    };

    // ----------------------------------------------------------------------- //
    // Register
    // ----------------------------------------------------------------------- //
    RegisterLoginController.prototype.register = function () {
        var referrer = registerLoginController.getParameterByName("referrer");

        if (this.validateRegisterForm()) {
            var gigyaUID = "";
            if (socialController.gigyaUser != null && socialController.gigyaUser != "" && socialController.gigyaUser.isLoggedIn != "") gigyaUID = socialController.gigyaUser.UID;
            var newsletterChecked = $('#newsletter').is(':checked');
            $('#dialog-form').block();
            $("#register_errors").hide();
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                url: socialController.servicePath + "Register",
                data: '{screenName:"' + $("#RegScreenName").val() + '", username:"' + $("#RegEmail").val() + '", password:"' + $("#RegPassword").val() + '", regDay:"' + $("#RegDay").val() + '",regMonth:"' + $("#RegMonth").val() + '",regYear:"' + $("#RegYear").val() + '", gigyaUID:"' + gigyaUID + '", newsletter:' + newsletterChecked.toString() + ', referrer:"' + referrer + '"}',
                success: function (response) {
                    // the user is unknown
                    // display the register or link dialog
                    // failure
                    var errorCode = response.d.errorCode;
                    if (errorCode != 0) {
                        if (response.d.validationErrors) {
                            //resize our window to handle errors
                            $("#dialog-form").dialog("option", "height", 650);
                            var validationErrors = response.d.validationErrors;
                            var errorText = "<ul>";
                            for (var i = 0; i < validationErrors.length; i++) {
                                var errorItem = validationErrors[i];
                                errorText += "<li>" + errorItem + "</li>";
                            }
                            errorText += "</ul>";
                        }
                        if (errorText) {
                            $("#register_errors").html(errorText).show();
                        }
                        else {
                            $("#register_errors").html("An unexpected error occured").show();
                        }
                    }
                    else {
                        if (socialController.gigyaUser.isLoggedIn) {
                            if (response.d.referrer != "") {
                                window.location = response.d.referrer;
                            }
                            else {
                                window.location.reload();

                            }
                        }
                        else {
                            registerLoginController.clearRegistrationForm();
                            $("#register_errors").html("Thanks for registering! A verification email has been sent to the email provided.").show();
                            // now just close the dialog
                            $("#dialog-form").dialog("close");
                            alert("Thanks for registering! A verification email has been sent to the email provided.");
                            // send omniture tracking
                            var tracking = new Tracking();
                            tracking.Register();

                        }

                    }
                    // unblock the UI
                    $('#dialog-form').unblock();
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    $("#register_errors").html("There was an error processing your request").show();
                    $('#dialog-form').unblock();
                    //alert(xhr.status);
                    //alert(thrownError);
                }
            });

        }

    };

    // ----------------------------------------------------------------------- //
    // Validate Register Form
    // ----------------------------------------------------------------------- //
    RegisterLoginController.prototype.validateRegisterForm = function () {
        $("#modal_registration_form").validate().resetForm();
        $("#register_errors").hide();
        if (socialController.isLoggedIntoGigya()) {
            if (!$('#terms_of_service_cb').attr('checked')) {
                $("#register_errors").html("You must agree to the terms of service by selecting the checkbox below").show();
                return false;
            }
        }

        if (this.DoesScreenNameExist(jQuery("#RegScreenName").val())) {
            return false;
        }
        if ($("#modal_registration_form").validate({
            rules: {
                RegPassword: {
                    required: true,
                    minlength: 6
                },
                RegVerify: {
                    required: true,
                    minlength: 6,
                    equalTo: "#RegPassword"
                }

            },
            messages: {
                RegEmail: {
                    required: "Please provide an email"
                },
                RegPassword: {
                    required: "Please provide a password"
                },
                RegVerify: {
                    required: "Please verify your password",
                    equalTo: "Please enter the same password as above"
                }
            }
        }).form()) {
            return true;
        }
        return false;

    };

    // ----------------------------------------------------------------------- //
    // Setup Login Listeners
    // ----------------------------------------------------------------------- //
    RegisterLoginController.prototype.setupLoginListeners = function () {
        $("#modal_login_form input").keypress(function (event) {
            if (event.keyCode == Event.KEY_RETURN) {
                registerLoginController.login();
            }
        });

        $(".modal_login .default_button").click(function (event) {
            event.preventDefault();
            registerLoginController.login();
        });

        $("#login_clear").click(function (event) {
            event.preventDefault();
            registerLoginController.clearLoginForm();
        });
    };

    // ----------------------------------------------------------------------- //
    // Clear Login Form
    // ----------------------------------------------------------------------- //
    RegisterLoginController.prototype.clearLoginForm = function () {
        $("#txtBoxUsername").val("");
        $("#txtBoxPassword").val("");
        $('#rememberMeLogin').attr('checked', true);
        $("#login_errors").hide();
        $("#modal_login_form").validate().resetForm();
        $("#txtBoxUsername").focus();
    };

    // ----------------------------------------------------------------------- //
    // Login
    // ----------------------------------------------------------------------- //
    RegisterLoginController.prototype.login = function () {

        //alert( "login" );

        if (this.validateLoginForm()) {
            var userName = $("#txtBoxUsername").val();
            var password = $("#txtBoxPassword").val();
            var rememberMe = $('#rememberMeLogin').is(':checked');
            var referrer = registerLoginController.getParameterByName("referrer"); // spelled wrong

            var hashed = true;
            if (hashed) {
                password = registerLoginController.sha1(userName, password);
            }

            if (socialController.gigyaUser != null && socialController.gigyaUser != "" && socialController.gigyaUser.isLoggedIn != "") {
                socialController.linkAccount(socialController.gigyaUser, userName, password, true);
            }
            else {
                $('.registration_wrapper').block();
                $("#login_errors").hide();

                $.ajax({
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    url: socialController.servicePath + "Login",
                    data: '{userName:"' + userName + '", password:"' + password + '", rememberMe:' + rememberMe.toString() + ', hashed:' + hashed.toString() + ', referrer:"' + referrer + '"}',
                    success: function (response) {

                        // the user is unknown
                        // display the register or link dialog
                        var errorCode = response.d.errorCode;
                        // failure
                        if (errorCode != 0) {
                            $("#login_errors").html(response.d.errorMsg).show();
                            $('.registration_wrapper').unblock();
                        }
                        else {
                            if (response.d.referrer != "") {
                                window.location = response.d.referrer;
                            }
                            else {
                                window.location.reload();
                            }
                        }

                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        $('.registration_wrapper').unblock();
                        // alert(xhr.status);
                        // alert(thrownError);
                    }
                });
            }
        }

    };

    // ----------------------------------------------------------------------- //
    // Validate Login Form
    // ----------------------------------------------------------------------- //
    RegisterLoginController.prototype.validateLoginForm = function () {
        if ($("#modal_login_form").validate().form()) {
            if ($("#modal_login_form").validate().element("#txtBoxPassword")) return true;
        }
        return false;

    };

    // ----------------------------------------------------------------------- //
    // Open Link Account Dialog
    // ----------------------------------------------------------------------- //
    RegisterLoginController.prototype.showLinkAccountDialog = function () {
        if (!$("#dialog-form").dialog("isOpen")) {
            $("#dialog-form").dialog("open");
        }
    };

    // ----------------------------------------------------------------------- //
    // Open Dialog
    // ----------------------------------------------------------------------- //
    RegisterLoginController.prototype.showDialog = function () {
        if (!$("#dialog-form").dialog("isOpen")) {
            $("#dialog-form").dialog("open");
            registerLoginController.clearLoginForm();
            registerLoginController.clearRegistrationForm();
        }
    };

    // ----------------------------------------------------------------------- //
    // Tool Tip Login
    // ----------------------------------------------------------------------- //
    RegisterLoginController.prototype.initializeToolTipLogin = function () {
        $(".tooltip_reg").click(function (event) {
            event.preventDefault();
            if (!registerLoginController.isLoggedIntoStarz()) {
                registerLoginController.showRegisterLogin("");
            }
            else {
                window.location = "/My-Starz/myaccount";
            }
        });

        $("#login-Username").focusin(function (event) {
            if ($(this).val() == "Username") {
                $(this).val("");
            }
        });
        $("#login-Username").focusout(function (event) {
            if ($(this).val() == "") {
                $(this).val("Username");
            }
        });
        $("#fauxPassword").focusin(function (event) {
            $("#fauxPassword").hide();
            $("#realPassword").show();
            $("#realPassword input").focus();
        });
        $("#realPassword input").focusout(function (event) {
            if ($("#realPassword input").val() == "") {
                $("#fauxPassword").show();
                $("#realPassword").hide();
            }
        });
        $("#login-Form").keypress(function (event) {
            if (event.keyCode == Event.KEY_RETURN) {
                registerLoginController.toolTipLogin();
            }
        });

        $("#login-Submit").click(function (event) {
            event.preventDefault();
            registerLoginController.toolTipLogin();
        })

    };

    // ----------------------------------------------------------------------- //
    // Tool Tip Login
    // ----------------------------------------------------------------------- //
    RegisterLoginController.prototype.toolTipLogin = function () {

        var userName = $("#login-Username").val();
        var password = $("#login-Password").val();
        var rememberMe = $('#login-Remember').is(':checked');
        var referrer = registerLoginController.getParameterByName("referrer"); // spelled wrong

        var hashed = true;
        if (hashed) {
            password = registerLoginController.sha1(userName, password);
        }

        if (socialController.gigyaUser != null && socialController.gigyaUser != "" && socialController.gigyaUser.isLoggedIn != "") {
            socialController.linkAccount(socialController.gigyaUser, userName, password, true);
        }
        else {
            $('#tooltip .form').block();

            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                url: socialController.servicePath + "Login",
                data: '{userName:"' + userName + '", password:"' + password + '", rememberMe:' + rememberMe.toString() + ', hashed:' + hashed.toString() + ', referrer:"' + referrer + '"}',
                success: function (response) {

                    // the user is unknown
                    // display the register or link dialog
                    var errorCode = response.d.errorCode;
                    // failure
                    if (errorCode != 0) {
                        $(".prompt p:nth-child(1)").html("");
                        $(".prompt p:nth-child(1)").append('<span class="error">' + response.d.errorMsg + '</span>');
                        $(".prompt p:nth-child(1)").append("Please try logging in again.");
                        $('#tooltip .form').unblock();
                    }
                    else {
                        if (response.d.referrer != "") {
                            window.location = response.d.referrer;
                        }
                        else {
                            window.location.reload();
                        }
                    }

                },
                error: function (xhr, ajaxOptions, thrownError) {
                    $('#tooltip .form').unblock();
                }
            });
        }

    };

    // ----------------------------------------------------------------------- //
    // ----------------------------------------------------------------------- //

    // Create a new instance of the registerLoginController and store it in the window.
    window.registerLoginController = new RegisterLoginController();

    // Return a new registerLoginController instance.
    return (window.registerLoginController);

})(jQuery);

// ----------------------------------------------------------------------- //
// String Prototypes
// ----------------------------------------------------------------------- //

String.prototype.trim = function ()
{
    return this.replace(/^\s+|\s+$/g, "");
}
String.prototype.ltrim = function ()
{
    return this.replace(/^\s+/, "");
}
String.prototype.rtrim = function ()
{
    return this.replace(/\s+$/, "");
}
