﻿// Function to raise an event.
// "eventName" - String specifying the name of the event to be raised.
// "eventData" - Object containing additional data to be passed to the event handler 
// in the second parameter.
function rbiViper_RaiseEvent(eventName, eventData) {
    jQuery(document).trigger(eventName, eventData);
}


// Function to allow caller to bind an event to an event handler.
// "eventName" - The name of the event to bind to.
// "funtionToExecute" - The event handler function to be called when the event fires.
function rbiViper_RegisterForEvent(eventName, functionToExecute) {
    $(document).ready(function() {
        $(document).bind(eventName, functionToExecute);
    });

}

// Function to allow caller to bind an event to an event handler.
// Also allows passing of extra data via event.data.
// "eventName" - The name of the event to bind to.
// "eventData" - Object containing any extra required data.
// "funtionToExecute" - The event handler function to be called when the event fires.
function rbiViper_RegisterForEventWithEventData(eventName, eventData, functionToExecute) {
    $(document).ready(function() {
        $(document).bind(eventName, eventData, functionToExecute);
    });
}

// Function to update the innerHTML of a DIV element.
// "divElement" - Client Id of the DIV element on the page.
// "newText" - string of text which will be set as the innerHTML property of the element.
function rbiViper_UpdateDiv(divElementId, newText) {

    if (newText != null) {
        // Space is appended to resolve bug in DPA control where space after span was ignored        
        $("#" + divElementId).html(newText + ' ');
    }
}

// Function to display a pop-up alert message.
// Useful for testing that the rbiViper.js file has been imported correctly.
// "message" - The text to display in the pop-up alert.
function rbiViper_ShowAlert(message) {
    alert(message);
}



//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//                  CORE REGISTRATION
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

// Defines the default text for the TitleOther textbox when "Other" is selected from the dropdown list.
var rbiViper_CoreRegWatermarkTitleOther = 'Type your title here';

function rbiViper_CoreRegUpdateStrength(pw) {
    var strength = rbiViper_CoreRegGetStrength(pw);

    rbiViper_CoreRegUpdateStrengthCaption(strength);

    var width = (200 / 30) * strength;

    //set the inner div's width
    document.getElementById('rbiViper_PwStrengthImageDiv').style.width = width + "px";
}

