﻿// Onload
$(function() 
{
    //Ensure anything with modal trigger classes have appropriate cursor on hover
    $("a.loginModalTrigger").hover(function() { $(this).addClass("activeTrigger"); }, function() { $(this).removeClass("activeTrigger"); });
    $(".registrationModalTrigger").hover(function() { $(this).addClass("activeTrigger"); }, function() { $(this).removeClass("activeTrigger"); });
    $("a.regPromptModalTrigger").hover(function() { $(this).addClass("activeTrigger"); }, function() { $(this).removeClass("activeTrigger"); });
    $("a.closeRegModalTrigger").hover(function() { $(this).addClass("activeTrigger"); }, function() { $(this).removeClass("activeTrigger"); });
    $("a.forgotPasswordTrigger").hover(function() { $(this).addClass("activeTrigger"); }, function() { $(this).removeClass("activeTrigger"); });
    $("a.forceRegModal").hover(function() { $(this).addClass("activeTrigger"); }, function() { $(this).removeClass("activeTrigger"); });

    //Registration Modal
    if ($('#registrationModal').length) 
    {
        //Anything with css class 'registrationModalTrigger' will show the registration Modal popup
        $(".registrationModalTrigger").overlay({

            //All appropriate triggers will show the one Modal
            target: '#registrationModal',

            fixed: false,

            //Make it look fancy with a background mask
            mask: {
                color: '#000000',
                loadSpeed: 200,
                opacity: 0.75,
                closeSpeed: 0   //NOTE: Mad hax to get next overlay to work if triggering one from another
            },

            //Reset the modal for next Registration attempt when it's closed
            onClose: function() 
            {
                //Hide all messages
                $("#ErrorContainer_Reg").hide();
                $("#registrationModal div.validationMsg").hide();

                //Ensure form, not loading, visible
                $("#RegistrationLoadingDiv").hide();
                $("#RegistrationContainer").show();
                $("#RegistrationSuccessful").hide();
            },

            onLoad: function() 
            {
                //Ensure modal header reset
                $("#registrationModal .modalHeader").empty();
                $("#registrationModal .modalHeader").append("Join the SC Magazine community");
            },
            
            
            onBeforeLoad: function()
            {
                //Check for email value to pre-populate
                CheckStoredValues();
            },

            //Misc
            top: '5',
            closeOnClick: false,
            load: false
        });

        //As we can click the text on a .Net Checkbox to check it, makes sense to show hand cursor for it...
        $("#registrationModal input:checkbox").next("label").hover(function() { $(this).addClass("activeTrigger"); }, function() { $(this).removeClass("activeTrigger"); });

        //Hide the 'success' message on Modal
        if ($('#RegistrationSuccessful').length) 
        {
            $('#RegistrationSuccessful').hide();
        }

        //Hover on Close modal link
        $("#RegistrationSuccessful a").hover(function() { $(this).addClass("activeTrigger"); }, function() { $(this).removeClass("activeTrigger"); });
    }
    else
    {
        //Registration Modal NOT in page, so user must be logged in, so hide anything that can be clicked to allow Registration
        $(".registrationModalTrigger").hide();
    }


    //Login Modal
    if ($('#loginModal').length) 
    {
        $(".loginModalTrigger").overlay(
        {
            //All appropriate triggers will show the one Modal
            target: '#loginModal',

            //Make it look fancy with a background mask
            mask: {
                color: '#000000',
                loadSpeed: 200,
                opacity: 0.75,
                closeSpeed: 0   //NOTE: Mad hax to get next overlay to work if triggering one from another
            },

            //Reset the modal for next login attempt when it's closed
            onClose: function() 
            {
                //Hide all error messages etc
                $("#ErrorContainer_Login").hide();
                $("#loginModal div.validationMsg").hide();
                $("#ForgotPWContainer div.validationMsg").hide();

                $("#LoginLoadingDiv").hide();
                $("#ForgotPWContainer").hide();
                $("#LoginContainer").show();

                //Reset Inputs (fields & checkbox)
                $('[id$="UsernameTextbox_Login"]').val('');
                $('[id$="PasswordTextbox_Login"]').val('');
                $("#loginModal input:checkbox").removeAttr('checked');
            },

            onLoad: function()
            {
                $("#LoginLoadingDiv").hide();
                $("#ForgotPWContainer").hide();
                $("#LoginContainer").show();
            },

            //Misc
            top: '35%',
            closeOnClick: false,
            load: false
        });
    }

    //Registration Prompt Modal (only contains Email and NL selections, passed to Registration Modal)
    if ($('#regPromptModal').length)
    {
        //Plant a cookie so won't be seen again
        var expiryDate = new Date();
        expiryDate.setDate(expiryDate.getDate() + 7);
        var expiryString = expiryDate.getDate() + '-' + (expiryDate.getMonth() + 1) + '-' + expiryDate.getFullYear() + ' ' + expiryDate.getHours() + ":" + expiryDate.getMinutes();
        $.cookie('RegistrationPromptModalExpiry_SC', expiryString, { expires: 7, path: '/' }); //NOTE: Ensure matches value of 'GeneralConstants.RegistrationModalExpiryCookieName'

        $("#regPromptModal.modal").overlay({

            //Make it look fancy with a background mask
            mask: {
                color: '#000000',
                loadSpeed: 200,
                opacity: 0.75,
                closeSpeed: 0   //NOTE: Mad hax to get next overlay to work if triggering one from another
            },

            //Reset the modal for next login attempt when it's closed
            onClose: function()
            {
                //Hide all error messages etc
                $("#regPromptModal div.validationMsg").hide();

                $("#RegistrationPromptContainer").show();

                //Reset Inputs (fields & checkbox)
                $("#regPromptModal :input").val('');
                $("#regPromptModal input:checkbox").removeAttr('checked');
            },

            //Misc
            closeOnClick: false,
            load: true  //NOTE: This is what shows the modal automatically when page loaded
        });
    }


    //IE fix
    if ($.browser.msie) 
    {
        $(".modal").appendTo("body");
    }

    //Tooltips for Newsletter details (used mulitple places/pages)
    if ($('#registrationModal').length || $('#manageAccount').length || $('#regPromptModal').length || $('#profileUpdate').length ) 
    {
        //Initialise the Newsletter details tooltips
        
        //NOTE: Setting opacity stuffs up IE, so don't do it...
        if ($(".nlTooltipTrigger_209").length) {
            $(".nlTooltipTrigger_209").tooltip({
                position: "top center",
                /*opacity: 0.95,*/
                offset: [3, 0],
                delay: 0,
                tipClass: "nlTooltip_209",
                relative: true
            });
        }
        if ($(".nlTooltipTrigger_259").length) {
            $(".nlTooltipTrigger_259").tooltip({
                position: "top center",
                /*opacity: 0.95,*/
                offset: [3, 0],
                delay: 0,
                tipClass: "nlTooltip_259",
                relative: true
            });
        }
        if ($(".nlTooltipTrigger_296").length) {
            $(".nlTooltipTrigger_296").tooltip({
                position: "top center",
                /*opacity: 0.95,*/
                offset: [3, 0],
                delay: 0,
                tipClass: "nlTooltip_296",
                relative: true
            });
        }
        if ($(".nlTooltipTrigger_333").length) {
            $(".nlTooltipTrigger_333").tooltip({
                position: "top center",
                /*opacity: 0.95,*/
                offset: [3, 0],
                delay: 0,
                tipClass: "nlTooltip_333",
                relative: true
            });
        }
        if ($(".nlTooltipTrigger_370").length) {
            $(".nlTooltipTrigger_370").tooltip({
                position: "top center",
                /*opacity: 0.95,*/
                offset: [3, 0],
                delay: 0,
                tipClass: "nlTooltip_370",
                relative: true
            });
        }
    }

    //Show pointer cursor on Manage Account page check boxes - If can click them to change, may as well show that
    $("#manageAccount input:checkbox").next("label").hover(function() { $(this).addClass("activeTrigger"); }, function() { $(this).removeClass("activeTrigger"); });
    $("#regPromptModal input:checkbox").next("label").hover(function() { $(this).addClass("activeTrigger"); }, function() { $(this).removeClass("activeTrigger"); });
    $("#profileUpdate input:checkbox").next("label").hover(function() { $(this).addClass("activeTrigger"); }, function() { $(this).removeClass("activeTrigger"); });
});


