﻿// 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.findVenueModalTrigger").hover(function() { $(this).addClass("activeTrigger"); }, function() { $(this).removeClass("activeTrigger"); });
    $("a.findDestinationModalTrigger").hover(function() { $(this).addClass("activeTrigger"); }, function() { $(this).removeClass("activeTrigger"); });
    $("a.findConceptModalTrigger").hover(function() { $(this).addClass("activeTrigger"); }, function() { $(this).removeClass("activeTrigger"); });
    $(".googleMapTrigger").hover(function() { $(this).addClass("activeTrigger"); }, function() { $(this).removeClass("activeTrigger"); });

    if ($('#modalFindVenue').length) {
        $(".findVenueModalTrigger").overlay({
            target: '#modalFindVenue',
            //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
            },
            //Misc
            fixed: false,
            top: 274,
            closeOnClick: false,
            load: false
        });
    }

    if ($('#modalGoogleMap').length) {
        $(".googleMapTrigger").overlay({
            target: '#modalGoogleMap',
            mask: {
                color: '#000000',
                loadSpeed: 200,
                opacity: 0.75,
                closeSpeed: 0   //NOTE: Mad hax to get next overlay to work if triggering one from another
            },
            onLoad: function() {
                initialize();
            },
            top: '5%',
            closeOnClick: false,
            load: false
        });
    }

    if ($('#modalFindDestination').length) {
        $(".findDestinationModalTrigger").overlay({
            target: '#modalFindDestination',
            //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
            },
            //Misc
            fixed: false,
            top: 274,
            closeOnClick: false,
            load: false
        });
    }

    if ($('#modalFindConcept').length) {
        $(".findConceptModalTrigger").overlay({
            target: '#modalFindConcept',
            //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
            },
            //Misc
            fixed: false,
            top: 274,
            closeOnClick: false,
            load: false
        });
    }

    //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',
            //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
            },
            onLoad: function() {
                //Ensure modal header reset
                $("#registrationModal .modalHeader span").empty();
                $("#registrationModal .modalHeader span").append("Join CEI");
                $('[id$="cbWeekly"]').attr('checked', true);
            },
            onBeforeLoad: function() {
                //Check for email value to pre-populate
                //CheckStoredValues();
            },
            //Misc
            top: '5',
            closeOnClick: false,
            load: false
        });
    }

    //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
        });
    }

    //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();

//Request STATES for that Country
    $.ajax({
    url: ajaxGetStatesURL,
    global: false,
    type: "POST",
    data: ({ countryid: countryID }),
    dataType: "html",
    async: false,
    success: function(response) {
            
    //Add default option
    $('[id$="StateDDL_Reg"]').append($("<option></option>").val("").html("-- Select Region --"));            
                
    //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("").html("Other region"));
    }
    }
    }); //end ajax        
    });

//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);

//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;
    }
    }
    }
    });
        
    //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
    $('[id$="CityDDL_Reg"]').change(function() {
    var city = $('[id$="CityDDL_Reg"]').val();
    $('[id$="hdnCity"]').val(city);
    //alert("City value now: '" + $('[id$="CityDDL_Reg"] option:selected').text() + "'");

//If selected 'Other', enable the City textbox
    if ($('[id$="CityDDL_Reg"] option:selected').text() == "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();
    }
    //Check Querystring for force display of Modal
    if (getQueryString()["login"] == "true") {
        $(".loginModalTrigger").overlay().load();
    }
    if (getQueryString()["menu"] == "venue") {
        $(".findVenueModalTrigger").overlay().load();
    }
    if (getQueryString()["menu"] == "concept") {
        $(".findConceptModalTrigger").overlay().load();
    }
    if (getQueryString()["menu"] == "destination") {
        $(".findDestinationModalTrigger").overlay().load();
    }

    //Handle custom close for registration
    $(".closeRegModalTrigger").click(function() {
        $(".registrationModalTrigger").overlay().close();
    });

    //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");
    });
});

/******************************* 
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();

        //Extract Checkbox values
        var cbWeeklyVal = "no"; if ($('[id$="cbWeekly"]').is(':checked')) { cbWeeklyVal = "yes"; }
        var cbEDMVal = "yes"; if ($('[id$="cbEDM"]').is(':checked')) { cbEDMVal = "no"; }
        var cbThirdPartyEDM = "yes"; if ($('[id$="cbThirdPartyEDM"]').is(':checked')) { cbThirdPartyEDM = "no"; }

        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,
                title: $('[id$="TitleDDL_Reg"] :selected').val(),
                firstname: $('[id$="FirstNameTextbox_Reg"]').val(),
                lastname: $('[id$="LastNameTextbox_Reg"]').val(),
                country: $('[id$="CountryDDL_Reg"] :selected').val(),  //ID
                //state: $('[id$="StateDDL_Reg"] :selected').val(),      //ID
                //city: $('[id$="CityDDL_Reg"] :selected').val(),        //ID
                //suburb: $('[id$="CityTextBox_Reg"]').val(),
                //postcode: $('[id$="PostcodeTextbox_Reg"]').val(),
                organization: $('[id$="OrganizationTypeDDL_Reg"] :selected').val(),
                seniority: $('[id$="SeniorityDDL_Reg"] :selected').val(),
                //Newsletters
                nlWeekly: cbWeeklyVal,
                nlEDM: cbEDMVal,
                nlThirdPartyEDM: cbThirdPartyEDM
            }),
            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 span").empty();
                    $("#registrationModal .modalHeader span").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 span").empty();
                    $("#registrationModal .modalHeader span").append("Join CEI");

                    //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 span").empty();
                    $("#registrationModal .modalHeader span").append("Join CEI");

                    //Display message/response from failed Registration attempt
                    $("#ErrorContainer_Reg").show();
                    $("#ErrorContainer_Reg").empty();
                    $("#ErrorContainer_Reg").append(response);
                }
            }
        });                    
    }
    return false;
}

function RegFormValid() {
    //Hide all messages
    $("#ErrorContainer_Reg").hide();
    $("#registrationModal div.validationMsg").hide();

    var valid = true;

    //Check for all required fields
    if ($('[id$="TitleDDL_Reg"]').val() < 0) { $("#rfvTitleDDL_Reg").show(); valid = false; }
    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$="OrganizationTypeDDL_Reg"] :selected').val() == "") { $("#rfvOrganizationTypeTextbox_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$="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;
}

/*******************************
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 CEI");
}

/*******************************
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);
}
