﻿// Onload
$(function()
{
    //alert("Processing modals.js...");

    //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"); });
    $(".adviceModalTrigger").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();

                //Reset Checkboxes
                //$("#registrationModal input:checkbox").removeAttr('checked');
            },

            onLoad: function()
            {
                //Ensure modal header reset
                $("#registrationModal .modalHeader span").empty();
                $("#registrationModal .modalHeader span").append("Join the " + siteName + " community");

                //Ensure Newsletter option ticked (NOTE: Removed for now because was always ticking even if NOT selected on Reg Prompt modal...)
                //$('[id$="cbDailyAus"]').attr('checked', true);
                //$('[id$="cbWeeklyIndia"]').attr('checked', true);
            },

            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_PP', 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: DO NOT set the 'opacity' setting, as it screws up in IE etc...
        //NOTE: Offset is [Vertical,Horizontal]

        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"); });

    //alert("Done!");
});


/******************************* 
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 AttemptRegistration()
{
    if (RegFormValid())
    {
        //Hide form, show loading div
        $("#RegistrationContainer").hide();
        $("#RegistrationLoadingDiv").show();
        $("#RegistrationSuccessful").hide();

        //Save CITY value, as code-behind can't detect the client-side changes made
        var city = "";
        if ($('[id$="CityDDL_Reg"]').length)
        {
            city = $('[id$="CityDDL_Reg"]').val();
            if (city == "Other")
            {
                city = $('[id$="CityTextBox_Reg"]').val();
                $('[id$="hdnCity"]').val(city);
            }
        }

        //Extract Checkbox values
        var cbDailyAusVal = "no";       if ($('[id$="cbDailyAus"]').is(':checked')) { cbDailyAusVal = "yes"; }
        var cbWeeklyIndiaVal = "no";    if ($('[id$="cbWeeklyIndia"]').is(':checked')) { cbWeeklyIndiaVal = "yes"; }
        var cbBulletinIndiaVal = "no";  if ($('[id$="cbBulletinIndia"]').is(':checked')) { cbBulletinIndiaVal = "yes"; }
        var cbEDMVal = "no";            if ($('[id$="cbEDM"]').is(':checked')) { cbEDMVal = "yes"; }

        //Some values are country-specific, so we'll supply default values just to be safe...
        var sizeVal = "XXXX";       if ($('[id$="CompanySizeDDL_Reg"]').length) { sizeVal = $('[id$="CompanySizeDDL_Reg"] :selected').val(); }
        var postcodeVal = "XXXX";   if ($('[id$="PostcodeTextbox_Reg"]').length && $('[id$="PostcodeTextbox_Reg"]').val() != "") { postcodeVal = $('[id$="PostcodeTextbox_Reg"]').val(); }
        var mobileVal = "XXXX";     if ($('[id$="MobileNumberTextbox_Reg"]').length) { mobileVal = $('[id$="MobileNumberTextbox_Reg"]').val(); }

        //alert("Size: " + sizeVal + ", Postcode: " + postcodeVal + ", Mobile: " + mobileVal);

        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: postcodeVal,
                city: city,
                job: $('[id$="JobFunctionDDL_Reg"] :selected').val(),   //Text
                company: $('[id$="CompanyNameTextbox_Reg"]').val(),
                size: sizeVal,
                industry: $('[id$="IndustryDDL_Reg"] :selected').val(), //Text
                mobile: mobileVal,

                //Newsletters
                nlDailyAus: cbDailyAusVal,
                nlWeeklyIndia: cbWeeklyIndiaVal,
                nlBulletinIndia: cbBulletinIndiaVal,
                nlEDM: cbEDMVal,

                //Source
                src: $('[id$="hdnRegSource"]').val()
            }),
            dataType: "html",
            async: false,
            success: function(response)
            {
                //alert("RESPONSE: " + response.toString());

                //Registration successful
                if (response.toString().toLowerCase() == "success")
                {
                    //Successful! Show message
                    $("#RegistrationSuccessful").show();

                    //Ensure correct modal heading
                    $("#registrationModal .modalHeader span").empty();
                    $("#registrationModal .modalHeader span").append(siteName + " 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")
                {
                    //alert("Reg Modal ERROR - PARAMS start");

                    //Show form, not loading
                    $("#RegistrationContainer").show();
                    $("#RegistrationLoadingDiv").hide();
                    $("#RegistrationSuccessful").hide();

                    //Ensure correct modal heading
                    $("#registrationModal .modalHeader span").empty();
                    $("#registrationModal .modalHeader span").append("Join the " + siteName + " 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!");

                    //alert("Reg Modal ERROR - PARAMS end");
                }
                //Registration Failed (some other reason)
                else
                {
                    //alert("Reg Modal ERROR - OTHER start");

                    //Show form, not loading
                    $("#RegistrationContainer").show();
                    $("#RegistrationLoadingDiv").hide();
                    $("#RegistrationSuccessful").hide();

                    //Ensure correct modal heading
                    $("#registrationModal .modalHeader span").empty();
                    $("#registrationModal .modalHeader span").append("Join the " + siteName + " community");

                    //Display message/response from failed Registration attempt
                    $("#ErrorContainer_Reg").show();
                    $("#ErrorContainer_Reg").empty();
                    $("#ErrorContainer_Reg").append(response);

                    //alert("Reg Modal ERROR - OTHER start");
                }
            }
        });
        //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$="JobFunctionDDL_Reg"]').val() == "") { $("#rfvJobFunctionMsg_Reg").show(); valid = false; }
    if ($('[id$="CompanyNameTextbox_Reg"]').val() == "") { $("#rfvCompanyNameMsg_Reg").show(); valid = false; }
    if ($('[id$="CompanySizeDDL_Reg"]').val() == "" && siteNameShort == "PP") { $("#rfvCompanySizeMsg_Reg").show(); valid = false; }    //Only req for AUS
    if ($('[id$="IndustryDDL_Reg"]').val() == "") { $("#rfvIndustryMsg_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$="PostcodeTextbox_Reg"]').val() == "") { $("#rfvPostcodeMsg_Reg").show(); valid = false; }
    //if ($('[id$="CityTextbox_Reg"]').val() == "") { $("#rfvCityMsg_Reg").show(); valid = false; }
    //Also have Mobile number, but is optional (and INDIA only), so can ignore...
    
    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("-- Select State/Region --"));

        //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

        if ($('[id$="CityDDL_Reg"]').length)
        {
            //Reset Cities
            $('[id$="CityTextBox_Reg"]').attr("disabled", "disabled");
            $('[id$="CityTextBox_Reg"]').val('');
            $('[id$="CityTextBox_Reg"]').addClass("disabled");

            //Remove all current Cities in City DDL
            $('[id$="CityDDL_Reg"] > option').remove();

            //Add default option
            $('[id$="CityDDL_Reg"]').append($("<option></option>").val("").html("State req'd"));

            //Disable City DDL
            $('[id$="CityDDL_Reg"]').attr("disabled", "disabled");
            $('[id$="CityDDL_Reg"]').val('');
            $('[id$="CityDDL_Reg"]').addClass("disabled");
        }
    });

    //Handle STATE selction change
    $('[id$="StateDDL_Reg"]').change(function()
    {
        var stateID = $('[id$="StateDDL_Reg"]').val();
        //Save State selection for stupid postback
        $('[id$="hdnState"]').val(stateID);
        //alert("State now: " + stateID);

        if ($('[id$="CityDDL_Reg"]').length)
        {
            //Reset City
            $('[id$="CityTextBox_Reg"]').attr("disabled", "disabled");
            $('[id$="CityTextBox_Reg"]').val('');
            $('[id$="CityTextBox_Reg"]').addClass("disabled");

            //Remove all current Cities in City DDL
            $('[id$="CityDDL_Reg"] > option').remove();

            //Add default option
            $('[id$="CityDDL_Reg"]').append($("<option></option>").val("").html("-- Select City --"));

            //Add returned City values
            $.ajax({
                url: ajaxGetCitiesURL,
                global: false,
                type: "POST",
                data: ({ stateid: stateID }),
                dataType: "html",
                async: false,
                success: function(response)
                {
                    //Process returned Cities
                    if (response.toString() != "")
                    {
                        var cities = response.toString().split(',');
                        var index = 0;

                        //alert(cities.length + " cities returned");

                        while (index < cities.length)
                        {
                            $('[id$="CityDDL_Reg"]').append($("<option></option>").val(cities[index]).html(cities[index + 1]));
                            index = index + 2;
                        }
                    }
                }
            });

            //Add 'Other' option (shows City Textbox upon selection)
            $('[id$="CityDDL_Reg"]').append($("<option></option>").val("Other").html("Other"));

            //If valid State selected, enable the City DDL
            if (stateID != "-1")
            {
                $('[id$="CityDDL_Reg"]').removeAttr("disabled");
                $('[id$="CityDDL_Reg"]').removeClass("disabled");
            }
            //Otherwise, ensure City DDL disabled until valid State selected
            else
            {
                $('[id$="CityDDL_Reg"]').attr("disabled", "disabled");
                $('[id$="CityDDL_Reg"]').val('');
                $('[id$="CityDDL_Reg"]').addClass("disabled");
            }
        }
    });

    //Save City selection for stupid postback
    if ($('[id$="CityDDL_Reg"]').length)
    {
        $('[id$="CityDDL_Reg"]').change(function()
        {
            var city = $('[id$="CityDDL_Reg"]').val();
            $('[id$="hdnCity"]').val(city);
            //alert("City value now: '" + city + "'");

            //If selected 'Other', enable the City textbox
            if (city == "Other")
            {
                $('[id$="CityTextBox_Reg"]').removeAttr("disabled");
                $('[id$="CityTextBox_Reg"]').removeClass("disabled");
            }
            //Otherwise, ensure City textbox disabled until 'other' selected
            else
            {
                $('[id$="CityTextBox_Reg"]').attr("disabled", "disabled");
                $('[id$="CityTextBox_Reg"]').val('');
                $('[id$="CityTextBox_Reg"]').addClass("disabled");
            }
        });
    }

    //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
    $("#logged-out a.registrationModalTrigger").click(function()
    {
        $('[id$="hdnRegSource"]').val(siteNameShort + "_TopNavMenuLink");
    });

    //Update/store 'source' of registration if passed in via querystring (otherwise will remain as default 'XX_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(siteNameShort + "_Online_Registration");
    }*/
});