/******************************* 
REGISTRATION MODAL
*******************************/
function ShowRegistrationModalForSource(src) //Can be used for anything you want to Pop the Reg Modal and set a certain Promo Code for
{
    //Set Registration Source
    $('[id$="hdnRegSource"]').val(src);

    //Show Registration Modal
    $(".registrationModalTrigger").overlay().load();
}

function ShowRegistrationModalWithNewsletterTicked(nl, src)
{
    if ($('#registrationModal').length)
    {
        //alert('Not logged in, should show Reg Modal');
        
        //Pre-tick using the hidden field that gets checked when modal loads
        var cbDailyVal = "1"; //Always tick daily newsletter
        var cbEDMVal = "0"; if (nl.toString().toLowerCase() == 'edm') { cbEDMVal = "1"; }
        var choices = cbDailyVal + cbEDMVal;
        $('[id$="hdnRegNLChoices"]').val(choices);

        //Set Registration Source
        $('[id$="hdnRegSource"]').val(src);

        //Show Registration Modal
        $(".registrationModalTrigger").overlay().load();
    }
    else
    {
        //alert('Logged in, going to manage page');
    
        var url = managePageURL + "?nl=" + nl;
        window.location.href = url;
    }
}

function AttemptRegistration()
{
    if (RegFormValid())
    {
        //Hide form, show loading div
        $("#RegistrationContainer").hide();
        $("#RegistrationLoadingDiv").show();
        $("#RegistrationSuccessful").hide();

        //Extract Checkbox values
        var cbDailyVal = "no"; if ($('[id$="cbDaily"]').is(':checked')) { cbDailyVal = "yes"; }
        var cbEDMVal = "no"; if ($('[id$="cbEDM"]').is(':checked')) { cbEDMVal = "yes"; }

        var email = $('[id$="EmailTextbox_Reg"]').val();

        //Send entered details to Registration processing page
        $.ajax({
            url: ajaxDoRegisatrationURL,
            global: false,
            type: "POST",
            data: ({    //Registrant Details
                username: $('[id$="UsernameTextbox_Reg"]').val(),
                password: $('[id$="PasswordTextbox_Reg"]').val(),
                email: email,
                firstname: $('[id$="FirstNameTextbox_Reg"]').val(),
                lastname: $('[id$="LastNameTextbox_Reg"]').val(),
                country: $('[id$="CountryDDL_Reg"] :selected').val(),  //ID
                state: $('[id$="StateDDL_Reg"] :selected').val(),      //ID
                postcode: $('[id$="PostcodeTextbox_Reg"]').val(),
                
                company: $('[id$="CompanyTextbox_Reg"]').val(),
                industry: $('[id$="IndustryDDL_Reg"] :selected').val(),
                //jobtitle: $('[id$="JobTextbox_Reg"]').val(),
                jobtitle: $('[id$="JobTitleListDDL_Reg"] :selected').val(),
                purchase: $('[id$="PurchaseDDL_Reg"] :selected').val(),
                employees: $('[id$="EmployeesDDL_Reg"] :selected').val(),

                //Newsletters
                nlDaily: cbDailyVal,
                nlEDM: cbEDMVal,

                //Source
                src: $('[id$="hdnRegSource"]').val()
            }),
            dataType: "html",
            async: false,
            success: function(response)
            {
                //Registration successful
                if (response.toString().toLowerCase() == "success")
                {
                    //Successful! Show message
                    $("#RegistrationSuccessful").show();

                    //Ensure correct modal heading
                    $("#registrationModal .modalHeader").empty();
                    $("#registrationModal .modalHeader").append("Registration Successful");

                    //Set email placeholder value on Success message
                    $("#registrationModal .emailValue").empty();
                    $("#registrationModal .emailValue").append(email);

                    //Hide other parts of modal
                    $("#RegistrationContainer").hide();
                    $("#RegistrationLoadingDiv").hide();
                }
                //Registration Failed (not enough params provided)
                else if (response.toString() == "ERROR - PARAMS")
                {
                    //Show form, not loading
                    $("#RegistrationContainer").show();
                    $("#RegistrationLoadingDiv").hide();
                    $("#RegistrationSuccessful").hide();

                    //Ensure correct modal heading
                    $("#registrationModal .modalHeader").empty();
                    $("#registrationModal .modalHeader").append("Join the SC Magazine community");

                    //Display message/response from failed Registration attempt
                    $("#ErrorContainer_Reg").show();
                    $("#ErrorContainer_Reg").empty();
                    $("#ErrorContainer_Reg").append("ERROR - Not all required values passed to registration process!");
                }
                //Registration Failed (some other reason)
                else
                {
                    //Show form, not loading
                    $("#RegistrationContainer").show();
                    $("#RegistrationLoadingDiv").hide();
                    $("#RegistrationSuccessful").hide();

                    //Ensure correct modal heading
                    $("#registrationModal .modalHeader").empty();
                    $("#registrationModal .modalHeader").append("Join the SC Magazine community");

                    //Display message/response from failed Registration attempt
                    $("#ErrorContainer_Reg").show();
                    $("#ErrorContainer_Reg").empty();
                    $("#ErrorContainer_Reg").append(response);
                }
            }
        });
        //end ajax
    }

    return false;
}

