﻿// 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) {
    if (document.getElementById('rbiViper_PwStrengthImageDiv') != null) {
        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) {
    if (document.getElementById('rbiViper_PwStrengthCaptionLabel') != null) {
        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 = $(".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[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[demographicID=" + demographicID + "] span[associateddemographicid]").each(function(i) {
            var thisAssociatedDemographicID = $(this).attr("associatedDemographicID");

            if (thisAssociatedDemographicID != associatedDemographicID) {
                var thisAssociatedDemographic = $(".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 = $(".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 = $(".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 = $(".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.tristatecheckbox input");
    if (checkBox.is(":checked")) {
        args.IsValid = true;
    }
    else {
        args.IsValid = false;
    }
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//                  END OF NEWSLETTER
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//                  BULK UPLOAD
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

// Create a pager with the specified number of pages
function createPager(numPages) {
    // Remove any existing pager
    $("#pager").remove();

    // Don't create if not necessary
    if (numPages == 1) return;

    // Clone pager template
    var pager = $("#template-pager")
        .clone()
        .attr("id", "pager")
        .find("#template-pagercontent")
            .removeAttr("id");

    // Loop from page numbers 1..numPages
    for (page = 1; page <= numPages; page++) {
        if (page == currentPage) {
            // Not a link for the current page
            $("<td></td>")
                .appendTo(pager)
                .text(page)
                .addClass("current");
        }
        else {
            // Create link
            $("<td><a href='#'></a></td>")
                .appendTo(pager)
                .find("a")
                    .text(page)
                    .attr("page", page)
                    .click(function(e) {
                        e.preventDefault();

                        var newPage = $(this).attr("page");
                        changeDisplaySettings(sortColumn, sortDirection, newPage);
                    });
        }
    }

    // Add pager to table
    $("#jobs > tfoot").append(pager.end());
}

// Show the supplied collection of jobs
function displayJobs(jobs) {
    if ($(jobs).length == 0) {
        $("#notice-norecords").show();
        return;
    }

    $(jobs).each(function() {
        // Clone empty job row
        var newRow = $("#template-jobrow").clone().removeAttr("id").show();

        // Populate with job information
        showJobInRow(newRow, this);

        // Add to table
        $("#jobs > tbody").append(newRow);
    });

    // Apply alternating row styles to table
    $("#jobs tr:even").addClass("rbi-grid-row");
    $("#jobs tr:odd").addClass("rbi-grid-alternate-row");

    // Display table
    $("#notice-norecords").hide();
    $("#jobs").show();
}


// jQuery extensions
jQuery.fn.onlyEnableLinkIf = function(condition) {
    // If condition is false, set 'disabled' attribute and remove 'href' on links, 
    // otherwise do the opposite.
    if (condition) {
        return this.each(function() {
            $(this).removeAttr("disabled").attr("href", "#");
        });
    }

    return this.each(function() {
        $(this).attr("disabled", "disabled").removeAttr("href");
    });
};

jQuery.fn.onlyShowIf = function(condition) {
    // If condition is false, hide each element, otherwise show.
    if (condition) {
        return this.each(function() { $(this).show(); });
    }

    return this.each(function() { $(this).hide(); });
}

// Show a confirmation dialog next to parentElement with the specified message
// and perform the action in callback if the user confirms.
function ifConfirmed(parentElement, message, callback) {
    $("#popup-confirmation")
        .find("#message")
            // Set message text
            .text(message)
        .end()
        .find(".oklink")
            // Hook up 'OK' link
            .unbind("click")
            .click(function(e) {
                e.preventDefault();
                $("#popup-confirmation").fadeOut();
                callback();
            })
        .end()
        .find(".cancellink")
            // Hook up 'cancel' link
            .unbind("click")
            .click(function(e) {
                e.preventDefault();
                $("#popup-confirmation").fadeOut();
            })
        .end()
        // Position at location of parent element
        .css({
            top: parentElement.offset().top,
            left: parentElement.offset().left
        })
        .fadeIn();
}

function showChangePriorityPopup(row, job) {
    var displayPosition = row.find(".changeprioritylink").offset();

    var popup = $("#popup-changepriority");

    // Position and show popup
    popup.css({
        top: displayPosition.top,
        left: displayPosition.left
    })
    .fadeIn();

    // Populate values and highlight text
    popup.find("#oldpriority").text(job.Priority);
    popup.find("#newpriority")
        .val(job.Priority)
        .focus()
        .select()

    // Hook up textbox event handlers
    var enterKeyCode = 13;
    var backspaceKeyCode = 8;
    var deleteKeyCode = 46;
    var arrowLeftKeyCode = 37;
    var arrowRightKeyCode = 39;

    popup.find("#newpriority")
        // Confirm when enter key pressed
        .unbind("keypress")
        .bind("keypress", { jobRow: row }, function(e) {
            if (e.keyCode != enterKeyCode) return;

            e.preventDefault();
            var newPriority = $(this).val();
            changePriorityOfJob(job.Id, e.data.jobRow, newPriority);
            popup.fadeOut();
        })
        // Restrict to numeric input
        .keydown(function(e) {
            var allowedKeys = [
                enterKeyCode, backspaceKeyCode, deleteKeyCode, arrowLeftKeyCode, arrowRightKeyCode,
                48, 49, 50, 51, 52, 53, 54, 55, 56, 57, // Number keys
                96, 97, 98, 99, 100, 101, 102, 103, 104, 105 // Numeric keypad
            ];

            if ($.inArray(e.keyCode, allowedKeys) == -1) {
                e.preventDefault();
            }
        });

    // Hook up OK link events
    popup.find(".oklink")
        .unbind("click")
        .bind("click", { jobRow: row }, function(e) {
            e.preventDefault();

            var newPriority = popup.find("#newpriority").val();
            changePriorityOfJob(job.Id, e.data.jobRow, newPriority);
            popup.fadeOut();
        });

    // Hook up cancel link event
    popup.find(".cancellink").click(function(e) {
        e.preventDefault();
        popup.fadeOut();
    });
}

// Delete the currently selected jobs
function deleteSelectedJobs() {
    // Find out which jobs are selected for deletion
    var jobIdsToDelete = [];
    $("#jobs tr .deletecheckbox:checked").each(function() {
        jobIdsToDelete.push($(this).closest("tr").data("jobid"));
    });

    if (jobIdsToDelete.length == 0) {
        alert("No jobs have been selected to delete");
        return;
    }

    // Confirm job deletion
    ifConfirmed($("#deleteselectedlink"), "Delete " + jobIdsToDelete.length + " jobs?", function() {
        // Make AJAX call to delete selected jobs
        var json = '{ jobIds: [' + jobIdsToDelete.join(",") + '] }';

        $.ajax({
            type: "POST",
            url: 'BulkUploadJobList.aspx/DeleteJobs',
            data: json,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
                loadRecords();
            }
        });
    });
}
function rbiViper_HideServerError() {
    $(".rbi-label-server-error").hide();
}

function changePriorityOfJob(jobId, jobRow, newPriority) {
    var json = '{ jobId: ' + jobId.toString() + ', newPriority: ' + newPriority + ' }';

    $.ajax({
        type: "POST",
        url: 'BulkUploadJobList.aspx/ChangeJobPriority',
        data: json,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {
            showJobInRow(jobRow, msg.d);
        }
    });
}

function changeJobStatus(jobId, newStatus, jobRow) {
    var json = '{"jobId": "' + jobId.toString() + '", "status": "' + newStatus + '" }';

    $.ajax({
        type: "POST",
        url: 'BulkUploadJobList.aspx/ChangeJobStatus',
        data: json,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {
            // If this change affects the sort order, reload the page, otherwise just update the row.
            if (sortColumn == "Status") {
                loadRecords();
            }
            else {
                showJobInRow(jobRow, msg.d);
            }
        }
    });
}

function showSortIndicator(sortedColumn, sortDirection) {
    // Remove previous sort indicator
    $("#sortindicator").remove();

    var ascImage = "Images/sortasc.gif";
    var descImage = "Images/sortdesc.gif";

    // Determine the correct image
    var image;
    if (sortDirection == "asc") {
        image = ascImage;
    }
    else if (sortDirection == "desc") {
        image = descImage;
    }
    else {
        alert("unknown sort order");
        return;
    }

    // Find the appropriate header row and add the image element
    $(".rbi-grid-header-row :contains('" + sortedColumn + "')")
        .closest("th")
        .append($("<img id='sortindicator' src='" + image + "' />"));
}

function loadRecords() {
    $.ajax({
        type: "POST",
        url: 'BulkUploadJobList.aspx/GetJobs',
        data: '{"pageNumber":"' + currentPage + '","sortColumn":"' + sortColumn + '","sortDirection":"' + sortDirection + '"}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {
            // Clear table
            $("#jobs > tbody").empty();

            displayJobs(msg.d.Jobs);
            createPager(msg.d.NumberOfPagesRequired);
            showSortIndicator(sortColumn, sortDirection);
        }
    });
}

function hookupGlobalAjaxEvents() {
    // Show/hide loading panel on start/finish AJAX call
    $("#popup-loadingindicator")
        .ajaxStart(function() { $(this).show(); })
        .ajaxComplete(function() { $(this).hide(); });

    // Handle any AJAX errors
    $("#error").ajaxError(function(e, xhr, settings, ex) {
        // Redirect to login page if 401
        if (xhr.status == 401) {
            window.location = 'Login.aspx?ReturnUrl=BulkUploadJobList.aspx';
            return;
        }

        // Show error notice with details
        var errorText = xhr.responseText.replace('\\r\\n', '<br />');
        $("#error").show().find("#errortext").html(errorText);
        $("#jobs").hide();
    })

    // Hide error notice on successful AJAX call
    $("#error").ajaxSuccess(function() {
        $(this).hide();
    });
}

function sortJobs(newSortColumn) {
    var newSortDirection = "asc";

    // Go back to first page when re-sorting
    var newPage = 1;

    // If sorting on same column as before, swap direction and maintain page number
    if (sortColumn == newSortColumn) {
        if (sortDirection == newSortDirection) {
            newSortDirection = "desc";
            newPage = currentPage;
        }
    }

    changeDisplaySettings(newSortColumn, newSortDirection, newPage)
}

function changeDisplaySettings(sortColumn, sortDirection, currentPage) {
    // Hide any popups that are visible
    $(".popup").fadeOut();

    // Just push new state onto history stack, the window hashchange event will take care of everything else.
    $.bbq.pushState({ sortColumn: sortColumn, sortDirection: sortDirection, currentPage: currentPage });
}

function rbiViper_RestrictMaximumLimit(text, limit) {
    var i = parseInt(limit)
    if (text.value.length > i) {
        text.value = text.value.substring(0, i);
        alert("You have exceeded the maximum character limit");
    }
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//                  END OF BULK UPLOAD
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//                  Function to ensure focus returns to the subject of validation errors
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


function setFocusOnValidationErrorAssociatedControls() {
    // Are there any validation errors displayed?
    $(".item_error").each(function() {
        var validatorErrorLbl = $(this);
        //":visible" returns true even if CSS visibility property is set to hidden so need to check for that also
        if ((validatorErrorLbl.is(":visible")) && (validatorErrorLbl.css('visibility') != 'hidden')) {
            // Find the sibling input - check for normal input fields (textboxes, check boxes etc)
            var siblingInput = validatorErrorLbl.siblings("input");
            if (siblingInput != null && siblingInput.size() > 0) {
                siblingInput.focus();
                // Break from iteration
                return false;
            }
            // If we didn't find one there, check for drop down lists
            var siblingInput = validatorErrorLbl.siblings("select");
            if (siblingInput != null && siblingInput.size() > 0) {
                siblingInput.focus();
                // Break from iteration
                return false;
            }
            //If we get here, it's possible the error is from a Newsletter checkbox
            siblingInput = validatorErrorLbl.siblings(".tristatecheckbox");
            if (siblingInput != null && siblingInput.size() > 0) {
                siblingInput.children("input").focus();
                // Break from iteration
                return false;
            }
            //TODO If we can't find any input to focus on, we could scroll to the validatorErrorLbl
            //This requires a plugin to jQuery however
        }
    });
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//     START OF MULTISELECT
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

function rbiViper_ProductMutliSelectDropdown() {
    $('.multiselectdropdown').multiSelect({ noneSelected: 'Select Distribution Methods', oneOrMoreSelected: '*' });
    $('.multiselectdropdownedit').multiSelect({ noneSelected: 'Select Distribution Methods', oneOrMoreSelected: '*', multiSelectClass: 'multiSelectcustom', multiSelectOptionClass: 'multiSelectOptionscustom' });
}

function rbiViper_ProductItemMutliSelectDropdown() {

    setTimeout(function() {
        $('.multiselectdropdown').multiSelect({ noneSelected: 'Select Distribution Methods', oneOrMoreSelected: '*' });
        $('.multiselectdropdownedit').multiSelect({ noneSelected: 'Select Distribution Methods', oneOrMoreSelected: '*' });
    }, 0);
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//   END OF MULTISELECT
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//   START OF LICENCE KEY ACTIVATION
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

function rbiViper_LicenceActivationValidateLicenceKey(sender, args) {
    args.IsValid = true;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//   END OF LICENCE KEY ACTIVATION
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

