﻿$(document).ready(function () {
    //Assign onClick to User Accounts Links
    jQuery.addOnClickToUA = function () {
        $("a.userAccounts_link").each(
	        function () {
	            if (!this.hasEventHander)
	                $(this).mouseover(function () { $(this).addUAClick(); });
	            this.hasEventHander = true;
	        }
        );

        $("a.userAccounts_header").each(
	        function () {
	            if (!this.hasEventHander)
	                $(this).mouseover(function () { $(this).addUAClick(); });
	            this.hasEventHander = true;
	        }
        );

        $("a.LeftNav_userAccounts").each(
	        function () {
	            if (!this.hasEventHander)
	                $(this).mouseover(function () { $(this).addUAClick(); });
	            this.hasEventHander = true;
	        }
        );
    }; // Assign onClick to User Accounts Links

    $.addOnClickToUA();

    jQuery.fn.addUAClick = function () {
        $(this).click(function () {
            $.DisplayAccountsWindow($(this).attr("id"));
        }); // END Click
    }; // END addUAClick

    //Display Accounts Window
    jQuery.DisplayAccountsWindow = function (controlId) {
        var currentDate = new Date();
        $.get("/Handler/RenderControl.aspx", { ctrl: controlId, t: currentDate, refid: webAndEventLogObj.WEB_LOG_referrer_number, detid: webAndEventLogObj.WEB_LOG_detail_number },
            function (controlContent) {
                if (controlContent != "EMPTY") {
                    $("#AccountDivs").css({ "display": "block" });

                    var AccountsDivs = $(controlContent).filter(function () { return $(this).is("div") });

                    //Setup the accounts window to center, grey out the back, etc...
                    $.SetupAccountsWindow(AccountsDivs);

                    //Reposition the accounts div if the window is resized
                    $.resizeAccountsDiv();

                }
                else {
                    $("#AccountDivs").css({ "display": "none" });
                }
            }); // End .get()
    };

    //Setup Accounts Window
    jQuery.SetupAccountsWindow = function (divs) {
        var loadedControl = $(divs[0]).attr("id");

        var divTitleId = loadedControl + "_title";
        var divContentId = loadedControl + "_content";
        var divContentMainId = loadedControl + "_main";
        var divTitle = $(divs[0]).find("#" + divTitleId).html();
        var divContent = $(divs[0]).find("#" + divContentId).html();

        $("#AccountDivs #AccountDivControl_title").html(divTitle);
        $("#AccountDivs #AccountDivControl").html(divContent);

        var divContentObj = $("#" + divContentMainId);
        var divHeaderObj = $("#AccountDivs #divAccountsHeader");
        var divFooterObj = $("#AccountDivs #divAccountsFooter");
        var totalWidth = divContentObj.width();
        var totalHeight = divContentObj.height();
        var headerHeight = divHeaderObj.height();
        var footerHeight = divFooterObj.height();

        $("#AccountDivControl").css({ "width": totalWidth, "min-height": totalHeight });

        //Total Padding Width/Height
        totalWidth += parseInt(divContentObj.css("padding-left"), 10) + parseInt(divContentObj.css("padding-right"), 10);
        totalHeight += parseInt(divContentObj.css("padding-top"), 10) + parseInt(divContentObj.css("padding-bottom"), 10);
        headerHeight += parseInt(divHeaderObj.css("padding-top"), 10) + parseInt(divHeaderObj.css("padding-bottom"), 10);
        footerHeight += parseInt(divFooterObj.css("padding-top"), 10) + parseInt(divFooterObj.css("padding-bottom"), 10);
        //Total Margin Width/Height
        totalWidth += parseInt(divContentObj.css("margin-left"), 10) + parseInt(divContentObj.css("margin-right"), 10);
        totalHeight += parseInt(divContentObj.css("margin-top"), 10) + parseInt(divContentObj.css("margin-bottom"), 10);
        headerHeight += parseInt(divHeaderObj.css("margin-top"), 10) + parseInt(divHeaderObj.css("margin-bottom"), 10);
        footerHeight += parseInt(divFooterObj.css("margin-top"), 10) + parseInt(divFooterObj.css("margin-bottom"), 10);


        var guiWidth = totalWidth + "px";
        var guiHeight = totalHeight + headerHeight + footerHeight + "px";
        var guiHeaderWidth = (totalWidth - 30 - 2) + "px";

        $("#AccountDivControl_GUI").css({ "width": guiWidth, "min-height": guiHeight });
        $("#AccountDivControl_title").css({ "width": guiHeaderWidth });

        $("#AccountDivControl_GUI #divAccountsHeader").css({ "background": "transparent url(/Images/UserAccounts/Layout/userBGtop" + totalWidth + ".png) left no-repeat" });
        $("#AccountDivControl_GUI #divAccountsFooter").css({ "background": "transparent url(/Images/UserAccounts/Layout/userBGbot" + totalWidth + ".png) left no-repeat" });
        $.showAccountControl();
        $(".closeAccountControl").css({ "cursor": "pointer" });
        $(".closeAccountControl").click(function () { $(this).closeCancel() });

        //Defining click events to left nav
        $.defineLeftNavStyles(loadedControl);

        //redefine clicks
        $.addOnClickToUA();

    }; // End SetupAccountsWindow

    //Resize accounts window when main window is resized
    jQuery.resizeAccountsDiv = function () {
        var resizeTimer = null;
        $(window).bind("resize", function () {
            if (resizeTimer) clearTimeout(resizeTimer);
            resizeTimer = setTimeout(fnShowAccountControl, 1);
        });
    }; // End resizeAccountsDiv

    //Define Left Nav Control Styles
    jQuery.defineLeftNavStyles = function (controlName) {
        var CtrlNameArray = controlName.split("_", 2);

        $("#UA_" + CtrlNameArray[1] + ".LeftNav_userAccounts").css({ "font-weight": "bold" });
        //$.addOnClickToUA();
        $("#UA_" + CtrlNameArray[1] + ".LeftNav_userAccounts").css({ "cursor": "default" });
        $("#UA_" + CtrlNameArray[1] + ".LeftNav_userAccounts").unbind("click");
    }; // End showAccountControl

    function getAccountInfoId() {
        this.accountInfoId = new String("UA_AccountInfo");
    }

    //Set up the Account Screen and dialogue
    jQuery.showAccountControl = function () {
        $("#divLoginBackground").resizeToFullScreen();
        $("#AccountDivControl_GUI").setToMiddleOfScreen();
    }; // End showAccountControl

    //Just a repeat function for the setTimeout call
    function fnShowAccountControl() {
        $.showAccountControl();
        return false;
    }

    //Close Control
    jQuery.closeAccountControl = function (closeObj) {
        $("#" + closeObj).css({ "display": "none" });
        return false;
    }; // End closeAccountControl

    jQuery.fn.changeLeftNavStyle = function () {
        $(this).css({ "font-weight": "bold" });
    };

    jQuery.fn.SubmitForm = function () {
        //alert($(this).find("input").not("#__VIEWSTATE,#__EVENTVALIDATION,[type=checkbox]").serialize());

        var myFormType = $(this).attr("action");

        // clear error message
        if (myFormType.toLowerCase().indexOf("requestpassword") > 0) {
            $("#divAccounts_RequestPassword_confirm").css({ "display": "none" });
        }
        if (myFormType.toLowerCase().indexOf("ua_login") > 0) {
            $("#divAccounts_LogIn_Error").css({ "display": "none" });
        }

        var reqList = $(this).find("input.UA_required");
        var isVerified = $.verifyRequired(reqList);

        if (isVerified == true) {
            // Clear all errors
            var errorList = $(this).find(".UA_error_class");
            $.each(errorList, function () {
                $(this).css({ "display": "none" });
            });
            //if this is the register form
            if (myFormType.toLowerCase().indexOf("ua_register") > 0) {
                //Get Registration data, minus the checkboxes
                var RegisterData = $(this).find("input").not("#__VIEWSTATE,#__EVENTVALIDATION,[type=checkbox]").serialize();

                //Add on the checkboxes
                RegisterData += "&" + $(this).find("input[type=checkbox]:checked").serialize();

                //Let's send off the registeration form data

                RegisterData = "reqType=UA_Register&" + RegisterData;
                $.post("/Accounts/Authenticate.aspx", RegisterData, function (data) { $.ParseRegisterReturnData(data, $(this)); }, "text");
            }

            if (myFormType.toLowerCase().indexOf("ua_login") > 0) {
                var loginData = $(this).find("input").not("#__VIEWSTATE,#__EVENTVALIDATION").serialize();
                loginData = "reqType=UA_Login&" + loginData;
                $.post("/Accounts/Authenticate.aspx", loginData, function (data) { $.ParseLoginReturnData(data, $(this)); }, "text");
            }

            if (myFormType.toLowerCase().indexOf("requestpassword") > 0) {
                var loginData = $(this).find("input").not("#__VIEWSTATE,#__EVENTVALIDATION").serialize();
                loginData = "reqType=UA_RequestPassword&" + loginData;
                $.post("/Accounts/Authenticate.aspx", loginData, function (data) { $.ParseReqPassReturnData(data, $(this)); }, "text");
            }
        }

        return false;

    };

    jQuery.deleteAccount = function () {
        var loginData = "reqType=UA_Delete";
        $.post("/Accounts/Authenticate.aspx", loginData, function (data) { $.parseDeleteAccount(data); }, "text");
    };

    jQuery.parseDeleteAccount = function (ReturnData) {
        if (ReturnData != null || ReturnData != "") {
            var returnCode = ReturnData;
            if (returnCode == "true") {
                $.DisplayAccountsWindow("UA_CancelMembership");
            }
        }
    };


    jQuery.ParseRegisterReturnData = function (ReturnData, submittedForm) {
        if (ReturnData != null || ReturnData != "") {
            //alert(ReturnData);
            var returnCode = ReturnData;
            if (returnCode == "true") {
                $.DisplayAccountsWindow("UA_RegisterConfirm");
                var userEmail = $(submittedForm + "input.UA_required[id*='email']").val();
                setTimeout(function () { $("#div_UAConfirmationEmail").html(userEmail) }, 1000);
            }
            else {
                $("#AccountDivs #error_info #error_info_text").text(ReturnData);
                $("#AccountDivs #error_info").css({ "display": "" });

            }
        }
    };

    jQuery.ParseLoginReturnData = function (ReturnData, submittedForm) {
        if (ReturnData != null || ReturnData != "") {
            $("#divAccounts_LogIn_Error").css({ "display": "" });
            var returnCode = ReturnData;
            if (returnCode == "true") {
                if (location.href.indexOf('show_login') >= 0) {
                    var querystring = "";
                    querystring = location.href.substring(location.href.indexOf("?"));
                    // check if search related
                    if (location.href.indexOf('sid=') >= 0) {
                        location = "/search.aspx" + querystring;
                    }
                    else {
                        location = "/Accounts/Account-Information.aspx" + querystring;
                    }
                }
                else {
                    location.reload();
                }
            }
            else {
                var emailField = $(submittedForm + "input.UA_required[id*='email']").attr("id");
                var passField = $(submittedForm + "input.UA_required[id*='password']").attr("id");

                var divEmailError = emailField + "_error";
                var divPassError = passField + "_error";

                $("#" + emailField).focus();

                $("#" + emailField).css({ "background-color": "#fcc" });
                $("#" + passField).css({ "background-color": "#fcc" });
                $("#" + divEmailError).css({ "display": "none" });
                $("#" + divPassError).css({ "display": "none" });
                $("#divAccounts_LogIn_Error .authFail").css({ "display": "" });
            }
        }
    };

    jQuery.ParseReqPassReturnData = function (ReturnData, submittedForm) {
        if (ReturnData != null || ReturnData != "") {
            $("#divAccounts_RequestPassword_confirm").css({ "display": "" });
            var returnCode = ReturnData;
            if (returnCode == "true") {
                var emailValue = $(submittedForm + "input.UA_required[id*='email']").val();
                $("#divAccounts_RequestPassword_confirm .passwordSent").css({ "display": "" });
                $("#divAccounts_RequestPassword_confirm .emailNotFound").css({ "display": "none" });
                $("#divAccounts_RequestPassword_topcopy").css({ "display": "none" });
                $("#RequestPasswordForm").css({ "display": "none" });
                $("#divAccounts_RequestPassword_confirm .passwordSent .passwordSentEmail").html(emailValue);
            }
            else {
                $("#divAccounts_RequestPassword_confirm .passwordSent").css({ "display": "none" });
                $("#divAccounts_RequestPassword_confirm .emailNotFound").css({ "display": "" });
            }
        }
    };

    jQuery.fn.closeCancel = function () {
        $.closeAccountControl("AccountDivs");
        return false;

    };

    //VerifyPasswordFormat
    jQuery.VerifyPasswordFormat = function (password1FieldId) {
        if (($("#" + password1FieldId).val() == "")
            || ($("#" + password1FieldId).val() == null)
            || ($("#" + password1FieldId).val().length < 5)
            || ($("#" + password1FieldId).val().length > 12)) {
            $("#" + password1FieldId).css({ "background-color": "#fcc" });
            var divError1 = $("#" + password1FieldId).attr("id") + "_error";
            $("#" + divError1).css({ "display": "block" });

            return false;
        }
        else {
            $("#" + password1FieldId).css({ "background-color": "#FFF" });
            var divError1 = $("#" + password1FieldId).attr("id") + "_error";
            $("#" + divError1).css({ "display": "none" });
        }

        return true;
    }; // End VerifyPasswordFormat

    //VerifyPasswords
    jQuery.VerifyPasswords = function (password1FieldId, password2FieldId) {

        var inputFieldPass1 = password1FieldId;
        var inputFieldPass2 = password2FieldId;
        if ($("#" + inputFieldPass1).val() != $("#" + inputFieldPass2).val()) {
            $("#" + inputFieldPass2).css({ "background-color": "#fcc" });
            var divError2 = $("#" + inputFieldPass2).attr("id") + "_error";
            $("#" + divError2).css({ "display": "block" });
            return false;
        }
        else {
            $("#" + inputFieldPass2).css({ "background-color": "#FFF" });
            var divError2 = $("#" + inputFieldPass2).attr("id") + "_error";
            $("#" + divError2).css({ "display": "none" });

            return true;
        }
    }; // End VerifyPasswords

    //Verify Required fields
    jQuery.verifyRequired = function (reqFieldsList) {
        var formVerified = true;
        var firstErrorField = null;
        var reqFieldsList_temp = reqFieldsList;

        $.each(reqFieldsList, function () {
            var getInputId = $(this).attr("id");
            var getInputIdLower = getInputId.toLowerCase();
            var isEmailValid = false;
            var isZipValid = false;
            var isPasswordCompareValid = false;

            if ($(this).attr("type") == "text" || $(this).attr("type") == "password") {
                if (getInputIdLower.indexOf("textbox_uaemail") > 0) {
                    //IsEmailValid function from utils.js
                    validEmail = IsEmailValid($(this).val());
                    if (validEmail == false) {
                        $(this).css({ "background-color": "#fcc" });
                        var divError = $(this).attr("id") + "_error";
                        $("#" + divError).css({ "display": "block" });
                        if (firstErrorField == null)
                            firstErrorField = $(this);

                        if (formVerified == true)
                            formVerified = validEmail;
                    }
                    else {
                        $(this).css({ "background-color": "#FFF" });
                        var divError = $(this).attr("id") + "_error";
                        $("#" + divError).css({ "display": "none" });
                    }
                }

                //Passwords
                if (getInputIdLower.indexOf("textbox_uapassword") > 0) {
                    if (($(this).val() == "") || ($(this).val() == null)) {
                        $(this).css({ "background-color": "#fcc" });
                        var divError = $(this).attr("id") + "_error";
                        $("#" + divError).css({ "display": "block" });

                        if (firstErrorField == null)
                            firstErrorField = $(this);

                        if (formVerified == true)
                            formVerified = false;
                    }
                    else {
                        $(this).css({ "background-color": "#FFF" });
                        var divError = $(this).attr("id") + "_error";
                        $("#" + divError).css({ "display": "none" });
                    }
                }

                if (getInputIdLower.indexOf("textbox_uapassword1") > 0) {
                    var verifyPasswordFormat = $.VerifyPasswordFormat($(this).attr("id"));
                    if (verifyPasswordFormat == false) {
                        if (firstErrorField == null)
                            firstErrorField = $(this);

                        if (formVerified == true)
                            formVerified = false;
                    }
                }


                if (getInputIdLower.indexOf("textbox_uapassword2") > 0) {
                    var password1FieldId = $(this).attr("id").replace("assword2", "assword1");
                    var verifyPasswords = $.VerifyPasswords(password1FieldId, $(this).attr("id"));
                    if (verifyPasswords == false) {
                        if (firstErrorField == null)
                            firstErrorField = $(this);

                        if (formVerified == true)
                            formVerified = false;
                    }
                }


                //Zip Code IsZipCodeValid
                if (getInputIdLower.indexOf("textbox_uazip") > 0) {
                    var verifyZip = IsZipCodeValid($(this).val());
                    if (verifyZip == false) {
                        $(this).css({ "background-color": "#fcc" });
                        var divError = $(this).attr("id") + "_error";
                        $("#" + divError).css({ "display": "block" });

                        if (firstErrorField == null)
                            firstErrorField = $(this);

                        if (formVerified == true)
                            formVerified = false;
                    }
                    else {
                        $(this).css({ "background-color": "#FFF" });
                        var divError = $(this).attr("id") + "_error";
                        $("#" + divError).css({ "display": "none" });
                    }
                }


                if (($(this).val() == "") || ($(this).val() == null)) {

                    $.each(reqFieldsList_temp, function () {
                        if ($(this).attr("type") == "text" || $(this).attr("type") == "password") {
                            if (($(this).val() == "") || ($(this).val() == null)) {
                                $(this).css({ "background-color": "#fcc" });
                                var divError = $(this).attr("id") + "_error";
                                $("#" + divError).css({ "display": "block" });
                            }
                            else {

                            }
                        }
                    }); // END $.each

                    if (firstErrorField == null)
                        firstErrorField = $(this);
                    formVerified = false;

                }
                else {
                    //                    $(this).css({ "background-color": "#FFF" });
                    //                    var divError = $(this).attr("id") + "_error";
                    //                    $("#"+divError).css({"display":"none"});
                }

            } // END if type = text or password

            if ($(this).attr("type") == "checkbox") {

                var divDefault = $(this).attr("id") + "_default";
                var divError = $(this).attr("id") + "_error";

                if ($(this).is(":checked") == true) {
                    $(this).css({ "background-color": "#FFF" });

                    $("#" + divError).css({ "display": "none" });
                    $("#" + divDefault).css({ "display": "" });
                }
                else {
                    $.each(reqFieldsList_temp, function () {

                        if ($(this).attr("type") == "checkbox") {
                            if ($(this).is(":checked") == false) {
                                $(this).css({ "background-color": "#fcc" });

                                $("#" + divError).css({ "display": "" });
                                $("#" + divDefault).css({ "display": "none" });
                                $(this).click(function () {
                                    if ($(this).is(":checked") == true) {
                                        $(this).css({ "background-color": "" });
                                        $("#" + divError).css({ "display": "none" });
                                        $("#" + divDefault).css({ "display": "" });
                                    }
                                    else {
                                        $(this).css({ "background-color": "#fcc" });
                                        $("#" + divError).css({ "display": "" });
                                        $("#" + divDefault).css({ "display": "none" });
                                    }
                                });
                            }
                            else {
                                $(this).css({ "background-color": "" });

                                $("#" + divError).css({ "display": "none" });
                                $("#" + divDefault).css({ "display": "" });
                            }
                        }
                    }); // END $.each
                    if (firstErrorField == null)
                        firstErrorField = $(this);
                    formVerified = false;
                }
            } // END if type=checkbox

        }); // END $.each
        if (firstErrorField != null)
            firstErrorField.focus();

        return formVerified;
    }; // End resizeToFullScreen

    //Resize element to full screen
    jQuery.fn.resizeToFullScreen = function () {
        var winWidth = 0;
        var winHeight = 0;

        if (document.body && (document.body.scrollWidth || document.body.scrollHeight)) {
            winWidth = document.body.scrollWidth + "px";
            winHeight = document.body.scrollHeight + "px";
        }
        else if (document.body.offsetWidth) {
            winWidth = document.body.offsetWidth + "px";
            winHeight = document.body.offsetHeight + "px";
        }
        else {
            winWidth = "100%";
            winHeight = "100%";
        }

        $(this).css({ "width": winWidth, "height": winHeight });
    }; // End resizeToFullScreen

    //Set element to middle of screen
    jQuery.fn.setToMiddleOfScreen = function () {
        var displayWidth = 0;
        var displayHeight = 0;
        var iebody = (document.compatMode && document.compatMode != "BackCompat") ? document.documentElement : document.body

        var offsetX = document.all ? iebody.scrollLeft : pageXOffset
        var offsetY = document.all ? iebody.scrollTop : pageYOffset

        var objWidth = $(this).width();
        var objHeight = $(this).height();

        if (typeof (window.innerWidth) == "number") {
            //Non-IE
            displayWidth = window.innerWidth;
            displayHeight = window.innerHeight;
        }
        else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
            //IE 6+ in 'standards compliant mode'
            displayWidth = document.documentElement.clientWidth;
            displayHeight = document.documentElement.clientHeight;
        }

        $(this).css({ "left": ((displayWidth / 2) - (objWidth / 2) + offsetX) + "px", "top": ((displayHeight / 2) - (objHeight / 2) + offsetY) + "px" });
    }; // End setToMiddleOfScreen    
});     //End document.ready