function RegFormValid()
{
    //Hide all messages
    $("#ErrorContainer_Reg").hide();
    $("#registrationModal div.validationMsg").hide();

    var valid = true;

    //Check for all required fields
    if ($('[id$="UsernameTextbox_Reg"]').val() == "") { $("#rfvUsernameMsg_Reg").show(); valid = false; }
    if ($('[id$="PasswordTextbox_Reg"]').val() == "") { $("#rfvPasswordMsg_Reg").show(); valid = false; }
    if ($('[id$="ConfirmPasswordTextbox_Reg"]').val() == "") { $("#rfvConfirmPasswordMsg_Reg").show(); valid = false; }
    if ($('[id$="EmailTextbox_Reg"]').val() == "") { $("#rfvEmailMsg_Reg").show(); valid = false; }
    if ($('[id$="FirstNameTextbox_Reg"]').val() == "") { $("#rfvFirstNameMsg_Reg").show(); valid = false; }
    if ($('[id$="LastNameTextbox_Reg"]').val() == "") { $("#rfvLastNameMsg_Reg").show(); valid = false; }
    if ($('[id$="PostcodeTextbox_Reg"]').val() == "") { $("#rfvPostcodeMsg_Reg").show(); valid = false; }
    if ($('[id$="CountryDDL_Reg"]').val() < 0) { $("#rfvCountryMsg_Reg").show(); valid = false; }
    if ($('[id$="StateDDL_Reg"]').val() < 0) { $("#rfvStateMsg_Reg").show(); valid = false; }
    
    if ($('[id$="CompanyTextbox_Reg"]').val() == "") { $("#rfvCompanyMsg_Reg").show(); valid = false; }
    //if ($('[id$="JobTextbox_Reg"]').val() == "") { $("#rfvJobMsg_Reg").show(); valid = false; }
    if ($('[id$="JobTitleListDDL_Reg"]').val() == "") { $("#rfvJobMsg_Reg").show(); valid = false; }
    if ($('[id$="PurchaseDDL_Reg"]').val() == "") { $("#rfvPurchaseMsg_Reg").show(); valid = false; }
    if ($('[id$="EmployeesDDL_Reg"]').val() == "") { $("#rfvEmployeesMsg_Reg").show(); valid = false; }
    if ($('[id$="IndustryDDL_Reg"]').val() == "") { $("#rfvIndustryMsg_Reg").show(); valid = false; }

    if (!$('[id$="cbTerms"]').is(':checked')) { $("#rfvTermsMsg_Reg").show(); valid = false; }

    //Check Password vs Confirmation
    if ($('[id$="PasswordTextbox_Reg"]').val() != $('[id$="ConfirmPasswordTextbox_Reg"]').val()) { $("#cvPasswordMismatchMsg_Reg").show(); valid = false; }

    //Check email validity vs Regex
    var emailaddr = $('[id$="EmailTextbox_Reg"]').val();
    if (emailaddr != "")
    {
        if (!IsValidEmail(emailaddr)) { $("#cvValidEmailMsg_Reg").show(); valid = false; }
    }

    return valid;
}

