﻿function showLoading(title) {
    if (title == null)
        title = 'Loading';
    $("#loading").dialog('option', 'title', title);
    $("#loading").dialog('open');
}

function hideLoading() {
    $("#loading").dialog('close');
}
function openModal(modal) {
    $(modal).dialog('open');
}
function closeModal(modal) {
    $(modal).dialog('close');
}

function openModalWithOptions(modal, options) {
    $(modal).dialog('option', options);
    $(modal).dialog('open');
    return false;
}

function showMessagesWithTitle(message, theTitle) {
    var options = { title: '' + theTitle + '' };
    $('#dvAlertPopup').find('#AlertMessage').html(message)
    openModalWithOptions('#dvAlertPopup', options)
}

function showErrorMessages(errMsg, theTitle) {
    var startString = '<ul class="errorDetails">';
    var finalString = '</ul>'
    var filler = '';

    var charPos = errMsg.indexOf(';');
    if (charPos === 0) {
        filler = '<li>' + errMsg + '</li>';
    }
    else {
        var col_array = errMsg.split(';');
        var part_num = 0;
        while (part_num < col_array.length) {
            filler += '<li>' + col_array[part_num] + '</li>';
            part_num += 1;
        }
    }

    var errorMessage = startString + filler + finalString;
    showMessagesWithTitle(errorMessage, theTitle);
}

function setupHoverRow() {
    $("table.grid tbody tr.HoverRow").hover(
        function () {
            $(this).addClass("hoverRowIE");
        },
        function () {
            $(this).removeClass("hoverRowIE");
        }
    );
}
function setupAltRows() {
    $("table.grid tbody tr:even").addClass("altRow");
}
String.prototype.startsWith = function (str) {
    return (this.indexOf(str) === 0);
}

//Default Date Calendar
function setupDefaultCalendar(id, imageUrl) {
    setupDefaultCalendarOnControl($("#" + id), imageUrl);
}

function setupDefaultCalendarOnControl(control, imageUrl) {
    setupCalendarOnControlWithOptions(control, imageUrl, null);
}

function setupCalendarOnControlWithOptions(control, imageUrl, options) {
    if ((typeof (options) != 'object') || (options == null))
        options = new Object();

    if ((imageUrl == null) || (imageUrl == ''))
        imageUrl = applicationPath + 'Content/Images/calendar.gif';

    if (typeof (options.dateFormat) == 'undefined') options.dateFormat = 'dd/mm/yy';
    if (typeof (options.constrainInput) == 'undefined') options.constrainInput = true;
    if (typeof (options.firstDay) == 'undefined') options.firstDay = 1;
    if (typeof (options.duration) == 'undefined') options.duration = 'fast';
    if (typeof (options.changeMonth) == 'undefined') options.changeMonth = false;
    if (typeof (options.changeYear) == 'undefined') options.changeYear = false;
    if (typeof (options.showOn) == 'undefined') options.showOn = 'button';
    if (typeof (options.buttonImageOnly) == 'undefined') options.buttonImageOnly = true;
    if (typeof (options.buttonImage) == 'undefined') options.buttonImage = imageUrl;

    control.datepicker(options);
}

function disableButton(button) {
    $(button).attr("disabled", "disabled");
    $(button).addClass("disabled");
}

function enableButton(button) {
    $(button).attr("disabled", "");
    $(button).removeClass("disabled");
}

function prependImage(jqObj, imageUrl) {
    var img = "<img src='" + imageUrl + "' /> ";
    var jHtml = jqObj.html();
    jqObj.html(img + jHtml);
    jqObj.addClass("button");
}

function ValidateForm(formName) {
    var myForm = $("#" + formName);
    var errors;
    if (myForm[0]['__MVC_FormValidation']) {
        errors = myForm[0]['__MVC_FormValidation'].validate("submit");        // Validate the form
    }
    if (!myForm[0]['__MVC_FormValidation'] || errors.length == 0) {
        return true;
    }
    else {
        return false;
    }
}

String.prototype.encodeHTML = function () {
    var encodeChars = [['&', '&amp;'], ['\"', '&quot;'], ['<', '&lt;'], ['>', '&gt;']];
    var encodeCharsLen = encodeChars.length;
    var len = this.length;
    var result = [];

    for (var i = 0; i < len; i++) {
        var c = result[i] = this.charAt(i);
        for (var l = 0; l < encodeCharsLen; ++l) {
            if (c == encodeChars[l][0]) {
                result[i] = encodeChars[l][1];
                break;
            }
        }
    }
    return result.join('');
}

function checkExpiryDate(expiryMonth, expiryYear) {
    var month = parseInt('<%=DateTime.Now.Month %>');
    var year = parseInt('<%= DateTime.Now.Year.ToString().Substring(2,2) %>');
    var selectedMonth = parseInt($(expiryMonth).val());
    var selectedYear = parseInt($(expiryYear).val());

    if (selectedYear === year) {
        if (selectedMonth < month) {
            return false;
        }
    }
    return true;
}