function CloseRegistrationModal()
{
    $(".registrationModalTrigger").overlay().close();
}

function CheckStoredValues()
{
    //Update/store 'source' of registration if passed in via querystring (otherwise will remain as default 'XX_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 viewing 'generated source' reveals updated 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(siteNameShort + "_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 Reg 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$="cbDailyAus"]').attr('checked', true); } break;
                case 1: if (choices.charAt(i) == "1") { $('[id$="cbWeeklyIndia"]').attr('checked', true); } break;
                case 2: if (choices.charAt(i) == "1") { $('[id$="cbBulletinIndia"]').attr('checked', true); } break;
                case 3: if (choices.charAt(i) == "1") { $('[id$="cbEDM"]').attr('checked', true); } break;
            }
        }
        $('[id$="hdnRegPromptNLChoices"]').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 SendNewPassword()
{
    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 span").empty();
    $("#loginModal .modalHeader span").append("Forgot Your Password?");
}

function ShowLoginForm()
{
    $("#LoginLoadingDiv").hide();
    $("#ErrorContainer_Login").hide();
    $("#ForgotPWContainer").hide();
    $("#LoginContainer").show();
    $("#LoginContainer div.validationMsg").hide();
    $('[id$="ForgotPWEmail_ForgotPW"]').val("");

    //Ensure modal header reset
    $("#loginModal .modalHeader span").empty();
    $("#loginModal .modalHeader span").append("Sign In to " + siteName);
}


/*******************************
REGISTRATION PROMPT MODAL
*******************************/
function ProcessJoinClick()
{
    if (RegPromptFormValid())
    {
        //Extract values
        var cbDailyAusVal = "0"; if ($('[id$="cbDailyAus_RegPrompt"]').is(':checked')) { cbDailyAusVal = "1"; }
        var cbWeeklyIndiaVal = "0"; if ($('[id$="cbWeeklyIndia_RegPrompt"]').is(':checked')) { cbWeeklyIndiaVal = "1"; }
        var cbBulletinIndiaVal = "0"; if ($('[id$="cbBulletinIndia_RegPrompt"]').is(':checked')) { cbBulletinIndiaVal = "1"; }
        var cbEDMVal = "0"; if ($('[id$="cbEDM_RegPrompt"]').is(':checked')) { cbEDMVal = "1"; }

        var email = $('[id$="EmailTextbox_RegPrompt"]').val();
        var choices = cbDailyAusVal + cbWeeklyIndiaVal + cbBulletinIndiaVal + 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);
}