$(function()
{
    //Handle COUNTRY selection change
    $('[id$="CountryDDL_Reg"]').change(function()
    {
        //Extract selected Country ID
        var countryID = $('[id$="CountryDDL_Reg"]').val();

        //Remove all current states in State DDL
        $('[id$="StateDDL_Reg"] > option').remove();

        //Add default option
        $('[id$="StateDDL_Reg"]').append($("<option></option>").val("-1").html(""));

        //Request STATES for that Country
        $.ajax({
            url: ajaxGetStatesURL,
            global: false,
            type: "POST",
            data: ({ countryid: countryID }),
            dataType: "html",
            async: false,
            success: function(response)
            {
                //Process returned states
                if (response.toString() != "")
                {
                    var states = response.toString().split(',');
                    var index = 0;

                    while (index < states.length)
                    {
                        $('[id$="StateDDL_Reg"]').append($("<option></option>").val(states[index]).html(states[index + 1]));
                        index = index + 2;
                    }
                }
                else
                {
                    //Add 'Other' option
                    $('[id$="StateDDL_Reg"]').append($("<option></option>").val("9").html("Other state/region"));
                }
            }
        }); //end ajax
    });

    //Check Querystring for force display of Modal
    if (getQueryString()["reg"] == "true")
    {
        $(".registrationModalTrigger").overlay().load();
    }

    //Handle custom close for registration
    $(".closeRegModalTrigger").click(function()
    {
        CloseRegistrationModal();
    });

    //Handle passing of Email Address from signup boxout to Registration Modal
    $(".regSignUpButton").click(function()
    {
        if ($(".regEmailPrePopulateField").val() != "")
        {
            $("#registrationModal .regEmailField").val($(".regEmailPrePopulateField").val());
        }

        $('[id$="hdnRegSource"]').val("RightColBox");
    });

    //If click top menu's register link, set promo code as appropriate
    $("#login a.registrationModalTrigger").click(function()
    {
        $('[id$="hdnRegSource"]').val("SC_Online_Registration");
    });

    //Update/store 'source' of registration if passed in via querystring (otherwise will remain as default 'SC_Online_Registration')
    /*var source = "";
    source = getQueryString()["src"];
    if (source != null && source != "" && source != "undefined")
    {
        $('[id$="hdnRegSource"]').val(source); //NOTE: Viewing source it looks like old value still there, but 'generated source' reveals new value...
    }
    else
    {
        $('[id$="hdnRegSource"]').val("SC_Online_Registration");
    }*/
});