function setupSpinControl(control, min, max, value, width, mask) {
    control.spin({ min: min, max: max, imageBasePath: applicationPath + 'Content/images/' });
    control.mask(mask);    
    control.val(value);
    control.css('width', width);
}

function pad(number, length) {
    var str = '' + number;
    while (str.length < length) {
        str = '0' + str;
    }
    return str;
}

function ValidEmailAddress(emailAddress) {
    var validEmailAddress = false;
    ///^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
    var emailReg = /^[a-zA-Z0-9._+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;




    if (emailReg.test(emailAddress)) {
        validEmailAddress = true;
    }
    return validEmailAddress;
}

$(
    function () {
        //Show the menu navigation above tabs
        $("ul.navMenu li").maxZIndex({ inc: 5 });
    });

function CollapsibleHeadingCollapse(id)
{
    $('#' + id + ' div.CollapsibleHeadingCollapse').click();
}

function CollapsibleHeadingExpand(id)
{
    $('#' + id + ' div.CollapsibleHeadingExpand').click();
}

function CollapsibleHeadingToggle(id)
{
    if ($('#' + id + ' div.CollapsibleHeadingCollapse').is(':visible'))
        CollapsibleHeadingCollapse(id);
    else
        CollapsibleHeadingExpand(id);
}

function SetCollapsibleButtonText(id, btn)
{
    var html = btn.html();
    if ($('#' + id + ' div.CollapsibleHeadingCollapse').is(':visible'))
        html = html.replace(/SHOW CRITERIA/g, 'HIDE CRITERIA')
    else
        html = html.replace(/HIDE CRITERIA/g, 'SHOW CRITERIA')
    btn.html(html);
}

function showFancyBox(html)
{
    $.fancybox(html, { cyclic: false, showNavArrows: false, titleShow: false, transitionIn: 'elastic', transitionOut: 'elastic', overlayOpacity: 0.2});
}

function showFancyBoxModal(html)
{
    $.fancybox(html, { modal: true, cyclic: false, showNavArrows: false, titleShow: false, transitionIn: 'elastic', transitionOut: 'elastic', overlayOpacity: 0.2});
}

function showFancyBoxForElement(el)
{
    el.fancybox({ cyclic: false, showNavArrows: false, titleShow: false, transitionIn: 'elastic', transitionOut: 'elastic', overlayOpacity: 0.2});
}

function showFancyBoxModalForElement(el)
{
    el.fancybox({ modal: true, cyclic: false, showNavArrows: false, titleShow: false, transitionIn: 'elastic', transitionOut: 'elastic', overlayOpacity: 0.2});
}

function hideFancyBox()
{
    $.fancybox.close();   
}

//The function adds required script to fancy box popup because it removes dynamically added script tags before display. 

function AppendPagerScript(addressDialog, reloadFunction)
{
    var code = " function prevNext (me, add) { var pageIndex = $('" + addressDialog + "').find('#PageIndex'); var page = pageIndex.val(); "
    code += " if(add < 0) { page--; } else {	page++;	} pageIndex.val(page); " + reloadFunction + " }";
                		
    var objScript = document.createElement( "script" );
    objScript.language = "javascript";
    objScript.type = "text/javascript";
    objScript.defer = true;
    objScript.text = code;
    $(addressDialog)[0].appendChild(objScript);   
}

//The function sets contact no: if phone no: or mobile no: is entered or selected from a list.

function SetContactNo(containerId, controlPrefix)
{
    var ContactPhoneAndMobile = $(containerId).find('#' + controlPrefix + 'PhoneAndMobile');
    var ContactPhoneNumber = $(containerId).find('#' + controlPrefix + 'PhoneNumber');
    var ContactMobileNumber = $(containerId).find('#' + controlPrefix + 'MobileNumber');
    
    ContactPhoneAndMobile.val("");

    if(ContactPhoneNumber.val() != '')
        ContactPhoneAndMobile.val(ContactPhoneNumber.val());
    else
        ContactPhoneAndMobile.val(ContactMobileNumber.val());   
}


function IsCustomerOnHold(CustomerId, customerDropdown)
{
    var returnVal=false;
    $.ajax(
    {
        type: 'GET',
        url: applicationPath + 'Common/IsCustomerOnHold',
        data: 'customerId=' + CustomerId,
        async: false,
        success: function (data, textStatus)
        {
            returnVal = data.CustomerOnHold;
            if(data.CustomerOnHold == undefined)
            {
                showFancyBox(data);
                $(customerDropdown + ' option:first-child').attr("selected", "selected");
                returnVal = true;
            }
        }
    });
    return returnVal;
}

function SetupHoverRow (container)
{
    $(container + " tbody tr.HoverRow").hover(function () { $(this).addClass("hoverRowIE"); }, function () { $(this).removeClass("hoverRowIE"); });
}

function CCEmailValidate(value) 
{
    var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
    var array = value.split(';');
    for (var i = 0; i < array.length; i++) {
        if (!array[i].match(emailReg))
            return false;
    }
    return true;
}