function rbiViper_CoreRegGetStrength(passwd) {

    intScore = 0;

    //NUMBER OF CHARACTERS

    if ((passwd.length > 0)) //more than 0 characters
    {
        intScore = (intScore + 5);
    }

    if ((passwd.length >= 12)) //equals or more than 12 characters
    {
        intScore = (intScore + 10);
    }
    else {
        if ((passwd.length > 6)) //more than 6 but less than 12 characters
        {
            intScore = (intScore + 5);
        }
    }

    // NUMBERS
    if (passwd.match(/\d+/)) // at least one number
    {
        intScore = (intScore + 5);
    }
    // SPECIAL CHAR
    if (passwd.match(/[!,@#$%^&*?_~]/)) // at least one special character
    {
        intScore = (intScore + 5);
    } // COMBOS
    if (passwd.match(/[a-z]/) && passwd.match(/[A-Z]/)) //  both upper and lower case
    {
        intScore = (intScore + 5);
    }


    return intScore;
}

function rbiViper_CoreRegUpdateStrengthCaption(passwordstrength) {
    var strengthCaptionLabel = document.getElementById('rbiViper_PwStrengthCaptionLabel');

    if (passwordstrength == 0) {
        strengthCaptionLabel.innerHTML = '';
    }
    if (passwordstrength > 0 & passwordstrength <= 10) {
        strengthCaptionLabel.innerHTML = 'Weak';
    }
    if (passwordstrength > 10 & passwordstrength <= 25) {
        strengthCaptionLabel.innerHTML = 'Medium';
    }
    if (passwordstrength > 25 & passwordstrength < 35) {
        strengthCaptionLabel.innerHTML = 'Strong';
    }
}

function rbiViper_CoreRegActivateOtherTxt(salutationClientId, titleOtherClientId) {

    var Salutation = document.getElementById(salutationClientId);
    var Other = document.getElementById(titleOtherClientId);
    
    if (Salutation[Salutation.selectedIndex].text == 'Other') {
        Other.disabled = false;
        Other.style.backgroundColor = '#ffffff';
        Other.value = rbiViper_CoreRegWatermarkTitleOther;
        Other.style.fontStyle = 'italic';
        Other.style.color = '#606060'
    }
    else {
        Other.disabled = true;
        Other.value = '';
        Other.style.backgroundColor = '#D9D9D9';
        Other.style.fontStyle = 'normal';
        Other.style.color = '#000000'
    }
}

function rbiViper_CoreRegValidateTitle(sender, args) {
    var OtherTxt = $(".corereg-OtherTxt");
    if (!OtherTxt.attr("disabled")) {
        var otherTxtVal = $.trim(OtherTxt.val());
        if (otherTxtVal == '' || otherTxtVal == '.' || otherTxtVal == rbiViper_CoreRegWatermarkTitleOther) {
            args.IsValid = false;
        }
        else {
            args.IsValid = true;
        }
    }
    else {
        args.IsValid = true;
    }
}

function rbiViper_CoreRegOnFocusTitleOther(elementId) {
    var TitleOther = document.getElementById(elementId);

    if (TitleOther.value == rbiViper_CoreRegWatermarkTitleOther) {
        TitleOther.value = "";
        TitleOther.style.fontStyle = 'normal';
        TitleOther.style.color = '#000000';
    }
}

function rbiViper_CoreRegOnBlurTitleOther(elementId) {
    var TitleOther = document.getElementById(elementId);

    if (TitleOther.value == rbiViper_CoreRegWatermarkTitleOther || TitleOther.value.length == 0) {
        TitleOther.value = rbiViper_CoreRegWatermarkTitleOther;
        TitleOther.style.fontStyle = 'italic';
        TitleOther.style.color = '#606060';
    }
}

function rbiViper_CoreRegTogglePasswordChange() {
    if ($(".corereg-change-password-checkbox input").is(":checked")) {
        $(".corereg-PasswordChangeInput").css("display", "block");
        $(".oldpasswordrequiredvalidator, .passwordrequiredvalidator, .passwordcomparevalidator, .confirmpasswordrequiredvalidator, .oldpasswordvalidator").each(function(i) {
            var validator = $(this);
            if ($("[id$=" + validator.attr("id") + "]")[0] != undefined) {
                $("[id$=" + validator.attr("id") + "]")[0].enabled = true;
                
            }
        });
        ValidatorUpdateIsValid();        
    } else {
        $(".corereg-PasswordChangeInput").css("display", "none");
        $(".oldpasswordrequiredvalidator, .passwordrequiredvalidator, .passwordcomparevalidator, .confirmpasswordrequiredvalidator, .oldpasswordvalidator").each(function(i) {
            ValidatorEnable(this, false);
        });
    }
}
function rbiViper_CoreRegValidateEmailAddress(sender, args) {
    var username = $(".corereg-field-username input").val();
    var confirmUserName = $(".corereg-field-username-confirmemail input").val()
    if (username != '' && confirmUserName != '')
    {
        if (username.toLowerCase() != confirmUserName.toLowerCase())
            args.IsValid = false;
        else
            args.IsValid = true;
    }
    else
        args.IsValid = true;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//                  END OF CORE REGISTRATION
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//                  DEMOGRAPHICS
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

function rbiViper_CheckboxDemographicToggle(demographicControl, demographicID, associatedDemographicID) {
    var associatedDemographic = $(".dmg-item-lvl1[demographicid=" + associatedDemographicID + "]");
    if ($(demographicControl).is(":checked")) 
    {
        rbiViper_EnableDisableDemographicValidator(associatedDemographic, true);
        associatedDemographic.css("display", "block");

        //enable default value
        rbiViper_SelectDefaultDemographicValue(associatedDemographic);
    }
    else {
        // Ensure that there aren't any other demographics associated with this demographic maintaining it's visibility
        var hide = true;
        $(".dmg-item[demographicid=" + demographicID + "] span[associateddemographicid=" + associatedDemographicID + "] input").each(function(i) {
            if ($(this).attr("checked") == true)
                hide = false;
        });
        if (hide) {
            // Hide the demogaphic
            rbiViper_EnableDisableDemographicValidator(associatedDemographic, false);
            associatedDemographic.css("display", "none");
            // Clear all any selected values
            rbiViper_ClearDemographicValues(associatedDemographic);
        }        
    }
}

function rbiViper_RadioDemographicToggle(demographicControl, demographicID, associatedDemographicID) {

    if ($(demographicControl).is(":checked")) {
        // Hide all associated demographics beloning to this radiobutton list demographic
        // Newly selected one will be handled next
        $(".dmg-item[demographicID=" + demographicID + "] span[associateddemographicid]").each(function(i) {
            var thisAssociatedDemographicID = $(this).attr("associatedDemographicID");

            if (thisAssociatedDemographicID != associatedDemographicID) {
                var thisAssociatedDemographic = $(".dmg-item-lvl1[demographicid=" + thisAssociatedDemographicID + "]");
                thisAssociatedDemographic.css("display", "none");               
                
                // disable all validators
                rbiViper_EnableDisableDemographicValidator(thisAssociatedDemographic, false);
                
                // Clear all any selected values
                rbiViper_ClearDemographicValues(thisAssociatedDemographic);                
            }
        });

        // get associated demographic
        var associatedDemographic = $(".dmg-item-lvl1[demographicid=" + associatedDemographicID + "]");

        //enable validator
        rbiViper_EnableDisableDemographicValidator(associatedDemographic, true);

        //enable default value
        rbiViper_SelectDefaultDemographicValue(associatedDemographic);

        associatedDemographic.css("display", "block");
    }
}

function rbiViper_DropdownDemographicToggle(demographicControl, demographicID) {    
    // Hide all associated demographics belonging to this dropdown list demographic
    // Newly selected one will be handled next
    var dropDownControl = $(demographicControl);
    var associatedDemographicID = dropDownControl.find("option:selected").attr("associateddemographicid");
    dropDownControl.find("option[associateddemographicid]").each(function(i) {
        var thisAssociatedDemographicID = $(this).attr("associatedDemographicID");
        
        if (thisAssociatedDemographicID != associatedDemographicID) {
            var thisAssociatedDemographic = $(".dmg-item-lvl1[demographicid=" + thisAssociatedDemographicID + "]");
            thisAssociatedDemographic.css("display", "none");

            // disable all validators
            rbiViper_EnableDisableDemographicValidator(thisAssociatedDemographic, false);

            // Clear all any selected values
            rbiViper_ClearDemographicValues(thisAssociatedDemographic);
        }
    });

    // get associated demographic
    var associatedDemographic = $(".dmg-item-lvl1[demographicid=" + associatedDemographicID + "]");
    associatedDemographic.css("display", "block");
    //enable validator
    rbiViper_EnableDisableDemographicValidator(associatedDemographic, true);
    //enable default value
    rbiViper_SelectDefaultDemographicValue(associatedDemographic);
}

function rbiViper_EnableDisableDemographicValidator(associatedDemographic, enabled) {

    var associatedDemographicType = associatedDemographic.attr("demographictype");
    if (associatedDemographicType != "CheckBox") {
        // get validator
        associatedDemographicValidator = associatedDemographic.find("span[isvalidator=true]");
        // disable validator
        if ($("[id$=" + associatedDemographicValidator.attr("id") + "]")[0] != undefined) {
            $("[id$=" + associatedDemographicValidator.attr("id") + "]")[0].enabled = enabled
            ValidatorUpdateIsValid();
        }
    }
}

function rbiViper_SelectDefaultDemographicValue(associatedDemographic) {
    var associatedDemographicType = associatedDemographic.attr("demographictype");
    if (associatedDemographicType == "RadioButton") {
        hasvalue = false;
        associatedDemographic.find("span[demographicvalueid]").each(function(i) {
            if ($(this).find("input[type=radio]").attr("checked") == true)
                hasvalue = true;
        });
        if (hasvalue == false) {
            associatedDemographic.find("span[demographicvalueid]").each(function(i) {
                var demographicvalueid = $(this).attr("demographicvalueid");
                var isdefault = $(this).attr("isdefault");

                if (isdefault == "true") {
                    $(this).find("input[type=radio]").attr("checked", true);
                }
            });
        }
    }
    else if (associatedDemographicType == "DropDownList") {
        $dropdownlist = associatedDemographic.find("select");
        $('option', $dropdownlist).each(function(i) {
            var isdefault = $(this).attr("isdefault");
            if (isdefault == "true") {
                $(this).attr("selected", "selected");
            }
            else $(this).attr("selected", "");
        });
    }    
}

function rbiViper_ClearDemographicValues(associatedDemographic) {

    if (associatedDemographic != undefined) {
        var associatedDemographicType = associatedDemographic.attr("demographictype");
        if (associatedDemographicType == "CheckBox") {
            associatedDemographic.find("input").attr("checked", false);
        }
        else if (associatedDemographicType == "RadioButton") {
            associatedDemographic.find("span[demographicvalueid]").each(function(i) {
                $(this).find("input[type=radio]").attr("checked", false);
            });
        }
        else if (associatedDemographicType == "DropDownList") {
            associatedDemographic.find("select").val("0");
        }
        else if (associatedDemographicType == "TextArea") {
            associatedDemographic.find("textarea").attr("value", "");
        }
        else if (associatedDemographicType == "TextBox") {
            associatedDemographic.find("input").attr("value", "");
        }
    }
}

// Function to limit input into text areas.
// "textarearef" - 'this' textarea control.
// "maxChar" - max number of chars allowed.
function rbiViper_LimitDemographicText(textarearef, maxChar) {
    var textArea = $(textarearef);
    var text = textArea.val();
    if (text.length > maxChar) {
        textArea.val(text.substr(0, maxChar));        
        return false;
    }
    else {
        return true;
    }
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//                  END OF DEMOGRAPHICS
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//                  LOCATION
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

// Function to retrieve Countries based on Continent.
// "UIServiceURL" - UI Ajax Service URL
// "LocationContainerID" - Location container to be updated.
function rbiViper_GetCountries(UIServiceURL, LocationContainerID) {
    $.ajaxSetup({
    error: rbiViper_HidePendingImgs
    });
    // Update the hidden field values
    var ContinentId = $("#LocationContainer" + LocationContainerID + " .WorldRegionDropDownList").val();
    $("#LocationContainer" + LocationContainerID + " input[name$='CountryIDHiddenField']").val(0);
    $("#LocationContainer" + LocationContainerID + " input[name$='RegionIDHiddenField']").val(0);
    $("#LocationContainer" + LocationContainerID + " .imgCountriesLoading").css("display", "inline");
    // Empty current Countries
    var CountryDropDown = $("#LocationContainer" + LocationContainerID + " .CountryDropDownList");
    CountryDropDown.find(">option").remove();
    CountryDropDown.attr("disabled", true);
    CountryDropDown.addClass("loc-dropdowncontrol-disabled");
    // Empty the regions as well
    var RegionDropDown = $("#LocationContainer" + LocationContainerID + " .RegionDropDownList");
    RegionDropDown.find(">option").remove();
    RegionDropDown.attr("disabled", true);
    RegionDropDown.addClass("loc-dropdowncontrol-disabled");
    $.getJSON(UIServiceURL + "?op=GetCountriesByContinent&ContinentId=" + ContinentId + "&jsonp=?",
        function(data) {
            if (data != null && data.length > 0) {
                CountryDropDown.removeAttr("disabled");
                CountryDropDown.removeClass("loc-dropdowncontrol-disabled");
                CountryDropDown.append($('<option></option').val(0).html("Please select"));
                $.each(data, function() {
                    CountryDropDown.append($('<option></option').val(this.LocationID).html(this.LocationDescription));
                });
            }
            rbiViper_HidePendingImgs();
        });
}
// Function to retrieve Regions based on Country.
// "UIServiceURL" - UI Ajax Service URL
// "LocationContainerID" - Location container to be updated.
function rbiViper_GetRegions(UIServiceURL, LocationContainerID) {
    $.ajaxSetup({
    error: rbiViper_HidePendingImgs
    });
    // Update the hidden field values
    var CountryId = $("#LocationContainer" + LocationContainerID + " .CountryDropDownList").val();
    $("#LocationContainer" + LocationContainerID + " input[name$='CountryIDHiddenField']").val(CountryId);
    $("#LocationContainer" + LocationContainerID + " input[name$='RegionIDHiddenField']").val(0);
    $("#LocationContainer" + LocationContainerID + " .imgRegionsLoading").css("display", "inline");
    // Empty the regions
    var RegionDropDown = $("#LocationContainer" + LocationContainerID + " .RegionDropDownList");
    RegionDropDown.find(">option").remove();
    RegionDropDown.attr("disabled", true);
    RegionDropDown.addClass("loc-dropdowncontrol-disabled");
    $.getJSON(UIServiceURL + "?op=GetRegionsByCountry&CountryId=" + CountryId + "&jsonp=?",
        function(data) {
            if (data != null && data.length > 0) {
                RegionDropDown.removeAttr("disabled");
                RegionDropDown.removeClass("loc-dropdowncontrol-disabled");
                RegionDropDown.append($('<option></option').val(0).html("Please select"));
                $.each(data, function() {
                    RegionDropDown.append($('<option></option').val(this.LocationID).html(this.LocationDescription));
                });
            }
            rbiViper_HidePendingImgs();
        });
}

// Function to retrieve Regions based on Country.
// "LocationContainerID" - Location container to be updated.
function rbiViper_SetRegion(LocationContainerID) {
    // Update the hidden field values
    var RegionId = $("#LocationContainer" + LocationContainerID + " .RegionDropDownList").val();
    $("#LocationContainer" + LocationContainerID + " input[name$='RegionIDHiddenField']").val(RegionId);
}

// Function to hide all pending ajax request images.
function rbiViper_HidePendingImgs() {
    // Hide pending imgs
    $(".location-pendingimg").css("display", "none");
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//                  END OF LOCATION
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//                  NEWSLETTER
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

function rbiViper_MandatoryNewsletterValidate(sender, args) {
    var validator = $(sender);
    var checkBox = validator.parent().find("div.nlt-tristatecheckbox input");
    if (checkBox.is(":checked")) {
        args.IsValid = true;
    }
    else {
        args.IsValid = false;
    }
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//                  END OF NEWSLETTER
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