function CloseRegistrationModal()
{
    $(".registrationModalTrigger").overlay().close();
}

function CheckStoredValues()
{
    //Update/store 'source' of registration if passed in via querystring (otherwise will remain as default 'SC_Online_Registration')
    var source = "";
    source = getQueryString()["src"];
    var source2 = "";
    source2 = getQueryString()["s"];    //From newsletters etc

    if (source != null && source != "" && source != "undefined")
    {
        $('[id$="hdnRegSource"]').val(source); //NOTE: Viewing source it looks like old value still there, but 'generated source' reveals new value...
    }
    else if (source2 != null && source2 != "" && source2 != "undefined")
    {
        $('[id$="hdnRegSource"]').val(source); //NOTE: Viewing source it looks like old value still there, but 'generated source' reveals new value...
    }
    //Or, value may have been set by external source (eg- Prompt modal)
    else if ($('[id$="hdnRegSource"]').val() != "")
    {
        source = $('[id$="hdnRegSource"]').val();
        $('[id$="hdnRegSource"]').val(source);
    }
    //Otherwise, use default value (for clicking from nav menu link)
    else
    {
        $('[id$="hdnRegSource"]').val("SC_Online_Registration");
    }

    //Check for 'stored' values from Prompt Modal
    var email = $('[id$="hdnRegPromptEmail"]').val();
    if (email != null && email != "" && email != "undefined")
    {
        $('[id$="EmailTextbox_Reg"]').val(email)
        $('[id$="hdnRegPromptEmail"]').val("");
    }

    //Newsletter choices from Reg Prompt Modal
    var choices = $('[id$="hdnRegPromptNLChoices"]').val();
    if (choices != null && choices != "" && choices != "undefined")
    {
        //Reset all checkboxes to unchecked
        $("#registrationModal input:checkbox").removeAttr('checked');

        //Set any choices user has made on Prompt Modal (or some other method for getting them here) to checked
        var i = 0;
        var numChars = choices.length;

        for (i = 0; i <= numChars; i++)
        {
            switch (i)
            {
                case 0: if (choices.charAt(i) == "1") { $('[id$="cbDaily"]').attr('checked', true); } break;
                case 1: if (choices.charAt(i) == "1") { $('[id$="cbEDM"]').attr('checked', true); } break;
            }
        }
        $('[id$="hdnRegPromptNLChoices"]').val("");
    }
    else
    {
        choices = $('[id$="hdnRegNLChoices"]').val();
        if (choices != null && choices != "" && choices != "undefined")
        {
            //Reset all checkboxes to unchecked
            $("#registrationModal input:checkbox").removeAttr('checked');

            //Set any choices user has made on Prompt Modal (or some other method for getting them here) to checked
            var i = 0;
            var numChars = choices.length;

            for (i = 0; i <= numChars; i++)
            {
                switch (i)
                {
                    case 0: if (choices.charAt(i) == "1") { $('[id$="cbDaily"]').attr('checked', true); } break;
                    case 1: if (choices.charAt(i) == "1") { $('[id$="cbEDM"]').attr('checked', true); } break;
                }
            }
            $('[id$="hdnRegNLChoices"]').val("");
        }
    }
}


/*******************************
LOGIN MODAL
*******************************/
function AttemptLogin()
{
    if (LoginFormValid())
    {
        $("#ErrorContainer_Login").hide();
        $("#loginModal div.validationMsg").hide();

        $("#LoginContainer").hide();
        $("#ForgotPWContainer").hide();
        $("#LoginLoadingDiv").show();

        var u = $('[id$="UsernameTextbox_Login"]').val();
        var p = $('[id$="PasswordTextbox_Login"]').val();
        var r = "no";
        if ($('[id$="cbRemember_Login"]').is(':checked')) { r = "yes"; }

        $.ajax({
            url: doLoginURL,
            global: false,
            type: "POST",
            data: ({ username: u, password: p, remember: r }),
            dataType: "html",
            async: false,
            success: function(response)
            {
                //Process the result of login
                if (response.toString().toLowerCase().indexOf("http") != -1 ||
                            response.toString().toLowerCase().indexOf("/default") != -1)   //sent a redirect url
                {
                    //Logged-in, close the modal and redirect
                    $(".loginModalTrigger").overlay().close();
                    window.location = response.toString();
                }
                else
                {
                    //Display message/response from login attempt (failed)
                    $("#LoginContainer").show();
                    $("#LoginLoadingDiv").hide();
                    $("#ErrorContainer_Login").show();
                    $("#ErrorContainer_Login").empty();
                    $("#ErrorContainer_Login").append(response);
                }
            }
        });     //end ajax
    }

    return false;
}

function LoginFormValid()
{
    $("#ErrorContainer_Login").hide();
    $("#rfvUsernameMsg_Login").hide();
    $("#rfvPasswordMsg_Login").hide();

    var u = $('[id$="UsernameTextbox_Login"]').val();
    var p = $('[id$="PasswordTextbox_Login"]').val();

    if (u == "" && p == "")
    {
        $("#rfvUsernameMsg_Login").show();
        $("#rfvPasswordMsg_Login").show();
        return false;
    }
    else if (u == "")
    {
        $("#rfvUsernameMsg_Login").show();
        return false;
    }
    else if (p == "")
    {
        $("#rfvPasswordMsg_Login").show();
        return false;
    }

    return true;
}

function SendForgottenPassword()
{
    if (ForgotPWFormValid())
    {
        $("#LoginContainer").hide();
        $("#ForgotPWContainer").hide();
        $("#LoginLoadingDiv").show();

        var e = $('[id$="ForgotPWEmail_ForgotPW"]').val();

        $.ajax({
            url: forgotPasswordURL,
            global: false,
            type: "POST",
            data: ({ email: e }),
            dataType: "html",
            async: false,
            success: function(response)
            {
                //Process result
                if (response.toString().toLowerCase().indexOf("sent") != -1)
                {
                    $("#ForgotPWFormContainer").hide();

                    //Password sent, display the message returned
                    $("#ForgotPWContainer").show();
                    $("#LoginLoadingDiv").hide();
                    $("#SuccessContainer_ForgotPW").show();
                    $("#SuccessContainer_ForgotPW").empty();
                    $("#SuccessContainer_ForgotPW").append(response);
                }
                else
                {
                    //Display message/response from login attempt (failed)
                    $("#ForgotPWContainer").show();
                    $("#LoginLoadingDiv").hide();
                    $("#ErrorContainer_ForgotPW").show();
                    $("#ErrorContainer_ForgotPW").empty();
                    $("#ErrorContainer_ForgotPW").append(response);
                }
            }
        });     //end ajax
    }

    return false;
}

function ForgotPWFormValid()
{
    $("#ErrorContainer_ForgotPW").hide();
    $("#SuccessContainer_ForgotPW").hide();
    $("#rfvForgotPWEmail_ForgotPW").hide();
    $("#cvForgotPWEmail_ForgotPW").hide();
    $("#cvNoEmailExists_ForgotPW").hide();

    var e = $('[id$="ForgotPWEmail_ForgotPW"]').val();

    if (e == "" || e == "undefined" || e.length == 0)
    {
        $("#rfvForgotPWEmail_ForgotPW").show();
        return false;
    }
    else if (!IsValidEmail(e))
    {
        $("#cvForgotPWEmail_ForgotPW").show();
        return false;
    }

    return true;
}

function ShowForgotPasswordForm()
{
    $("#ErrorContainer_ForgotPW").hide();
    $("#ErrorContainer_Login").hide();
    $("#ForgotPWContainer div.validationMsg").hide();
    $("#LoginContainer").hide();
    $("#LoginLoadingDiv").hide();
    $("#SuccessContainer_ForgotPW").hide();
    $("#ForgotPWFormContainer").show();
    $("#ForgotPWContainer").show();

    //Ensure modal header reset
    $("#loginModal .modalHeader").empty();
    $("#loginModal .modalHeader").append("Forgot Your Password?");
}

function ShowLoginForm()
{
    $("#LoginLoadingDiv").hide();
    $("#ErrorContainer_Login").hide();
    $("#ForgotPWContainer").hide();
    $("#LoginContainer").show();
    $('[id$="ForgotPWEmail_ForgotPW"]').val("");

    //Ensure modal header reset
    $("#loginModal .modalHeader").empty();
    $("#loginModal .modalHeader").append("Login to SC Magazine");
}


/*******************************
REGISTRATION PROMPT MODAL
*******************************/
function ProcessJoinClick()
{
    if (RegPromptFormValid())
    {
        //Extract Checkbox values
        var cbDailyVal = "0"; if ($('[id$="cbDaily_RegPrompt"]').is(':checked')) { cbDailyVal = "1"; }
        var cbEDMVal = "0"; if ($('[id$="cbEDM_RegPrompt"]').is(':checked')) { cbEDMVal = "1"; }

        var email = $('[id$="EmailTextbox_RegPrompt"]').val();
        var choices = cbDailyVal + cbEDMVal;

        //Store values
        $('[id$="hdnRegSource"]').val("RegPromptModal");
        $('[id$="hdnRegPromptEmail"]').val(email);
        $('[id$="hdnRegPromptNLChoices"]').val(choices);

        //Close Reg Prompt Modal, show full Registration Modal
        $(".registrationModalTrigger").overlay().load();
    }

    return false;
}

function RegPromptFormValid()
{
    //Reset
    $("#regPromptModal div.validationMsg").hide();

    var valid = true;

    //Check for all required fields
    if ($('[id$="EmailTextbox_RegPrompt"]').val() == "") { $("#rfvEmailMsg_RegPrompt").show(); valid = false; }

    //Check email validity vs Regex
    var emailaddr = $('[id$="EmailTextbox_RegPrompt"]').val();
    if (emailaddr != "")
    {
        if (!IsValidEmail(emailaddr)) { $("#cvValidEmailMsg_RegPrompt").show(); valid = false; }
    }

    return valid;
}

function CloseRegPromptModal()
{
    $("#regPromptModal").overlay().close();
}
































/*******************************
UTILITY FUNCTIONS FOR MODALS
*******************************/
function getQueryString()
{
    var result = {}, queryString = location.search.substring(1), re = /([^&=]+)=([^&]*)/g, m;
    while (m = re.exec(queryString))
    {
        result[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
    }

    return result;
}

function IsValidEmail(email)
{
    var regex = new RegExp(/^(([\w-\s]+)|([\w-]+(?:\.[\w-]+)*)|([\w-\s]+)([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
    return regex.test(email);
}
