
var accountStatusList = { "show": true, "initialValue": "0", "items": [{ "text": "SelectStatus", "value": "0" }, { "text": "strActive", "value": "1" }, { "text": "strDeleted", "value": "2" }, { "text": "strOnHold", "value": "3" }, { "text": "GN0000348", "value": "4" }, { "text": "GN00001546", "value": "5" }, { "text": "GN0000861", "value": "6" }, { "text": "SPT002056", "value": "7" }, { "text": "SPT002057", "value": "8" }, { "text": "SPT002058", "value": "9" }, { "text": "SPT002059", "value": "10" }] };

if (getCookie("MachPanel_PageSize") && getCookie("MachPanel_PageSize") != '')
    gridPageSize = parseInt(getCookie("MachPanel_PageSize").split("=")[1]);

const fetchGet = {
    method: 'Get',
    headers: new Headers({
        'Content-Type': 'application/json; charset=UTF-8',
        'Accept': 'application/json;'
    })
}

const fetchPost = {
    method: 'Post',
    headers: new Headers({
        'Content-Type': 'application/json; charset=UTF-8',
        'Accept': 'application/json;'
    })
}
const { fetch: origFetch } = window;
window.fetch = async (...args) => {

    //console.log("fetch called with args:", args);

    //console.log("fetch called with args:", ({ ...args })[0]);
    $('.page-loader-wrapper').show();

    const response = await origFetch(...args);

    $('.page-loader-wrapper').show();

    if (!response.ok) {

        let j = "";

        try {
            j = await response.json();
        }
        catch {
        }

        $('.page-loader-wrapper').hide();

        if (j != "")
            throw new Error(j.Message, { cause: (j.ExceptionType == 'MachSol.MachPanel.Utility.MPValidationException' ? "" : j.ExceptionType + " " + j.StackTrace) });
        else
            throw new Error("Invalid response " + response.status, { cause: "Invalid url or server not found " + ({ ...args })[0] });

    }
    else {
        let j = await response
            .clone()
            .json();
        if (j.d && !j.d.success && j.d.message) {
            $('.page-loader-wrapper').hide();
            throw new Error(j.d.message, { cause: j.d.code });
        }
    }
    /* work with the cloned response in a separate promise
       chain -- could use the same chain with `await`. */

    $('.page-loader-wrapper').show();

    response
        .clone()
        .json()
        .then(data => { //console.log("intercepted response data:", data);            
            $('.page-loader-wrapper').hide();
            $('.option-menu').hover(optionMenuMouseHoverHandler);
            $('.option-menu').mouseleave(optionMenuMouseLeaveHandler);
            //$.AdminBSB.dropdownMenu.activate();
            setTimeout(function () { if ($.AdminBSB) $.AdminBSB.dropdownMenu.activate(); updateSelectInterface(); }, 100);
        })
        .catch(err => {
            $('.page-loader-wrapper').hide();
        });

    /* the original response can be resolved unmodified: */

    return response;

};

async function getLocale() {

    let c = getCookie('LocaleDateInfo');
    //console.log('c:', c);
    let l;
    if (c) {
        try {
            //console.log('c2:', window.atob(c));
            l = JSON.parse(window.atob(c))
        } catch (e) {
            console.error(e);
        }
    }
    if (!l) {
        l = {};

        await fetch("/webservices/machpanelservice.asmx/GetDatePickerUIInfo", fetchGet)

            .then(response => response.json()).then((data) => {

                l = JSON.parse(data.d);

            })
            .catch(function (e) {
                displayErrorMsg(e);
            });
    }
    return l;
}

var locale = 'en-US';
var datePattern = 'mm/dd/yyyy';
var language = 'en-US';

async function getDateGlobalSettings() {

    let previewData = await getLocale();
    locale = previewData.locale;
    language = previewData.language;
    datePattern = previewData.pattern;
}

getDateGlobalSettings();

//}, 10);


Array.prototype.move = function (from, to) {
    this.splice(to, 0, this.splice(from, 1)[0]);
};

/**
 * Set property in source list with given value when matched with target list property to match.
 * Example: customers.setPropertyFromListOfObjects('selected', true, 'value', data.d.selectedCustomers, false);
 * /
 * @param {String} propNameToSet Name of property to set in source list.
 * @param {any} valToSet Value to set in source list.
 * @param {String} propNameToMatch Name of property to match in target and source list.
 * @param {Array} targetList Array of objects whose property to match, it must consist of objects that u want as selected.
 * @param {any} defaultVal default val to set for all items in propNameToSet when given, otherwise pass null or do not pass.
 */
Array.prototype.setPropertyFromListOfObjects = function (propNameToSet, valToSet, propNameToMatch, targetList, defaultVal) {

    this.clearPropertySelectionFromList(propNameToSet, defaultVal);

    this.forEach(i => {
        if (targetList.find(t => t[propNameToMatch] == i[propNameToMatch]))
            i[propNameToSet] = valToSet;
    });
};

/**
 * Set property in source list of objects with given value when matched with target list property to match.
 * Example: customers.setSelectedListByListOfObjects(data.d.selectedCustomers);
 * /
 * @param {Array} targetList Array of objects whose property to match.
 */
Array.prototype.setSelectedListByListOfObjects = function (targetList) {

    this.setPropertyFromListOfObjects('selected', true, 'value', targetList, false);
};

/**
 * Set property in source list with given value when matched with target list property to match.
 * Example: customers.setPropertyFromListOfVals('selected', true, 'value', data.d.selectedCustomerIds, false);
 * /
 * @param {String} propNameToSet Name of property to set in source list.
 * @param {any} valToSet Value to set in source list.
 * @param {String} propNameToMatch Name of property to include in target list.
 * @param {Array} targetList Array of values whose property to match.
 * @param {any} defaultVal default val to set for all items in propNameToSet when given, otherwise pass null or do not pass.
 */
Array.prototype.setPropertyFromListOfVals = function (propNameToSet, valToSet, propNameToMatch, targetList, defaultVal) {

    this.clearPropertySelectionFromList(propNameToSet, defaultVal);

    this.forEach(i => {
        if (targetList.includes(i[propNameToMatch]))
            i[propNameToSet] = valToSet;
    });
};

/**
 * Set property in source list of objects with given value when matched with target list property to match.
 * Example: customers.setSelectedListByListOfVals(data.d.selectedCustomerIds);
 * /
 * @param {Array} targetList Array of objects whose property to match.
 */
Array.prototype.setSelectedListByListOfVals = function (targetList) {

    this.setPropertyFromListOfVals('selected', true, 'value', targetList, false);
};

/**
 * Clear selected list on basis of given property in source list.
 * Example: customers.clearPropertySelectionFromList('selected', false);
 * /
 * @param {String} propNameToSet Name of property to set in source list.
 * @param {any} defaultVal default val to set for all items in propNameToSet when given, otherwise pass null or do not pass.
 */
Array.prototype.clearPropertySelectionFromList = function (propNameToSet, defaultVal) {

    if (defaultVal != undefined && defaultVal != null)
        this.forEach(i => {
            i[propNameToSet] = defaultVal;
        });
};

/**
 * Clear selected source list.
 * Example: customers.clearSelection();
 */
Array.prototype.clearSelection = function () {
    this.clearPropertySelectionFromList('selected', false);
};

//****** START: URLSearchParams Customizations https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams#browser_compatibility *********
URLSearchParams.prototype.has = function (key) {
    let x = false;
    for (const k of this.keys()) {
        if (k.toLowerCase() == key.toLowerCase()) { x = true; break; }
    }
    return x;
}

URLSearchParams.prototype.get = function (key) {
    let x = null;
    for (const [k, val] of this.entries()) {
        if (k.toLowerCase() == key.toLowerCase()) { x = val; break; }
    }
    return x;
}
//****** END: URLSearchParams Customizations *********

function displayErrorMsg(e) {
    clearAllMsgs();
    $("#ctl00_Div_UPMessageForJS").attr('style', 'display: ""')
    $("#ctl00_Div_MessageForJS").addClass("errorMsg YOverFlowMsg");
    if (e.body)
        $("#ctl00_Div_MessageForJS").html(e.body.Message);
    else
        $("#ctl00_Div_MessageForJS").html(e.message + ' ' + (e.cause ? e.cause : ''));
    console.error(e.toString());
    window.scrollTo(0, 0);

}

function displaySuccessMsg(msg) {
    clearAllMsgs();
    $("#ctl00_Div_UPMessageForJS").attr('style', 'display: ""')
    $("#ctl00_Div_MessageForJS").addClass("successMsg YOverFlowMsg");
    $("#ctl00_Div_MessageForJS").html(msg);

    window.scrollTo(0, 0);
}

function displayInfoMsg(msg) {
    clearAllMsgs();
    $("#ctl00_Div_UPMessageForJS").attr('style', 'display: ""')
    $("#ctl00_Div_MessageForJS").addClass("infoMsg YOverFlowMsg");
    $("#ctl00_Div_MessageForJS").html(msg);

    window.scrollTo(0, 0);

}

function displayWarningMsg(msg) {
    clearAllMsgs();
    $("#ctl00_Div_UPMessageForJS").attr('style', 'display: ""')
    $("#ctl00_Div_MessageForJS").addClass("warnMsg YOverFlowMsg");
    $("#ctl00_Div_MessageForJS").html(msg);

    window.scrollTo(0, 0);
}

function clearAllMsgs() {
    $("#ctl00_Div_MessageForJS").removeClass();

    $("#ctl00_Div_MessageForJS").html('');
    $("#ctl00_Div_UPMessageForJS").attr('style', 'display: none');

    //**** Scroll on top of the page when any action is performed like pager change etc. *******
    window.scrollTo(0, 0);
}

//Used in vue.js Tab Container event handling. ******
function vueActiveTabChanged(newTabIndex, currentTabIndex, tabPanels) {
    clearAllMsgs();

    //**** If clicked on same tab again, ignore. *****
    if (newTabIndex == currentTabIndex)
        return currentTabIndex;

    tabPanels[newTabIndex].enabled = true;

    try {
        tabPanels[newTabIndex].hideTabs.forEach((i, x) => {
            tabPanels[i].enabled = false;
        });
    } catch (e) { }

    return newTabIndex;
}

//used in 'Master_Ready.js' and 'menu.js' files.
const anchorClickShowProgressHandler = function () {
    let $elem = $(this);
    $elem.attr('data-show-progress', 'no');
    var href = $elem.prop("href");
    var target = $elem.prop("target");

    if (href != null) {
        if (href.substr(href.length - 1, 1) == "#") { href = "#"; }
    }

    if (href != null && href != undefined && href != "")
        href = href.replace(window.location.hostname, '');//remove host name from href for validation only as .asp, .aspx, .htm, .php can occur in domain/host name.

    if (!(target != null && target.match(/_blank/g))
        && href != null && href != undefined && href != "" && href != "#"
        && !(href.match(/#/gi))
        && (href.match(/.aspx/gi) || href.match(/.htm/gi) || href.match(/.html/gi) || href.match(/.asp/gi) || href.match(/.php/gi))) {
        $elem.attr('data-show-progress', 'show');
        $elem.on("click", function (event) {
            if (event.which == 1 && LocalPostBackLoader == false) {
                $('.page-loader-wrapper').show();
                return true;
            }
        });
    }
}


const optionMenuMouseHoverHandler = function () {

    $(this).find('.dropdown').addClass('open')
    setTimeout(function ($this) {
        // calculate the required sizes, spaces
        var $ul = $this.find(".dropdown-menu");
        var $button = $this.find(".dropdown-toggle");
        var ulOffset = $ul.offset();

        if (ulOffset == undefined) {
            $ul = $this.find(".option-menu");
            ulOffset = $ul.offset();
        }

        if (ulOffset) {
            // how much space would be left on the top if the dropdown opened that direction
            var spaceUp = Math.abs((ulOffset.top - $button.height() - $ul.height()) - $(window).scrollTop());
            // how much space is left at the bottom
            var spaceDown = $(window).scrollTop() + $(window).height() - (ulOffset.top + $ul.height());
            // switch to dropup only if there is no space at the bottom AND there is space at the top, or there isn't either but it would be still better fit

            if (spaceUp > spaceDown)
                $this.addClass("dropup");
        }
    }, 10, $(this));
};

const optionMenuMouseLeaveHandler = function () {
    $(this).find('.dropdown').removeClass('open');
    $(this).removeClass("dropup");
};


function updateSelectInterface() {
    setTimeout(function () {
        $('select:not(.ms, .HE_top_bar select)')
            //.attr("data-live-search", "true")
            //.attr("data-width", "100%")
            .addClass("virtual-select show-tick");

        //$('.vue-select').selectpicker('refresh');
        initVirtualSelectPlugin('.vue-select');

        //$('.vue-select.bootstrap-select  input[type="text"]').addClass('form-control');
    }, 50);
}

function getQueryParam(name, url) {
    url = window.location.href;
    name = name.replace(/[\[\]]/g, '\\$&');
    var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, ' '));
}

function authenticate(subId, rURL, aURL, appId, lH) {

    var currentUrl = [location.protocol, '//', location.host, location.pathname].join('');

    if (appId.indexOf('AUTH') == -1) {

        aURL += '?response_type=code';
        aURL += '&client_id=' + appId;
        aURL += '&redirect_uri=' + currentUrl;

        //if (aURL.indexOf('lync.com') != -1)
        //    aURL += '&resource=' + rURL;
        //else
        //    aURL += '&scope=' + rURL;

        aURL += '&resource=' + rURL;
        aURL += '&response_mode=query'
        aURL += '&state=' + subId;
        aURL += '&rand=' + Math.random().toString(36).substr(2, 10);
        aURL += '&login_hint=' + lH;
    }
    else {
        aURL = aURL.replace('oauth2/authorize', 'adminconsent?');
        aURL += 'client_id=' + appId.replace('AUTH', '');
        aURL += '&redirect_uri=' + currentUrl;
        aURL += '&prompt=admin_consent';
        aURL += '&rand=' + Math.random().toString(36).substr(2, 10);
        aURL += '&login_hint=' + lH;
        aURL += '&state=' + subId;
    }



    document.location.href = aURL;
}

String.prototype.replaceAll = function (search, replacement) {
    var target = this;
    return target.split(search).join(replacement);
};

var EmailValidationExpression = /^[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?\.)+[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?$/;

var currentCultureNumberDecimalSeparator = '.';
var currentCultureNumberGroupSeparator = ',';

function setCultureNumberSeparators(decimalSeparator, groupSeparator) {
    currentCultureNumberDecimalSeparator = decimalSeparator;
    currentCultureNumberGroupSeparator = groupSeparator;

}

function setEmailAddressesUI(Type, TypeTXT, TRTypeTXT, EmailTXT, EmailDDL, EmailNA, ExtTXT, ExtNA, DailPlan, DailPlanNA, TypeText) {
    var selectedType = $('#' + Type + ' option:selected').val();
    //alert(selectedType);

    $('#' + TRTypeTXT).attr("style", "display:none");
    $('#' + EmailTXT).val('');
    $('#' + EmailTXT).attr("style", "display:none");
    $('#' + EmailNA).attr("style", "display:''");
    $('#' + EmailNA).text('@');
    $('#' + EmailDDL).attr("style", "display:none");
    $('#' + EmailDDL).next('span').attr("style", "display:none");
    $('#' + ExtTXT).val('');
    $('#' + ExtTXT).attr("style", "display:none");
    $('#' + ExtNA).attr("style", "display:none");
    //$('#' + DailPlan).attr("style", "display:none");
    $('#' + DailPlanNA).attr("style", "display:none");
    $('#' + DailPlan).next('span').attr("style", "display:none");

    if (selectedType.toLowerCase() == 'smtp') {
        $('#' + TypeTXT).val('smtp');
        $('#' + EmailTXT).attr("style", "display:''");
        $('#' + EmailNA).attr("style", "display:''");
        $('#' + EmailNA).text('@');
        $('#' + EmailDDL).attr("style", "display:''");
        $('#' + EmailDDL).next('span').attr("style", "display:''");
        $('#' + ExtNA).attr("style", "display:''");
        $('#' + DailPlanNA).attr("style", "display:''");
    }
    else if (selectedType.toLowerCase() == 'eum') {
        $('#' + TypeTXT).val('eum');
        $('#' + EmailNA).attr("style", "display:''");
        $('#' + EmailNA).text('N/A');
        $('#' + ExtTXT).val('');
        $('#' + ExtTXT).attr("style", "display:''");
        //$('#' + DailPlan).attr("style", "display:none");
        $('#' + DailPlanNA).attr("style", "display:none");
        $('#' + DailPlan).next('span').attr("style", "display:''");
    }
    else if (selectedType.toLowerCase() == 'other') {
        //alert(TypeText);
        $('#' + TypeTXT).val(TypeText);
        $('#' + TRTypeTXT).attr("style", "display:''");
        $('#' + EmailTXT).attr("style", "display:''");
        $('#' + EmailNA).attr("style", "display:none");
        $('#' + EmailNA).text('@');
        $('#' + EmailDDL).attr("style", "display:none");
        $('#' + EmailDDL).next('span').attr("style", "display:none");
        $('#' + ExtNA).attr("style", "display:''");
        $('#' + DailPlanNA).attr("style", "display:''");
    }
    else if (selectedType.toLowerCase() == '-1') {
        //Display all in case of no option selected.
        $('#' + TypeTXT).val('');
        $('#' + EmailTXT).val('');
        $('#' + EmailTXT).attr("style", "display:''");
        $('#' + EmailNA).attr("style", "display:''");
        $('#' + EmailNA).text('@');
        $('#' + EmailDDL).attr("style", "display:none");
        $('#' + EmailDDL).next('span').attr("style", "display:''");
        $('#' + ExtTXT).val('');
        $('#' + ExtTXT).attr("style", "display:''");
        $('#' + ExtNA).attr("style", "display:none");
        //$('#' + DailPlan).attr("style", "display:none");
        $('#' + DailPlanNA).attr("style", "display:none");
        $('#' + DailPlan).next('span').attr("style", "display:''");
    }
}

var changeTXTOnSPLAUpdate = 1;

function setCookie(cName, value, exdays) {
    if (!exdays)
        exdays = 365;

    var exdate = new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value = escape(value) + "; expires=" + exdate.toUTCString();
    document.cookie = cName + "=" + c_value + ';path=/';
}

function getCookie(cName) {
    var i, x, y, ARRcookies = document.cookie.split(";");
    for (i = 0; i < ARRcookies.length; i++) {
        x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
        y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
        x = x.replace(/^\s+|\s+$/g, "");
        if (x == cName) {
            return unescape(y);
        }
    }
}

function getCookieFromKeyValue(keyToFind, cookieValue) {
    //MachPanel=AuditAccount=y2N6DqR+1p4d3869uurhoa5ht5MmQ8VYTcFhaKtIw/oRgeLC4hKhIxs513F37+alIDvotiguIWkJ1/3ge4iE+wU3VdvxINthk01SkGwO8dM=~~~&U=gHs8XDsJOf1i7gJwvs/Ccq+bhhVBIORxaiN6JPEdY6E=~~~&IsContactOfCustomer=0&CartId=1ca1cb27-f0fc-43ba-ab6f-c24bb44f4970&MPVersion=v 6.1.34&LocaleId=1&AfterDate=1/1/2024; body_color=indigo; JSEnabled=1
    var i, x, y, ARRcookies = cookieValue.split("&");
    for (i = 0; i < ARRcookies.length; i++) {
        x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
        y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
        x = x.replace(/^\s+|\s+$/g, "");
        //console.log(x, y);
        if (x.toLowerCase() == keyToFind.toLowerCase()) {
            return unescape(y);
        }
    }
}

function setProviderDomainASDefaultUI(CB1, CB2) {
    var CB_ProviderDomainASDefault = document.getElementById(CB1);
    var CB_CreateAliasOnProvider = document.getElementById(CB2);

    if (CB_ProviderDomainASDefault.checked == true) {
        CB_CreateAliasOnProvider.checked = false;
        CB_CreateAliasOnProvider.disabled = true;
    }
    else
        CB_CreateAliasOnProvider.disabled = false;
}

function setFileManagerUI(TBHide, TBShow, TRName, RFVName, TRData, TRCopy, TRUP, RFVUP, OPCode, DDLOP, LName, LSTR, LOP, OPSTR, HF) {
    var HideTable = document.getElementById(TBHide);
    var ShowTable = document.getElementById(TBShow);
    var NameTR = document.getElementById(TRName);
    var RFVN = document.getElementById(RFVName);
    var DataTR = document.getElementById(TRData);
    var TRCopyMove = document.getElementById(TRCopy);
    var TRUpload = document.getElementById(TRUP);
    var RFVUpLoad = document.getElementById(RFVUP);
    var DDLOPerations = document.getElementById(DDLOP);
    var Ltl_Name = document.getElementById(LName);
    var Ltrl_Operation = document.getElementById(LOP);
    var HF_Operations = document.getElementById(HF);

    Ltl_Name.innerHTML = LSTR;
    Ltrl_Operation.innerHTML = OPSTR;
    HF_Operations.value = OPCode;
    HideTable.style.display = 'none';
    ShowTable.style.display = 'none';
    NameTR.style.display = 'none';
    DataTR.style.display = 'none';
    TRCopyMove.style.display = 'none';
    TRUpload.style.display = 'none';
    ValidatorEnable(RFVN, false);
    ValidatorEnable(RFVUpLoad, false);

    if ((OPCode == '1') || (OPCode == '6')) { //Add Folder or Rename
        ShowTable.style.display = '';
        NameTR.style.display = '';
        setTimeout(function () { DDLOPerations.selectedIndex = 0; $(DDLOPerations).trigger('change'); }, 500);


        if (OPCode == '6')
            setTimeout(function () { DDLOPerations.selectedIndex = 5; $(DDLOPerations).trigger('change'); }, 500);

        ValidatorEnable(RFVN, true);
    }
    else if (OPCode == '2') { //Upload a file
        ShowTable.style.display = '';
        TRUpload.style.display = '';
        setTimeout(function () { DDLOPerations.selectedIndex = 1; $(DDLOPerations).trigger('change'); }, 500);

        ValidatorEnable(RFVUpLoad, true);
    }
    else if (OPCode == '3') { //Add a file
        ShowTable.style.display = '';
        NameTR.style.display = '';
        DataTR.style.display = '';
        setTimeout(function () { DDLOPerations.selectedIndex = 2; $(DDLOPerations).trigger('change'); }, 500);

        ValidatorEnable(RFVN, true);
    }
    else if ((OPCode == '4') || (OPCode == '5')) { //Copy or Move
        ShowTable.style.display = '';
        TRCopyMove.style.display = '';
        setTimeout(function () { DDLOPerations.selectedIndex = 3; $(DDLOPerations).trigger('change'); }, 500);

        if (OPCode == '5')
            setTimeout(function () { DDLOPerations.selectedIndex = 4; $(DDLOPerations).trigger('change'); }, 500);

    }
}

function _showPassword(TB, TB2, CB) {
    var txtPassword = $('#' + TB).first();
    var txtPassword2 = $('#' + TB2).first();
    var CBPassword = $('#' + CB).first();

    if (CBPassword.is(":checked")) {

        $(txtPassword).prop('type', 'text');
        $(txtPassword2).prop('type', 'text');

        ////txtPassword.after('<input onchange = "PasswordChanged(this);" id = "txt_' + txtPassword.attr("id") + '" type = "text" value = "' + txtPassword.val() + '" />');
        ////txtPassword2.after('<input onchange = "PasswordChanged(this);" id = "txt_' + txtPassword2.attr("id") + '" type = "text" value = "' + txtPassword2.val() + '" />');

        //$(txtPassword).clone(false).prop('name', 'txt_' + txtPassword.attr("name")).prop('class', 'form-control form-password').prop('id', 'txt_' + txtPassword.attr("id")).prop('type', 'text').on('change', function () { PasswordChanged(this); })
        //                                                    .insertAfter('#' + TB);
        //$(txtPassword2).clone(false).prop('name', 'txt_' + txtPassword2.attr("name")).prop('class', 'form-control form-password').prop('id', 'txt_' + txtPassword2.attr("id")).prop('type', 'text').on('change', function () { PasswordChanged(this); })
        //                                                    .insertAfter('#' + TB2);
        //txtPassword.hide();
        //txtPassword2.hide();
    }
    else {

        $(txtPassword).prop('type', 'password');
        $(txtPassword2).prop('type', 'password');

        //txtPassword.val(txtPassword.next().val());
        //txtPassword.next().remove();
        //txtPassword.show();
        //txtPassword2.val(txtPassword2.next().val());
        //txtPassword2.next().remove();
        //txtPassword2.show();
    }

}

function PasswordChanged(txt) {

    $(txt).prev().val($(txt).val());

}

var _symbolClasses = ["ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz", "0123456789", "!@#$&*?_~"];

function GenerateNumericTransactionId(TB1) {

    var TXT = document.getElementById(TB1);

    var symbolClasses = ['number', 'number', 'number', 'number', 'number', 'number', 'number'];
    symbolClasses.push('number', 'number', 'number', 'number', 'number');

    symbolClasses.sort(function (a, b) {
        return Math.floor(b.length * Math.random()) - Math.floor(a.length * Math.random());
    });

    var password = "";

    for (var i = 0; i < symbolClasses.length; i++) {
        var dataChar = this._generateSymbol(symbolClasses[i]);
        if (("!@#$&*?_~".indexOf(dataChar) > -1) && (password == '')) {
            //Ignore special character in start of Password string,
            //to avoid this assigning 'A' this will make passowrd string length consistent
            password += 'A';
        }
        else
            password += dataChar;
    }

    TXT.value = password;

    //alert(password);
    return true;
}

function GeneratePasswords(TB1, TB2, PLN) {
    var txtPassword = $('#' + TB1).first();
    var txtPassword2 = $('#' + TB2).first();
    var txtPassword3 = $('#txt_' + TB1).first();
    var txtPassword4 = $('#txt_' + TB2).first();

    var symbolClasses = ['upper', 'lower', 'lower', 'number', 'number', 'number', 'upper', 'lower'];

    for (var Len = 8; Len <= PLN; Len++) {
        symbolClasses.push('upper', 'lower', 'lower', 'number', 'number', 'number', 'upper', 'lower');
        Len += 7;//Added 7 more items in Array.        
    }

    symbolClasses.sort(function (a, b) {
        return Math.floor(b.length * Math.random()) - Math.floor(a.length * Math.random());
    });

    var password = "";
    var LengthP = symbolClasses.length;

    for (var i = 0; i < symbolClasses.length; i++) {
        var dataChar = this._generateSymbol(symbolClasses[i]);
        password += dataChar;
    }

    password = password.substr(0, PLN - 4);

    //************************** Add 4 necessary charracters, Upper+Lower+Number+Password+Special ************************** 
    password = this._generateSymbol('upper') + this._generateSymbol('lower') + this._generateSymbol('number') + password + this._generateSymbol('special');

    txtPassword.val(password);
    if (txtPassword2 != null)
        txtPassword2.val(password);
    if (txtPassword3 != null)
        txtPassword3.val(password);
    if (txtPassword4 != null)
        txtPassword4.val(password);

    //alert(password);
    return true;
}

function GeneratePasswordSIP(TB1, TB2, PLN) {
    var txtPassword = $('#' + TB1).first();
    var txtPassword2 = $('#' + TB2).first();
    var txtPassword3 = $('#txt_' + TB1).first();
    var txtPassword4 = $('#txt_' + TB2).first();

    var symbolClasses = ['upper', 'lower', 'lower', 'number', 'number', 'number', 'upper', 'lower'];

    for (var Len = 12; Len <= PLN; Len++) {
        symbolClasses.push('upper', 'lower', 'lower', 'number', 'number', 'number', 'upper', 'lower');
        Len += 11;//Added 11 more items in Array.        
    }

    symbolClasses.sort(function (a, b) {
        return Math.floor(b.length * Math.random()) - Math.floor(a.length * Math.random());
    });

    var password = "";
    var LengthP = symbolClasses.length;

    for (var i = 0; i < symbolClasses.length; i++) {
        var dataChar = this._generateSymbol(symbolClasses[i]);
        password += dataChar;
    }

    password = password.substr(0, PLN - 4);

    //************************** Add 4 necessary charracters, Upper+Lower+Number+Password+upper ************************** 
    password = this._generateSymbol('upper') + this._generateSymbol('lower') + this._generateSymbol('number') + password + this._generateSymbol('upper');

    txtPassword.val(password);
    if (txtPassword2 != null)
        txtPassword2.val(password);
    if (txtPassword3 != null)
        txtPassword3.val(password);
    if (txtPassword4 != null)
        txtPassword4.val(password);

    //alert(passwsync
    return true;
}

function ADUserPasswordOptions(CBMustChange, CBCantChange, CBNeverExpires) {
    var MustChange = document.getElementById(CBMustChange);
    var CantChange = document.getElementById(CBCantChange);
    var NeverExpires = document.getElementById(CBNeverExpires);

    if (MustChange.checked == true) {
        if (NeverExpires.checked == true) {
            alert('You specified that the password should never expire. The user will not be required to change the password at next logon.');
            MustChange.checked = false;
        }
        else if (CantChange.checked == true) {
            alert('You cannot check both User must change password at next logon and User cannot change password.');
            CantChange.checked = false;
        }
    }
}

function _generateSymbol(symbolClass) {
    var index = 0;
    if (symbolClass == 'upper') {
        index = Math.floor(this._symbolClasses[0].length * Math.random());
        return this._symbolClasses[0][index];
    }
    else if (symbolClass == 'lower') {
        index = Math.floor(this._symbolClasses[1].length * Math.random());
        return this._symbolClasses[1][index];
    }
    else if (symbolClass == 'number') {
        index = Math.floor(this._symbolClasses[2].length * Math.random());
        return this._symbolClasses[2][index];
    }
    else if (symbolClass == 'special') {
        index = Math.floor(this._symbolClasses[3].length * Math.random());
        return this._symbolClasses[3][index];
    }

}

function RemoveAllSpaces(TB) {
    var TXT = document.getElementById(TB);

    if (TXT != null) {
        TXT.value = TXT.value.replace(/ /g, '');
    }
}
function RemoveIllegalCharacters(TB) {
    var TXT = document.getElementById(TB);

    if (TXT != null) {
        TXT.value = TXT.value.replace(/[~|+%{}\[\]<>\/#?*^&$@]/g, '');
        TXT.value = TXT.value.replace(/ /g, "");;
        //alert('I am in RemoveIllegalCharacters');
    }
}

function selectALLBuiltInModules(CBAll, CBSH, CBEX, CBDNS, CBSP, CBD, CBCRM, CBSSL, CBOCS, CBB, CBW, CBMIG, CBVPS, CBNTW, CBMISC, CBHD, CBDH, CBOH, CBDC, CBDS, CBCBR, CBSBR, CBWHMCS) {
    var ChBx_All = document.getElementById(CBAll);
    var ChBx_SH = document.getElementById(CBSH);
    var ChBx_EX = document.getElementById(CBEX);
    var ChBx_DNS = document.getElementById(CBDNS);
    var ChBx_SP = document.getElementById(CBSP);
    var ChBx_D = document.getElementById(CBD);
    var ChBx_CRM = document.getElementById(CBCRM);
    var ChBx_SSL = document.getElementById(CBSSL);
    var ChBx_OCS = document.getElementById(CBOCS);
    var ChBx_B = document.getElementById(CBB);
    var ChBx_W = document.getElementById(CBW);
    var ChBx_MIG = document.getElementById(CBMIG);
    var ChBx_VPS = document.getElementById(CBVPS);
    var ChBx_NTW = document.getElementById(CBNTW);
    var ChBx_MISC = document.getElementById(CBMISC);
    var ChBx_HD = document.getElementById(CBHD);
    var ChBx_DH = document.getElementById(CBDH);
    var ChBx_OH = document.getElementById(CBOH);
    var ChBx_DC = document.getElementById(CBDC);
    var ChBx_DS = document.getElementById(CBDS);
    var ChBx_CBR = document.getElementById(CBCBR);
    var ChBx_SBR = document.getElementById(CBSBR);
    var Chbx_WHMCS = document.getElementById(CBWHMCS);
    ChBx_SH.checked = false;
    ChBx_EX.checked = false;
    ChBx_DNS.checked = false;
    ChBx_SP.checked = false;
    ChBx_D.checked = false;
    ChBx_CRM.checked = false;
    ChBx_SSL.checked = false;
    ChBx_OCS.checked = false;
    ChBx_B.checked = false;
    ChBx_W.checked = false;
    ChBx_MIG.checked = false;
    ChBx_VPS.checked = false;
    ChBx_NTW.checked = false;
    ChBx_MISC.checked = false;
    ChBx_HD.checked = false;
    ChBx_DH.checked = false;
    ChBx_OH.checked = false;
    ChBx_DC.checked = false;
    ChBx_DS.checked = false;
    ChBx_CBR.checked = false;
    ChBx_SBR.checked = false;
    Chbx_WHMCS.checked = false;

    if (ChBx_All.checked == true) {
        ChBx_SH.checked = true;
        ChBx_EX.checked = true;
        ChBx_DNS.checked = true;
        ChBx_SP.checked = true;
        ChBx_D.checked = true;
        ChBx_CRM.checked = true;
        ChBx_SSL.checked = true;
        ChBx_OCS.checked = true;
        ChBx_B.checked = true && !ChBx_B.disabled;
        ChBx_W.checked = true;
        ChBx_MIG.checked = true;
        ChBx_VPS.checked = true;
        ChBx_NTW.checked = true;
        ChBx_MISC.checked = true;
        ChBx_HD.checked = true;
        ChBx_DH.checked = true;
        ChBx_OH.checked = true;
        ChBx_DC.checked = true;
        ChBx_DS.checked = true;
        ChBx_CBR.checked = true;
        ChBx_SBR.checked = true;
        Chbx_WHMCS.checked = true && ChBx_B.disabled;
    }
}
function customBuiltInModules(CBAll, CBC) {
    var ChBx_All = document.getElementById(CBAll);
    var ChBx_Child = document.getElementById(CBC);

    if (ChBx_Child.checked == false)
        ChBx_All.checked = false;
}

function ValidateQuantity(TxBx) {
    var Txt = document.getElementById(TxBx);

    Txt.value = Math.round(Txt.value);
    //alert(Txt.value);
    //alert(parseInt(Txt.value));
    if (parseInt(Txt.value)) {
        // data is an integer
        //alert("IN INT:" + Txt.value);
        Txt.value = Txt.value.replace(/^0+/, '');
    }
    else {
        Txt.value = '1';
    }
    if (Txt.value == '0')
        Txt.value = '1';
}
function cTrig(clickedid) {
    if (document.getElementById(clickedid).checked == true) {
        return false;
    } else {
        var box = confirm("Are you sure you want to disable SPAM filter?");
        if (box == true)
            return true;
        else
            document.getElementById(clickedid).checked = true;

    }
}
function ChBx_SEPAEnabled_CheckedChanged(CB, TR, RFV1, RFV2, RFV3, RFV4) {
    var CB_Id = document.getElementById(CB);
    var TR_Enable = document.getElementById(TR);
    var RFVD1 = document.getElementById(RFV1);
    var RFVD2 = document.getElementById(RFV2);
    var RFVD3 = document.getElementById(RFV3);
    var RFVD4 = document.getElementById(RFV4);

    TR_Enable.style.display = 'none';
    ValidatorEnable(RFVD1, false);
    ValidatorEnable(RFVD2, false);
    ValidatorEnable(RFVD3, false);
    ValidatorEnable(RFVD4, false);

    if (CB_Id.checked == true) {
        TR_Enable.style.display = '';
        ValidatorEnable(RFVD1, true);
        ValidatorEnable(RFVD2, true);
        ValidatorEnable(RFVD3, true);
        ValidatorEnable(RFVD4, true);
    }
    //alert(RFVD1 + ":" + RFVD2 + ":" + RFVD3 + ":" + RFVD4);
}
function ResellerSettings_CheckedChanged(CB, TR, RFV1, RFV2, RFV3, RFV4, TT) {
    var CB_Id = document.getElementById(CB);
    var TR_Id = document.getElementById(TR);
    var RFVD1 = document.getElementById(RFV1);
    var RFVD2 = document.getElementById(RFV2);
    var RFVD3 = document.getElementById(RFV3);
    var RFVD4 = document.getElementById(RFV3);  // url validator

    ValidatorEnable(RFVD1, false);
    ValidatorEnable(RFVD2, false);
    ValidatorEnable(RFVD3, false);
    ValidatorEnable(RFVD4, false);
    TR_Id.style.display = 'none';

    if (CB_Id.checked == true) {
        TR_Id.style.display = '';
        ValidatorEnable(RFVD1, true);
        if (TT == "0")    // URL
        {
            ValidatorEnable(RFVD2, true);
            ValidatorEnable(RFVD4, true);
        }
        else
            ValidatorEnable(RFVD3, true);
    }
}
function showHideControlOnDDLChange(ddl, elementId, ValueToAct, IsShowRequest) {
    var DDL_Source = document.getElementById(ddl);
    var Target_element = document.getElementById(elementId);

    if (DDL_Source.options[DDL_Source.selectedIndex].value == ValueToAct) {
        if (IsShowRequest)
            Target_element.style.display = '';
        else
            Target_element.style.display = 'none';
    }
    else {
        //**** Toogle the control if value is changed. */
        if (IsShowRequest)
            Target_element.style.display = 'none';
        else
            Target_element.style.display = '';
    }
}
function RecordDescription(ddl, lbl, lblName) {
    var DDL_RecprdType = document.getElementById(ddl);
    var Lbl_Content = document.getElementById(lbl);
    var Lbl_Name = document.getElementById(lblName);
    //alert("IN");
    Lbl_Content.innerHTML = '';
    Lbl_Name.innerHTML = '';
    if (DDL_RecprdType.options[DDL_RecprdType.selectedIndex].value == "-1") {
        Lbl_Content.innerHTML = '';
        Lbl_Name.innerHTML = '';
    }
    else if (DDL_RecprdType.options[DDL_RecprdType.selectedIndex].value == "A") {
        Lbl_Content.innerHTML = "format: (IPAddress of IPv4) [0.0.0.0]";
        Lbl_Name.innerHTML = "format: [Name] or [@]";
    }
    else if (DDL_RecprdType.options[DDL_RecprdType.selectedIndex].value == "AAAA") {
        Lbl_Content.innerHTML = "format: (IPAddress of IPv6) [FE80:0000:0000:0000:0202:B3FF:FE1E:8329]";
        Lbl_Name.innerHTML = "format: [Name] or [@]";
    }
    else if (DDL_RecprdType.options[DDL_RecprdType.selectedIndex].value == "CNAME") {
        Lbl_Content.innerHTML = "format: [domain.com] or [@]";
        Lbl_Name.innerHTML = "format: [Name]";
    }
    else if (DDL_RecprdType.options[DDL_RecprdType.selectedIndex].value == "MX") {
        Lbl_Content.innerHTML = "format: [priority] [target]";
        Lbl_Name.innerHTML = "format: [Name] or [@]";
    }
    else if (DDL_RecprdType.options[DDL_RecprdType.selectedIndex].value == "NS") {
        Lbl_Content.innerHTML = "format: [hostName.ns]";
        Lbl_Name.innerHTML = "format: [Name]";
    }
    else if (DDL_RecprdType.options[DDL_RecprdType.selectedIndex].value == "SRV") {
        Lbl_Content.innerHTML = "format: [priority] [weight] [port] [target.com.]";
        Lbl_Name.innerHTML = "format: [_service]";
    }
    else if (DDL_RecprdType.options[DDL_RecprdType.selectedIndex].value == "TXT") {
        Lbl_Content.innerHTML = "format: [Text description]";
        Lbl_Name.innerHTML = "format: [Name]";
    }
    //alert("UHU");
    //alert(Lbl_Content.innerHTML + "|" + Lbl_Name.innerHTML);
}
function ShowHideIISBindingOption(ddlId, trId) {
    var ddlProtocol = document.getElementById(ddlId);
    var trAddIISBinding = document.getElementById(trId);
    if (ddlProtocol && trAddIISBinding) {
        if (ddlProtocol.options[0].selected) {
            trAddIISBinding.style.display = '';
        }
        else
            trAddIISBinding.style.display = 'none';
    }
    return false;
}
function ShowServicesOffered(DDL, TB, BTN) {
    var DDL_ResellerType = document.getElementById(DDL);
    var TB_Services = document.getElementById(TB);
    var Btn_AddnSubscribe = document.getElementById(BTN);

    TB_Services.style.display = '';
    Btn_AddnSubscribe.style.display = 'none';
    if (DDL_ResellerType.options[DDL_ResellerType.selectedIndex].value != "0") {
        TB_Services.style.display = 'none';
        Btn_AddnSubscribe.style.display = '';
    }
}
function ExpandDetails(Div, Data, DataFull, Btn, OP) {
    //alert("IN start");
    var TRow = document.getElementById(Btn);
    var DivDetails = document.getElementById(Div);
    var HData = document.getElementById(Data);
    var FData = document.getElementById(DataFull);
    var HFOP = document.getElementById(OP);

    //alert("IN" + HFOP.value);
    //DivDetails.innerHTML = FData.value;
    if (HFOP.value == 'c') {
        HFOP.value = 'e';
        DivDetails.innerHTML = FData.innerHTML;
        TRow.innerHTML = "<font color='blue' style='cursor : pointer'>&laquo;&laquo;less</font>";
    }
    else {
        HFOP.value = 'c';
        DivDetails.innerHTML = HData.innerHTML;
        TRow.innerHTML = "<font color='blue' style='cursor : pointer'>&raquo;&raquo;more</font>";
    }
}
function Responses(TD, HF, TR, ImgId, ImgPath) {
    var TCol = document.getElementById(TD);
    var HFR = document.getElementById(HF);
    var TRow = document.getElementById(TR);
    var ImageId = document.getElementById(ImgId);

    TRow.style.display = 'none';
    if (HFR.value == 'c') {
        HFR.value = 'e';
        TRow.style.display = '';
        ImageId.src = ImgPath.replace("next", "down");
    }
    else {
        HFR.value = 'c';
        TRow.style.display = 'none';
        ImageId.src = ImgPath;
    }
}
function CB_DaysChecked(CB, OP1, CL1, OP2, CL2) {
    var CBDay = document.getElementById(CB);
    var TxtOpen1 = document.getElementById(OP1);
    var TxtClose1 = document.getElementById(CL1);
    var TxtOpen2 = document.getElementById(OP2);
    var TxtClose2 = document.getElementById(CL2);
    //alert("IN");
    TxtOpen1.disabled = false;
    $(TxtOpen1).removeClass('disabled');
    TxtClose1.disabled = false;
    $(TxtClose1).removeClass('disabled');
    TxtOpen2.disabled = false;
    $(TxtOpen2).removeClass('disabled');
    TxtClose2.disabled = false;
    $(TxtClose2).removeClass('disabled');
    TxtOpen1.value = "00:00";
    TxtClose1.value = "23:59";
    TxtOpen2.value = '';
    TxtClose2.value = '';

    if (CBDay.checked == false) {
        TxtOpen1.disabled = true;
        $(TxtOpen1).addClass('disabled');
        TxtClose1.disabled = true;
        $(TxtClose1).addClass('disabled');
        TxtOpen2.disabled = true;
        $(TxtOpen2).addClass('disabled');
        TxtClose2.disabled = true;
        $(TxtClose2).addClass('disabled');
    }
}
function CheckAlertTime(TB, flag) {
    var Txt = document.getElementById(TB);

    //alert(flag + ":" + Txt.value);
    if (flag == '1') {
        if (Txt.value == '')
            Txt.value = '20';
        else if ((Txt.value <= 9) || (Txt.value >= 601)) {
            Txt.value = '20';
        }
        /*alert("You must enter a numeric value between 10 to 600.");
        Txt.focus();
        return false;*/

    }
    else if (flag == '2') {
        if (Txt.value == '')
            Txt.value = '10';
        else if (Txt.value <= 9)
            Txt.value = '10';
        else if (Txt.value > 65535)
            Txt.value = '65535';
        /*alert("You must enter a numeric value between 10 to 65535.");
        Txt.focus();
        return false;*/
    }
    else if (flag == '3') {
        if (Txt.value == '')
            Txt.value = '0';
        else if (Txt.value <= 0 || Txt.value >= 1001)
            Txt.value = '0';
        /*alert("You must enter a numeric value between 0 to 1000.");
        Txt.focus();
        return false;*/
    }
    //alert(flag + ":" + Txt.value);
}
function CB_CheckedShowtable(CB_Id, TR) {
    var TR_Enable = document.getElementById(TR);
    var CB = document.getElementById(CB_Id);
    TR_Enable.style.display = 'none';

    if (CB.checked == true) {
        TR_Enable.style.display = '';
    }

    var childTable = $(TR_Enable).find('table').first();
    if (childTable != null) {
        //$('input:checkbox', childTable).prop('checked', CB.checked);
        $('input:checkbox', childTable).each(function () {
            if ($(this).is(':disabled'))
                $(this).prop('checked', false);
            else
                $(this).prop('checked', CB.checked);

        });
        $('tr', childTable).show();
    }
}


function CheckUnCheckChildItemsWithId(CB_Id, ChildContainer_Id) {
    $('input:checkbox', $('#' + ChildContainer_Id)).prop('checked', $('#' + CB_Id).prop('checked'));
}

function CheckUnCheckChildItemsWithId_ShowHideSection(CB_Id, ChildContainer_Id) {
    var changeEventTriggered = false;
    $('input:checkbox', $('#' + ChildContainer_Id)).each(function () {
        $(this).prop('checked', $('#' + CB_Id).prop('checked'));
        if ($(this).attr('section') || $(this).parent().attr('section') && !changeEventTriggered) {
            changeEventTriggered = true;
            var currentElement = $(this);
            setTimeout(function () { currentElement.trigger('change'); }, 100);
        }
    });
}

function CheckUnCheckChildItemsWithClass(CBParent_Id, ChildClassName) {

    var ParentChecked = $('#' + CBParent_Id).prop('checked');

    $('input:checkbox', $('.' + ChildClassName)).each(function () {

        $(this).prop('checked', ParentChecked);

        CheckUnCheckChildItemsWithClass($(this).prop('id'), 'child-' + $(this).parent().data('feature-id'));

    });
}

function CheckParentWithClass(CB_Id, Class) {

    var parent = $('input:checkbox', $('.' + Class));

    if ($('#' + CB_Id).prop('checked') == true)
        parent.prop('checked', $('#' + CB_Id).prop('checked'));

    var dataparentfeatureid = parent.parent().data('parentfeature-id');

    if (dataparentfeatureid != 0)
        CheckParentWithClass(parent.prop('id'), 'parent-' + dataparentfeatureid);

}

function CheckUnCheckParentItemWithId(ParentItemId, ChildContainer_Id) {

    $('#' + ParentItemId).prop('checked', false);
    if ($('#' + ParentItemId).attr('section') || $('#' + ParentItemId).parent().attr('section') && !changeEventTriggered) {
        changeEventTriggered = true;
        var currentElement = $(this);
        setTimeout(function () { currentElement.trigger('change'); }, 100);
    }

    //$('input:checkbox', $('#' + ChildContainer_Id)).each(function () {
    //    $('#' + ParentItemId).prop('checked', $('#' + ParentItemId).prop('checked') || $(this).prop('checked'));

    //});
}


function CheckUnCheckParentItemWithIdLicense(ParentItemId, ChildContainer_Id) {

    var table = document.getElementById(ChildContainer_Id);

    var checkBoxes = table.getElementsByTagName("INPUT");

    var checkParent = false;

    //Loop through the CheckBoxes.
    for (var i = 0; i < checkBoxes.length; i++) {
        if (checkBoxes[i].checked && !checkBoxes[i].disabled) {
            checkParent = true;
            break;
        }
    }

    if ((checkParent && $('#' + ParentItemId).prop("checked") == false) || (!checkParent && $('#' + ParentItemId).prop("checked"))) {
        setTimeout(function () { $('#' + ParentItemId).prop('checked', checkParent); $('#' + ParentItemId).trigger('change'); }, 100);
    }

}

function UnCheckParentItemIfAnyChildUnChecked(ParentItemId, ChildContainer_Id) {
    $('#' + ParentItemId).prop('checked', false);
    $('input:checkbox', $('#' + ChildContainer_Id)).each(function () {
        $('#' + ParentItemId).prop(!'checked', !$('#' + ParentItemId).prop('checked') || !$(this).prop('checked'));
    });
}

function CheckUnCheckParentItemWithId_ShowHideSection(ParentItemId, ChildContainer_Id, triggerBtnId, section) {

    CheckUnCheckParentItemWithIdLicense(ParentItemId, ChildContainer_Id);

    var postbackTriggered = false;
    $('input:checkbox', $('#' + ChildContainer_Id)).each(function () {
        $('#' + ParentItemId).prop('checked', $('#' + ParentItemId).prop('checked') || $(this).prop('checked'));

        var currentSection;
        if ($(this).attr('section'))
            currentSection = $(this).attr('section');
        else if ($(this).parent().attr('section'))
            currentSection = $(this).parent().attr('section')

        if (currentSection && triggerBtnId && triggerBtnId != null && triggerBtnId != undefined && triggerBtnId != '' && section == currentSection && !postbackTriggered) {
            postbackTriggered = true;
            setTimeout(function () { $('#' + triggerBtnId)[0].click(); }, 100);
        }
    });
}

function CB_CheckedShowtableDisableRFV(CB_Id, TR) {
    var TR_Enable = document.getElementById(TR);
    var CB = document.getElementById(CB_Id);
    //var RFVD = document.getElementById(RFV);

    TR_Enable.style.display = 'none';
    //RFVD.disabled = true;
    //if (RFVD != null)
    //    ValidatorEnable(RFVD, false);

    if (CB.checked == true) {
        TR_Enable.style.display = '';
        //RFVD.disabled = false;
        //  if (RFVD != null)
        //    ValidatorEnable(RFVD, true);
        //alert("INIFTER");
    }
    //alert("out");
}

function CB_Checked_ShowTableEnableValidator(CB_Id, TR, RFV) {
    var TR_Enable = document.getElementById(TR);
    var CB = document.getElementById(CB_Id);
    var RFVD = document.getElementById(RFV);
    var REVD = document.getElementById(RFV.replace('RFV', 'REV'));

    TR_Enable.style.display = 'none';
    if (RFVD)
        ValidatorEnable(RFVD, false);
    if (REVD)
        ValidatorEnable(REVD, true);

    if (CB.checked == true) {
        TR_Enable.style.display = '';
        if (RFVD)
            ValidatorEnable(RFVD, true);
        if (REVD)
            ValidatorEnable(REVD, false);
    }
}

function CB_Checked_HideTableDisableValidator(CB_Id, TR, RFV) {
    var TR_Enable = document.getElementById(TR);
    var CB = document.getElementById(CB_Id);
    var RFVD = document.getElementById(RFV);

    TR_Enable.style.display = '';
    if (RFVD)
        ValidatorEnable(RFVD, true);

    if (CB.checked == true) {
        TR_Enable.style.display = 'none';
        if (RFVD)
            ValidatorEnable(RFVD, false);
    }
}

/*function redirectSubscription(BaseURL, DDL) {
    //alert("IN");
    var DDL_SPLAType = document.getElementById(DDL);
    var selIndex = DDL_SPLAType.options[DDL_SPLAType.selectedIndex].value;
    var UserID = '0';
    var PackageTypeID = '0';
    var OrgID = '0';
    if (selIndex != '-1') {
        if (selIndex.search("|") > -1) {
            UserID = selIndex.split("|")[0];
            PackageTypeID = selIndex.split("|")[1];
            OrgID = selIndex.split("|")[2];
        }
        //alert(UserID + "," + PackageTypeID + "," + OrgID);
        if (PackageTypeID == "1")
            window.location.replace(BaseURL + "/Client/SHDetail.aspx?domainid=" + UserID);
        else if (PackageTypeID == "8")
            window.location.replace(BaseURL + "/Client/SSL.aspx?ACID=" + UserID);
        else if (PackageTypeID == "10")
            window.location.replace(BaseURL + "/Client/ManageDomain.aspx?domainid=" + OrgID);
        else if (ackageTypeID == "14")
            window.location.replace(BaseURL + "/Client/CRMAccountDetail.aspx?OID=" + OrgID & "&CS=" + UserID);
        else if (PackageTypeID == "16")
            window.location.replace(BaseURL + "/Client/ExAccountDetail.aspx?oID=" + OrgID & "&CS=" + UserID);
        else if (PackageTypeID == "17")
            window.location.replace(BaseURL + "/Client/SPAccountDetail.aspx?OID=" + OrgID & "&CS=" + UserID);
        else if (PackageTypeID == "18")
            window.location.replace(BaseURL + "/Client/OCSAccountDetail.aspx?oID=" + OrgID & "&CS=" + UserID);
        else if (PackageTypeID == "19")
            window.location.replace(BaseURL + "/Client/VPSAccountDetail.aspx?OID=" + OrgID & "&CS=" + UserID);
    }

}
*/
function CB_CheckedHidetable(CB_Id, TR) {
    var TR_Disable = document.getElementById(TR);
    var CB = document.getElementById(CB_Id);
    TR_Disable.style.display = '';

    if (CB.checked == true) {
        TR_Disable.style.display = 'none';
    }
}

function CB_CheckedShowtable(CB_Id, TR) {
    var TR_Disable = document.getElementById(TR);
    var CB = document.getElementById(CB_Id);
    TR_Disable.style.display = 'none';

    if (CB.checked == true) {
        TR_Disable.style.display = '';
    }
}

function CB_CheckedShowHide(CB_Id, TRShow, TRHide) {
    var TR_Enable = document.getElementById(TRShow);
    var TR_Disable = document.getElementById(TRHide);
    var CB = document.getElementById(CB_Id);
    TR_Enable.style.display = 'none';
    TR_Disable.style.display = '';

    if (CB.checked == true) {
        TR_Enable.style.display = '';
        TR_Disable.style.display = 'none';
    }
}

function UpdateLabelText(Ctrl, uText) {
    var Lbl = document.getElementById(Ctrl);
    $(Lbl).text(uText);
}
function CB_CheckedIIS(CB_Id, TxBx_Id, TxBx_Name) {
    var TxBx = document.getElementById(TxBx_Id);
    var TxBx2 = document.getElementById(TxBx_Name);
    var CB = document.getElementById(CB_Id);

    if (CB.checked == false) {
        TxBx.disabled = true;
        $(TxBx).addClass('disabled');
        TxBx2.disabled = true;
        $(TxBx2).addClass('disabled');
        TxBx.value = '0';
        TxBx2.value = '';
    }
    else {
        TxBx.disabled = false;
        $(TxBx).removeClass('disabled');
        TxBx2.disabled = false;
        TxBx.value = '';
        TxBx2.value = '';
    }
}
function DomainAlias(TXTD, DN, TR) {
    var TxBx_DomainName = document.getElementById(TXTD);
    var TR_EnableSynch = document.getElementById(TR);

    if (TxBx_DomainName.value == DN) {
        TR_EnableSynch.style.display = 'none';
    }
    else {
        TR_EnableSynch.style.display = '';
    }
}

function DynamicDlist(RBAR, RBST, CBUExMB, CBUEMB, CBRMB, CBC, CBMG) {

    var RB_AllRecipients = document.getElementById(RBAR);
    var RB_SpecificTypes = document.getElementById(RBST);
    var CB_UsersExchangeMBs = document.getElementById(CBUExMB);
    var CB_UsersExternalMBs = document.getElementById(CBUEMB);
    var CB_ResourceMBs = document.getElementById(CBRMB);
    var CB_Contacts = document.getElementById(CBC);
    var CB_MailGroups = document.getElementById(CBMG);

    CB_UsersExchangeMBs.disabled = false;
    CB_UsersExternalMBs.disabled = false;
    CB_ResourceMBs.disabled = false;
    CB_Contacts.disabled = false;
    CB_MailGroups.disabled = false;
    if (RB_AllRecipients.checked == true) {
        CB_UsersExchangeMBs.checked = false;
        CB_UsersExternalMBs.checked = false;
        CB_ResourceMBs.checked = false;
        CB_Contacts.checked = false;
        CB_MailGroups.checked = false;
        CB_UsersExchangeMBs.disabled = true;
        CB_UsersExternalMBs.disabled = true;
        CB_ResourceMBs.disabled = true;
        CB_Contacts.disabled = true;
        CB_MailGroups.disabled = true;
    }
    //else if (RB_SpecificTypes.checked == true) {

    //}
}

function PublicFolderPermission(DDL, CBCI, CBFO, CBRI, CBFC, CBCSF, CBFV, CBEO, CBDO, CBEA, CBDA) {
    var DDL_PermissionLevel = document.getElementById(DDL);
    var ChBx_CreateItems = document.getElementById(CBCI);
    var ChBx_FolderOwner = document.getElementById(CBFO);
    var ChBx_ReadItems = document.getElementById(CBRI);
    var ChBx_FolderContact = document.getElementById(CBFC);
    var ChBx_CreateSubFolders = document.getElementById(CBCSF);
    var ChBx_FolderVisible = document.getElementById(CBFV);
    var ChBx_EditOwn = document.getElementById(CBEO);
    var ChBx_DeleteOwn = document.getElementById(CBDO);
    var ChBx_EditAll = document.getElementById(CBEA);
    var ChBx_DeleteAll = document.getElementById(CBDA);


    //reset checkboxes when non custom option is sleected.
    if (DDL_PermissionLevel.selectedIndex > 0) {
        ChBx_CreateItems.checked = false;
        ChBx_FolderOwner.checked = false;
        ChBx_ReadItems.checked = false;
        ChBx_FolderContact.checked = false;
        ChBx_CreateSubFolders.checked = false;
        ChBx_FolderVisible.checked = false;
        ChBx_EditOwn.checked = false;
        ChBx_DeleteOwn.checked = false;
        ChBx_EditAll.checked = false;
        ChBx_DeleteAll.checked = false;
    }
    else
        return;


    if (!(DDL_PermissionLevel && DDL_PermissionLevel.options))
        return;

    if (DDL_PermissionLevel.options[DDL_PermissionLevel.selectedIndex].value == "none") {// None
        // ChBx_FolderVisible.checked = true;
    }
    else if (DDL_PermissionLevel.options[DDL_PermissionLevel.selectedIndex].value == "availabilityonly") {// availabilityonly

    }
    else if (DDL_PermissionLevel.options[DDL_PermissionLevel.selectedIndex].value == "limiteddetails") {// limiteddetails

    }
    else if (DDL_PermissionLevel.options[DDL_PermissionLevel.selectedIndex].value == "reviewer") {// Reviewer
        ChBx_ReadItems.checked = true;
        ChBx_FolderVisible.checked = true;
    }
    else if (DDL_PermissionLevel.options[DDL_PermissionLevel.selectedIndex].value == "contributor") {// Contributer
        ChBx_CreateItems.checked = true;
        ChBx_FolderVisible.checked = true;
    }
    else if (DDL_PermissionLevel.options[DDL_PermissionLevel.selectedIndex].value == "noneditingauthor") {// Non Editing Author
        ChBx_CreateItems.checked = true;
        ChBx_FolderVisible.checked = true;
        ChBx_ReadItems.checked = true;
        ChBx_DeleteOwn.checked = true;
    }
    else if (DDL_PermissionLevel.options[DDL_PermissionLevel.selectedIndex].value == "author") {// Author
        ChBx_CreateItems.checked = true;
        ChBx_FolderVisible.checked = true;
        ChBx_ReadItems.checked = true;
        ChBx_EditOwn.checked = true;
        ChBx_DeleteOwn.checked = true;
    }
    else if (DDL_PermissionLevel.options[DDL_PermissionLevel.selectedIndex].value == "editor") {// Editor
        ChBx_CreateItems.checked = true;
        ChBx_FolderVisible.checked = true;
        ChBx_ReadItems.checked = true;
        ChBx_EditOwn.checked = true;
        ChBx_DeleteOwn.checked = true;
        ChBx_EditAll.checked = true;
        ChBx_DeleteAll.checked = true;
    }
    else if (DDL_PermissionLevel.options[DDL_PermissionLevel.selectedIndex].value == "publishingauthor") {// Publishing Author
        ChBx_CreateItems.checked = true;
        ChBx_FolderVisible.checked = true;
        ChBx_ReadItems.checked = true;
        ChBx_CreateSubFolders.checked = true;
        ChBx_EditOwn.checked = true;
        ChBx_DeleteOwn.checked = true;
        ChBx_DeleteAll.checked = true;
    }
    else if (DDL_PermissionLevel.options[DDL_PermissionLevel.selectedIndex].value == "publishingeditor") {// Publishing Editor
        ChBx_CreateItems.checked = true;
        ChBx_FolderVisible.checked = true;
        ChBx_ReadItems.checked = true;
        ChBx_CreateSubFolders.checked = true;
        ChBx_EditOwn.checked = true;
        ChBx_DeleteOwn.checked = true;
        ChBx_EditAll.checked = true;
        ChBx_DeleteAll.checked = true;
    }
    else if (DDL_PermissionLevel.options[DDL_PermissionLevel.selectedIndex].value == "owner") {// Owner
        ChBx_CreateItems.checked = true;
        ChBx_FolderOwner.checked = true;
        ChBx_ReadItems.checked = true;
        ChBx_FolderContact.checked = true;
        ChBx_CreateSubFolders.checked = true;
        ChBx_FolderVisible.checked = true;
        ChBx_EditOwn.checked = true;
        ChBx_DeleteOwn.checked = true;
        ChBx_EditAll.checked = true;
        ChBx_DeleteAll.checked = true;
    }
}

function PublicFolderCustomPermission(DDL, CB) {
    var DDL_PermissionLevel = document.getElementById(DDL);
    var ChBx = document.getElementById(CB);
    var CB_State = ChBx.checked;
    DDL_PermissionLevel.selectedIndex = 0; $(DDL_PermissionLevel).trigger('change');
    setTimeout(function () { ChBx.checked = CB_State; }, 100);

}

function SPLATypeChanged(DDL, CB, TXT) {
    var DDL_SPLAType = document.getElementById(DDL);
    var TxBx = document.getElementById(TXT);
    var ChBx = document.getElementById(CB);

    changeTXTOnSPLAUpdate = 0;
    if ((DDL_SPLAType.options[DDL_SPLAType.selectedIndex].value == "1") || (DDL_SPLAType.options[DDL_SPLAType.selectedIndex].value == "2") || (DDL_SPLAType.options[DDL_SPLAType.selectedIndex].value == "3") || (DDL_SPLAType.options[DDL_SPLAType.selectedIndex].value == "4") || (DDL_SPLAType.options[DDL_SPLAType.selectedIndex].value == "5")) {
        if ((TxBx.disabled == false) && (ChBx.checked == false) && (TxBx.value > 0))

            setTimeout(function () { DDL_SPLAType.selectedIndex = 0; $(DDL_SPLAType).trigger('change'); }, 500);
        if (ChBx.checked == true)
            setTimeout(function () { DDL_SPLAType.selectedIndex = 0; $(DDL_SPLAType).trigger('change'); }, 500);

        else if (ChBx.checked == false)
            setTimeout(function () { DDL_SPLAType.selectedIndex = 0; $(DDL_SPLAType).trigger('change'); }, 500);

    }
}

function ChangeSPLAType(DDL, TxtMAPI, CBMAPI, TxtULMailbox, CBULMailbox, TxtOrg, CBOrg, TxtShared, CBShared, TxtResource, CBResource,
    TxtUM, CBUM, TxtOCAL, CBOCAL, TxtArMB, CBArMB, TxtAS, CBAS, TxtNCach, CBNCach, TxtASA, CBASA, TxtOPF, CBOPF, CBOWAUM, TxtOWAUM, TxtPOP3, CBPOP3,
    TxtIMAP, CBIMAP, TxtOWAHTTPA, CBOWAHTTPA, TxtOWAAList, CBOWAAList, TxtOWACal, CBOWACal, TxtOWAContacts, CBOWAContacts, TxtOWACP, CBOWACP,
    TxtOWAj, CBOWAj, TxtOWAtask, CBOWAtask, TxtOWASN, CBOWASN, TxtOWAPC, CBOWAPC, TxtOWARN, CBOWARN, TxtOWASC, CBOWASC, TxtOWASF, CBOWASF,
    TxtOWASig, CBOWASig, TxtOWAJM, CBOWAJM, TxtOWATSel, CBOWATSel, TxtJournal, CBJournal, TxtAllowLHToCustomer, CBAllowLHToCustomer,
    TxtInPlaceHold, CBIInPlaceHold, TxtEWSAllowed, CBEWSAllowed) {
    var DDL_SPLAType = document.getElementById(DDL);

    //****** If it is checkbox checked/un-checked no need to refresh Textboxes on custom SPLA **********
    if (changeTXTOnSPLAUpdate == 0 && DDL_SPLAType.options[DDL_SPLAType.selectedIndex].value == "0") {
        changeTXTOnSPLAUpdate = 1;
    }
    else {

        changeTXTOnSPLAUpdate = 1;
        var TxBx_MAPIAllowed = document.getElementById(TxtMAPI);
        var ChBx_MAPIAllowed = document.getElementById(CBMAPI);
        //var TxBx_MBPerOrg = document.getElementById(TxtMailbox);
        //var ChBx_MBPerOrg = document.getElementById(CBMailbox);
        var TxBx_ExchOrgs = document.getElementById(TxtOrg);
        var ChBx_ExchOrgs = document.getElementById(CBOrg);
        var TxBx_UM = document.getElementById(TxtUM);
        var ChBx_UM = document.getElementById(CBUM);
        var TxBx_OutLookCAL = document.getElementById(TxtOCAL);
        var ChBx_OutLookCAL = document.getElementById(CBOCAL);
        var TxBx_ArchiveMBs = document.getElementById(TxtArMB);
        var ChBx_ArchiveMBs = document.getElementById(CBArMB);
        var TxBx_OwAActiveSync = document.getElementById(TxtAS);
        var ChBx_OwAActiveSync = document.getElementById(CBAS);
        var TxBx_OLNonCachedModeAllowed = document.getElementById(TxtNCach);
        var ChBx_OLNonCachedModeAllowed = document.getElementById(CBNCach);
        var TxBx_EXActiveSyncAllowed = document.getElementById(TxtASA);
        var ChBx_EXActiveSyncAllowed = document.getElementById(CBASA);
        var TxBx_OwAPublicFolder = document.getElementById(TxtOPF);
        var ChBx_OwAPublicFolder = document.getElementById(CBOPF);
        var ChBx_OWAUMIntegration = document.getElementById(CBOWAUM);
        var TxBx_OWAUMIntegration = document.getElementById(TxtOWAUM);
        var ChBx_Journaling = document.getElementById(CBJournal);
        var TxBx_Journaling = document.getElementById(TxtJournal);
        var ChBx_AllowLHToCustomer = document.getElementById(CBAllowLHToCustomer);
        var TxBx_AllowLHToCustomer = document.getElementById(TxtAllowLHToCustomer);
        var ChBx_InPlaceHold = document.getElementById(CBIInPlaceHold);
        var TxBx_InPlaceHold = document.getElementById(TxtInPlaceHold);
        var ChBx_EWSAllowed = document.getElementById(CBEWSAllowed);
        var TxBx_EWSAllowed = document.getElementById(TxtEWSAllowed);

        //var TxBx_Pop3Allowed = document.getElementById(TxtPOP3);
        //var ChBx_Pop3Allowed = document.getElementById(CBPOP3);
        PopulateProduct(CBPOP3, TxtULMailbox, CBULMailbox, TxtOrg, CBOrg, TxtPOP3, TxtShared, CBShared, TxtResource, CBResource);
        PopulateProduct(CBIMAP, TxtULMailbox, CBULMailbox, TxtOrg, CBOrg, TxtIMAP, TxtShared, CBShared, TxtResource, CBResource);
        PopulateProduct(CBMAPI, TxtULMailbox, CBULMailbox, TxtOrg, CBOrg, TxtMAPI, TxtShared, CBShared, TxtResource, CBResource);
        PopulateProduct(CBOWAHTTPA, TxtULMailbox, CBULMailbox, TxtOrg, CBOrg, TxtOWAHTTPA, TxtShared, CBShared, TxtResource, CBResource);
        PopulateProduct(CBOWAAList, TxtULMailbox, CBULMailbox, TxtOrg, CBOrg, TxtOWAAList, TxtShared, CBShared, TxtResource, CBResource);
        PopulateProduct(CBOWACal, TxtULMailbox, CBULMailbox, TxtOrg, CBOrg, TxtOWACal, TxtShared, CBShared, TxtResource, CBResource);
        PopulateProduct(CBOWAContacts, TxtULMailbox, CBULMailbox, TxtOrg, CBOrg, TxtOWAContacts, TxtShared, CBShared, TxtResource, CBResource);
        PopulateProduct(CBOWACP, TxtULMailbox, CBULMailbox, TxtOrg, CBOrg, TxtOWACP, TxtShared, CBShared, TxtResource, CBResource);
        PopulateProduct(CBOWAj, TxtULMailbox, CBULMailbox, TxtOrg, CBOrg, TxtOWAj, TxtShared, CBShared, TxtResource, CBResource);
        PopulateProduct(CBOWAtask, TxtULMailbox, CBULMailbox, TxtOrg, CBOrg, TxtOWAtask, TxtShared, CBShared, TxtResource, CBResource);
        PopulateProduct(CBOWASN, TxtULMailbox, CBULMailbox, TxtOrg, CBOrg, TxtOWASN, TxtShared, CBShared, TxtResource, CBResource);
        PopulateProduct(CBOWAPC, TxtULMailbox, CBULMailbox, TxtOrg, CBOrg, TxtOWAPC, TxtShared, CBShared, TxtResource, CBResource);
        PopulateProduct(CBOWARN, TxtULMailbox, CBULMailbox, TxtOrg, CBOrg, TxtOWARN, TxtShared, CBShared, TxtResource, CBResource);
        PopulateProduct(CBOWASC, TxtULMailbox, CBULMailbox, TxtOrg, CBOrg, TxtOWASC, TxtShared, CBShared, TxtResource, CBResource);
        PopulateProduct(CBOWASF, TxtULMailbox, CBULMailbox, TxtOrg, CBOrg, TxtOWASF, TxtShared, CBShared, TxtResource, CBResource);
        PopulateProduct(CBOWASig, TxtULMailbox, CBULMailbox, TxtOrg, CBOrg, TxtOWASig, TxtShared, CBShared, TxtResource, CBResource);
        PopulateProduct(CBOWAJM, TxtULMailbox, CBULMailbox, TxtOrg, CBOrg, TxtOWAJM, TxtShared, CBShared, TxtResource, CBResource);
        PopulateProduct(CBOWATSel, TxtULMailbox, CBULMailbox, TxtOrg, CBOrg, TxtOWATSel, TxtShared, CBShared, TxtResource, CBResource);
        if (ChBx_UM != null) {
            PopulateProduct(CBUM, TxtULMailbox, CBULMailbox, TxtOrg, CBOrg, TxtUM, TxtShared, CBShared, TxtResource, CBResource);
        }
        if (ChBx_Journaling != null) {
            PopulateProduct(CBJournal, TxtULMailbox, CBULMailbox, TxtOrg, CBOrg, TxtJournal, TxtShared, CBShared, TxtResource, CBResource);
        }
        if (ChBx_AllowLHToCustomer != null) {
            PopulateProduct(CBAllowLHToCustomer, TxtULMailbox, CBULMailbox, TxtOrg, CBOrg, TxtAllowLHToCustomer, TxtShared, CBShared, TxtResource, CBResource);
        }
        if (ChBx_InPlaceHold != null) {
            PopulateProduct(CBIInPlaceHold, TxtULMailbox, CBULMailbox, TxtOrg, CBOrg, TxtInPlaceHold, TxtShared, CBShared, TxtResource, CBResource);
        }
        if (ChBx_EWSAllowed != null) {
            PopulateProduct(CBEWSAllowed, TxtULMailbox, CBULMailbox, TxtOrg, CBOrg, TxtEWSAllowed, TxtShared, CBShared, TxtResource, CBResource);
        }
        if (ChBx_ArchiveMBs != null) {
            PopulateProduct(CBArMB, TxtULMailbox, CBULMailbox, TxtOrg, CBOrg, TxtArMB, TxtShared, CBShared, TxtResource, CBResource);
        }

        PopulateProduct(CBAS, TxtULMailbox, CBULMailbox, TxtOrg, CBOrg, TxtAS, TxtShared, CBShared, TxtResource, CBResource);
        PopulateProduct(CBNCach, TxtULMailbox, CBULMailbox, TxtOrg, CBOrg, TxtNCach, TxtShared, CBShared, TxtResource, CBResource);
        PopulateProduct(CBASA, TxtULMailbox, CBULMailbox, TxtOrg, CBOrg, TxtASA, TxtShared, CBShared, TxtResource, CBResource);
        if (ChBx_OwAPublicFolder != null) {
            PopulateProduct(CBOPF, TxtULMailbox, CBULMailbox, TxtOrg, CBOrg, TxtOPF, TxtShared, CBShared, TxtResource, CBResource);
        }
        PopulateProduct(CBOWAUM, TxtULMailbox, CBULMailbox, TxtOrg, CBOrg, TxtOWAUM, TxtShared, CBShared, TxtResource, CBResource);
        PopulateProduct(CBJournal, TxtULMailbox, CBULMailbox, TxtOrg, CBOrg, TxtJournal, TxtShared, CBShared, TxtResource, CBResource);
        PopulateProduct(CBAllowLHToCustomer, TxtULMailbox, CBULMailbox, TxtOrg, CBOrg, TxtAllowLHToCustomer, TxtShared, CBShared, TxtResource, CBResource);
        PopulateProduct(CBIInPlaceHold, TxtULMailbox, CBULMailbox, TxtOrg, CBOrg, TxtInPlaceHold, TxtShared, CBShared, TxtResource, CBResource);
        PopulateProduct(CBOCAL, TxtULMailbox, CBULMailbox, TxtOrg, CBOrg, TxtOCAL, TxtShared, CBShared, TxtResource, CBResource);

        //********************************************************************************
        //************Product will be populated for all Permissions and OWA settings,
        //************only significant will be reset below as per SPLA Type Selection
        //********************************************************************************

        //Refresh all controls if Type is not Custom
        if (DDL_SPLAType.options[DDL_SPLAType.selectedIndex].value != "0") {

            TxBx_MAPIAllowed.value = '';
            TxBx_MAPIAllowed.disabled = true;
            $(TxBx_MAPIAllowed).addClass('disabled');
            ChBx_MAPIAllowed.checked = true;
            ChBx_OwAActiveSync.checked = true;
            TxBx_OwAActiveSync.disabled = true;
            $(TxBx_OwAActiveSync).addClass('disabled');
            TxBx_OwAActiveSync.value = '';
            ChBx_OLNonCachedModeAllowed.checked = true;
            TxBx_OLNonCachedModeAllowed.disabled = true;
            $(TxBx_OLNonCachedModeAllowed).addClass('disabled');
            TxBx_OLNonCachedModeAllowed.value = '';
            ChBx_EXActiveSyncAllowed.checked = true;
            TxBx_EXActiveSyncAllowed.disabled = true;
            $(TxBx_EXActiveSyncAllowed).addClass('disabled');
            TxBx_EXActiveSyncAllowed.value = '';
            ChBx_OWAUMIntegration.checked = true;
            TxBx_OWAUMIntegration.disabled = true;
            $(TxBx_OWAUMIntegration).addClass('disabled');
            TxBx_OWAUMIntegration.value = '';
            ChBx_OutLookCAL.checked = true;
            TxBx_OutLookCAL.disabled = true;
            $(TxBx_OutLookCAL).addClass('disabled');
            TxBx_OutLookCAL.value = '';

            if (ChBx_UM != null) {
                ChBx_UM.checked = true;
                TxBx_UM.disabled = true;
                $(TxBx_UM).addClass('disabled');
                TxBx_UM.value = '';
            }
            if (ChBx_Journaling != null) {
                ChBx_Journaling.checked = true;
                TxBx_Journaling.disabled = true;
                $(TxBx_Journaling).addClass('disabled');
                TxBx_Journaling.value = '';
            }
            if (ChBx_AllowLHToCustomer != null) {
                ChBx_AllowLHToCustomer.checked = true;
                TxBx_AllowLHToCustomer.disabled = true;
                $(TxBx_AllowLHToCustomer).addClass('disabled');
                TxBx_AllowLHToCustomer.value = '';
            }
            if (ChBx_InPlaceHold != null) {
                ChBx_InPlaceHold.checked = true;
                TxBx_InPlaceHold.disabled = true;
                $(TxBx_InPlaceHold).addClass('disabled');
                TxBx_InPlaceHold.value = '';
            }
            if (ChBx_EWSAllowed != null) {
                ChBx_EWSAllowed.checked = true;
                TxBx_EWSAllowed.disabled = true;
                $(TxBx_EWSAllowed).addClass('disabled');
                TxBx_EWSAllowed.value = '';
            }
            if (ChBx_ArchiveMBs != null) {
                ChBx_ArchiveMBs.checked = true;
                TxBx_ArchiveMBs.disabled = true;
                $(TxBx_ArchiveMBs).addClass('disabled');
                TxBx_ArchiveMBs.value = '';
            }
            if (ChBx_OwAPublicFolder != null) {
                ChBx_OwAPublicFolder.checked = true;
                TxBx_OwAPublicFolder.disabled = true;
                $(TxBx_OwAPublicFolder).addClass('disabled');
                TxBx_OwAPublicFolder.value = '';
            }

            //Refresh all controls ends here
        }


        if (DDL_SPLAType.options[DDL_SPLAType.selectedIndex].value == "1") { // Basic

            ChBx_MAPIAllowed.checked = false;
            TxBx_MAPIAllowed.disabled = false;
            $(TxBx_MAPIAllowed).removeClass('disabled');
            TxBx_MAPIAllowed.value = "0";
            ChBx_OwAActiveSync.checked = false;
            TxBx_OwAActiveSync.disabled = false;
            $(TxBx_OwAActiveSync).removeClass('disabled');
            TxBx_OwAActiveSync.value = '0';
            ChBx_OLNonCachedModeAllowed.checked = false;
            TxBx_OLNonCachedModeAllowed.disabled = false;
            $(TxBx_OLNonCachedModeAllowed).removeClass('disabled');
            TxBx_OLNonCachedModeAllowed.value = "0";
            ChBx_EXActiveSyncAllowed.checked = false;
            TxBx_EXActiveSyncAllowed.disabled = false;
            $(TxBx_EXActiveSyncAllowed).removeClass('disabled');
            TxBx_EXActiveSyncAllowed.value = "0";
            ChBx_OWAUMIntegration.checked = false;
            TxBx_OWAUMIntegration.disabled = false;
            $(TxBx_OWAUMIntegration).removeClass('disabled');
            TxBx_OWAUMIntegration.value = "0";
            ChBx_OutLookCAL.checked = false;
            TxBx_OutLookCAL.disabled = false;
            $(TxBx_OutLookCAL).removeClass('disabled');
            TxBx_OutLookCAL.value = "0";

            if (ChBx_UM != null) {
                ChBx_UM.checked = false;
                TxBx_UM.disabled = false;
                $(TxBx_UM).removeClass('disabled');
                TxBx_UM.value = "0";
            }
            if (ChBx_Journaling != null) {
                ChBx_Journaling.checked = false;
                TxBx_Journaling.disabled = false;
                $(TxBx_Journaling).removeClass('disabled');
                TxBx_Journaling.value = '0';
            }
            if (ChBx_AllowLHToCustomer != null) {
                ChBx_AllowLHToCustomer.checked = false;
                TxBx_AllowLHToCustomer.disabled = false;
                $(TxBx_AllowLHToCustomer).removeClass('disabled');
                TxBx_AllowLHToCustomer.value = '0';
            }
            if (ChBx_InPlaceHold != null) {
                ChBx_InPlaceHold.checked = false;
                TxBx_InPlaceHold.disabled = false;
                $(TxBx_InPlaceHold).removeClass('disabled');
                TxBx_InPlaceHold.value = '0';
            }
            if (ChBx_EWSAllowed != null) {
                ChBx_EWSAllowed.checked = false;
                TxBx_EWSAllowed.disabled = false;
                $(TxBx_EWSAllowed).removeClass('disabled');
                TxBx_EWSAllowed.value = '0';
            }
            if (ChBx_ArchiveMBs != null) {
                ChBx_ArchiveMBs.checked = false;
                TxBx_ArchiveMBs.disabled = false;
                $(TxBx_ArchiveMBs).removeClass('disabled');
                TxBx_ArchiveMBs.value = "0";
            }
            if (ChBx_OwAPublicFolder != null) {
                ChBx_OwAPublicFolder.checked = false;
                TxBx_OwAPublicFolder.disabled = false;
                $(TxBx_OwAPublicFolder).removeClass('disabled');
                TxBx_OwAPublicFolder.value = "0";
            }
        }
        else if ((DDL_SPLAType.options[DDL_SPLAType.selectedIndex].value == "2") || (DDL_SPLAType.options[DDL_SPLAType.selectedIndex].value == "3") || (DDL_SPLAType.options[DDL_SPLAType.selectedIndex].value == "4") || (DDL_SPLAType.options[DDL_SPLAType.selectedIndex].value == "5")) {

            PopulateProduct(CBMAPI, TxtULMailbox, CBULMailbox, TxtOrg, CBOrg, TxtMAPI, TxtShared, CBShared, TxtResource, CBResource);
            if (ChBx_UM != null) {
                PopulateProduct(CBUM, TxtULMailbox, CBULMailbox, TxtOrg, CBOrg, TxtUM, TxtShared, CBShared, TxtResource, CBResource);
            }
            if (ChBx_Journaling != null) {
                PopulateProduct(CBJournal, TxtULMailbox, CBULMailbox, TxtOrg, CBOrg, TxtJournal, TxtShared, CBShared, TxtResource, CBResource);
            }
            if (ChBx_AllowLHToCustomer != null) {
                PopulateProduct(CBAllowLHToCustomer, TxtULMailbox, CBULMailbox, TxtOrg, CBOrg, TxtAllowLHToCustomer, TxtShared, CBShared, TxtResource, CBResource);
            }
            if (ChBx_InPlaceHold != null) {
                PopulateProduct(CBIInPlaceHold, TxtULMailbox, CBULMailbox, TxtOrg, CBOrg, TxtInPlaceHold, TxtShared, CBShared, TxtResource, CBResource);
            }
            if (ChBx_EWSAllowed != null) {
                PopulateProduct(CBEWSAllowed, TxtULMailbox, CBULMailbox, TxtOrg, CBOrg, TxtEWSAllowed, TxtShared, CBShared, TxtResource, CBResource);
            }
            PopulateProduct(CBOCAL, TxtULMailbox, CBULMailbox, TxtOrg, CBOrg, TxtOCAL, TxtShared, CBShared, TxtResource, CBResource);
            if (ChBx_ArchiveMBs != null) {
                PopulateProduct(CBArMB, TxtULMailbox, CBULMailbox, TxtOrg, CBOrg, TxtArMB, TxtShared, CBShared, TxtResource, CBResource);
            }

            PopulateProduct(CBAS, TxtULMailbox, CBULMailbox, TxtOrg, CBOrg, TxtAS, TxtShared, CBShared, TxtResource, CBResource);
            PopulateProduct(CBNCach, TxtULMailbox, CBULMailbox, TxtOrg, CBOrg, TxtNCach, TxtShared, CBShared, TxtResource, CBResource);
            PopulateProduct(CBASA, TxtULMailbox, CBULMailbox, TxtOrg, CBOrg, TxtASA, TxtShared, CBShared, TxtResource, CBResource);
            if (ChBx_OwAPublicFolder != null) {
                PopulateProduct(CBOPF, TxtULMailbox, CBULMailbox, TxtOrg, CBOrg, TxtOPF, TxtShared, CBShared, TxtResource, CBResource);
            }
            PopulateProduct(CBOWAUM, TxtULMailbox, CBULMailbox, TxtOrg, CBOrg, TxtOWAUM, TxtShared, CBShared, TxtResource, CBResource);

            if (DDL_SPLAType.options[DDL_SPLAType.selectedIndex].value == "2") { //Standard
                //UM is inclued in Standard since 2014
                //if (ChBx_UM != null) {
                //    ChBx_UM.checked = false;
                //    TxBx_UM.disabled = false;
                //    TxBx_UM.value = "0";
                //}

                ChBx_OutLookCAL.checked = false;
                TxBx_OutLookCAL.disabled = false;
                $(TxBx_OutLookCAL).removeClass('disabled');
                TxBx_OutLookCAL.value = "0";
                if (ChBx_ArchiveMBs != null) {
                    ChBx_ArchiveMBs.checked = false;
                    TxBx_ArchiveMBs.disabled = false;
                    $(TxBx_ArchiveMBs).removeClass('disabled');
                    TxBx_ArchiveMBs.value = "0";
                }

                if (ChBx_Journaling != null) {
                    ChBx_Journaling.checked = false;
                    TxBx_Journaling.disabled = false;
                    $(TxBx_Journaling).removeClass('disabled');
                    TxBx_Journaling.value = "0";
                }
                if (ChBx_AllowLHToCustomer != null) {
                    ChBx_AllowLHToCustomer.checked = false;
                    TxBx_AllowLHToCustomer.disabled = false;
                    $(TxBx_AllowLHToCustomer).removeClass('disabled');
                    TxBx_AllowLHToCustomer.value = "0";
                }
                if (ChBx_InPlaceHold != null) {
                    ChBx_InPlaceHold.checked = false;
                    TxBx_InPlaceHold.disabled = false;
                    $(TxBx_InPlaceHold).removeClass('disabled');
                    TxBx_InPlaceHold.value = "0";
                }

            }
            else if (DDL_SPLAType.options[DDL_SPLAType.selectedIndex].value == "3") { //Standard Plus
                //UM is inclued in Standard since 2014
                //if (ChBx_UM != null) {
                //    ChBx_UM.checked = false;
                //    TxBx_UM.disabled = false;
                //    TxBx_UM.value = "0";
                //}

                if (ChBx_ArchiveMBs != null) {
                    ChBx_ArchiveMBs.checked = false;
                    TxBx_ArchiveMBs.disabled = false;
                    $(TxBx_ArchiveMBs).removeClass('disabled');
                    TxBx_ArchiveMBs.value = "0";
                }

                if (ChBx_Journaling != null) {
                    ChBx_Journaling.checked = false;
                    TxBx_Journaling.disabled = false;
                    $(TxBx_Journaling).removeClass('disabled');
                    TxBx_Journaling.value = "0";
                }
                if (ChBx_AllowLHToCustomer != null) {
                    ChBx_AllowLHToCustomer.checked = false;
                    TxBx_AllowLHToCustomer.disabled = false;
                    $(TxBx_AllowLHToCustomer).removeClass('disabled');
                    TxBx_AllowLHToCustomer.value = "0";
                }
                if (ChBx_InPlaceHold != null) {
                    ChBx_InPlaceHold.checked = false;
                    TxBx_InPlaceHold.disabled = false;
                    $(TxBx_InPlaceHold).removeClass('disabled');
                    TxBx_InPlaceHold.value = "0";
                }
            }
            else if (DDL_SPLAType.options[DDL_SPLAType.selectedIndex].value == "4") { //Enterprise
                ChBx_OutLookCAL.checked = false;
                TxBx_OutLookCAL.disabled = false;
                $(TxBx_OutLookCAL).removeClass('disabled');
                TxBx_OutLookCAL.value = '0';
            }
            else if (DDL_SPLAType.options[DDL_SPLAType.selectedIndex].value == "5") { //Enterprise Plus
                //All should be active
            }
        }
    }

}

// TXT1 & CB1 is for User/Linked Mailboxes
// TXT3 & CB3 is for Resource/Shared Mailboxes

function GetTotalNumberOfMailboxes(TxBx_ULMBPerOrg, ULMBPerOrg, TxBx_SMBPerOrg, SMBPerOrg, TxBx_RMBPerOrg, RMBPerOrg) {
    if (ULMBPerOrg || SMBPerOrg || RMBPerOrg)
        return -1;
    else
        return parseInt((!TxBx_ULMBPerOrg ? 0 : TxBx_ULMBPerOrg)) + parseInt((!TxBx_SMBPerOrg ? 0 : TxBx_SMBPerOrg)) + parseInt((!TxBx_RMBPerOrg ? 0 : TxBx_RMBPerOrg));
}

//No need to multiply orgs quota.
function PopulateProduct(CBRES, TXTUL, CBUL, TXTORG, CBORG, TXTRES, TXTSH, CBSH, TXTR, CBR) {
    var ChBxRes = document.getElementById(CBRES);
    var TxBxUL = document.getElementById(TXTUL);
    var ChBxUL = document.getElementById(CBUL);
    var TxBxSH = document.getElementById(TXTSH);
    var ChBxSH = document.getElementById(CBSH);
    var TxBxR = document.getElementById(TXTR);
    var ChBxR = document.getElementById(CBR);
    var TxBx2 = document.getElementById(TXTORG);
    var ChBx2 = document.getElementById(CBORG);
    var TxBxRes = document.getElementById(TXTRES);

    var TotalMBPerOrg = GetTotalNumberOfMailboxes(TxBxUL.value, ChBxUL.checked, TxBxSH.value, ChBxSH.checked, TxBxR.value, ChBxR.checked); // TxBxUL.value;

    /*
    if ((ChBxUL.checked == false) && ((TxBxUL.value == "") || (TxBxUL.value == "0")))
        TotalMBPerOrg = '0';*/

    if (TotalMBPerOrg == -1) {
        TxBxRes.disabled = true;
        $(TxBxRes).addClass('disabled');
        TxBxRes.value = '';
        ChBxRes.checked = true;
    }
    else if (TotalMBPerOrg == "0") {
        TxBxRes.disabled = false;
        $(TxBxRes).removeClass('disabled');
        TxBxRes.value = "0";
        ChBxRes.checked = false;
    }
    else if (TotalMBPerOrg != "") {
        TxBxRes.disabled = false;
        $(TxBxRes).removeClass('disabled');
        TxBxRes.value = (parseInt(TotalMBPerOrg));
        ChBxRes.checked = false;
    }
    else {
        TxBxRes.disabled = true;
        $(TxBxRes).addClass('disabled');
        TxBxRes.value = '';
        ChBxRes.checked = true;
    }
}

function ChangeSPLATypeMailBoxAdv(DDL, CBMAPI, CBOCAL, CBAS, CBNCach, CBASA, CBOPF, CBOWAUM, CBPop3, CBIMAP, CBOWAHTTP, CBOWAAL, CBOWACal, CBOWAC, CBOWACP,
    CBOWAJ, CBOWAT, CBOWASN, CBOWAPC, CBOWARN, CBOWASC, CBOWASF, CBOWASig, CBOWAJM, CBOWATSel, CBRPCOverHTTP, CBMAPIOverHTTP, CBEWSAcessAlwd) {
    var DDL_SPLAType = document.getElementById(DDL);
    var ChBx_MAPIAllowed = document.getElementById(CBMAPI);
    //var ChBx_UM = document.getElementById(CBUM);
    var ChBx_OutLookCAL = document.getElementById(CBOCAL);
    //var ChBx_ArchiveMBs = document.getElementById(CBArMB);
    var ChBx_OwAActiveSync = document.getElementById(CBAS);
    var ChBx_OLNonCachedModeAllowed = document.getElementById(CBNCach);
    var ChBx_EXActiveSyncAllowed = document.getElementById(CBASA);
    var ChBx_OwAPublicFolder = document.getElementById(CBOPF);
    var ChBx_OWAUMIntegration = document.getElementById(CBOWAUM);
    var CB_Pop3AcessAlwd = document.getElementById(CBPop3);
    var CB_IMAPAcessAlwd = document.getElementById(CBIMAP);
    var CB_OWA_HTTPAcessAlwd = document.getElementById(CBOWAHTTP);
    var CB_OWAAdrLstAlwd = document.getElementById(CBOWAAL);
    var CB_OWACalEnable = document.getElementById(CBOWACal);
    var CB_OWAContactEnable = document.getElementById(CBOWAC);
    var CB_OWAChangePwdEnable = document.getElementById(CBOWACP);
    var CB_OWAJournalEnable = document.getElementById(CBOWAJ);
    var CB_OWATaskEnable = document.getElementById(CBOWAT);
    var CB_OWAStickyN_Alwd = document.getElementById(CBOWASN);
    var CB_OWAPriClientEnable = document.getElementById(CBOWAPC);
    var CB_OWAReminder_Notify_Enable = document.getElementById(CBOWARN);
    var CB_OWASpellCheckEnable = document.getElementById(CBOWASC);
    var CB_OWASearchFolderEnable = document.getElementById(CBOWASF);
    var CB_OWASigEnable = document.getElementById(CBOWASig);
    var CB_OWAJunkEmailEnable = document.getElementById(CBOWAJM);
    var CB_OWAThemeSeleEnable = document.getElementById(CBOWATSel);
    var CB_RPCOverHTTP = document.getElementById(CBRPCOverHTTP);
    var CB_MAPIOverHTTP = document.getElementById(CBMAPIOverHTTP);
    var CB_EWSAcessAlwd = document.getElementById(CBEWSAcessAlwd);

    //Refresh if Type is not Custom
    if (DDL_SPLAType.options[DDL_SPLAType.selectedIndex].value != "0") {
        //alert("REFRESH");
        CB_Pop3AcessAlwd.checked = true;
        CB_IMAPAcessAlwd.checked = true;
        CB_OWA_HTTPAcessAlwd.checked = true;
        CB_OWAAdrLstAlwd.checked = true;
        CB_OWACalEnable.checked = true;
        CB_OWAContactEnable.checked = true;
        CB_OWAChangePwdEnable.checked = true;
        CB_OWAJournalEnable.checked = true;
        CB_OWATaskEnable.checked = true;
        CB_OWAStickyN_Alwd.checked = true;
        CB_OWAPriClientEnable.checked = true;
        CB_OWAReminder_Notify_Enable.checked = true;
        CB_OWASpellCheckEnable.checked = true;
        CB_OWASearchFolderEnable.checked = true;
        CB_OWASigEnable.checked = true;
        CB_OWAJunkEmailEnable.checked = true;
        CB_OWAThemeSeleEnable.checked = true;
        CB_EWSAcessAlwd.checked = true;
        ChBx_MAPIAllowed.checked = false;
        CB_RPCOverHTTP.checked = false;
        CB_MAPIOverHTTP.checked = false;
        //ChBx_UM.checked = false;

        if (ChBx_OutLookCAL != null) {
            ChBx_OutLookCAL.checked = false;
        }
        //ChBx_ArchiveMBs.checked = false;
        ChBx_OwAActiveSync.checked = false;
        ChBx_OLNonCachedModeAllowed.checked = false;
        ChBx_EXActiveSyncAllowed.checked = false;
        if (ChBx_OwAPublicFolder != null) {
            ChBx_OwAPublicFolder.checked = false;
        }
        ChBx_OWAUMIntegration.checked = false;
    }
    if (DDL_SPLAType.options[DDL_SPLAType.selectedIndex].value == "1") { //Basic
        //alert("IN BASIC");
        ChBx_MAPIAllowed.checked = false;
        //  alert(ChBx_MAPIAllowed);
        CB_RPCOverHTTP.checked = false;
        CB_MAPIOverHTTP.checked = false;
        // alert(CB_MAPIOverHTTP);
        //ChBx_UM.checked = false;
        if (ChBx_OutLookCAL != null) {
            ChBx_OutLookCAL.checked = false;
        }
        if (CB_EWSAcessAlwd != null) {
            CB_EWSAcessAlwd.checked = false;
        }
        //ChBx_ArchiveMBs.checked = false;
        ChBx_OwAActiveSync.checked = false;
        ChBx_OLNonCachedModeAllowed.checked = false;
        ChBx_EXActiveSyncAllowed.checked = false;
        if (ChBx_OwAPublicFolder != null) {
            ChBx_OwAPublicFolder.checked = false;
        }
        ChBx_OWAUMIntegration.checked = false;
    }
    else if ((DDL_SPLAType.options[DDL_SPLAType.selectedIndex].value == "2") || (DDL_SPLAType.options[DDL_SPLAType.selectedIndex].value == "3") || (DDL_SPLAType.options[DDL_SPLAType.selectedIndex].value == "4") || (DDL_SPLAType.options[DDL_SPLAType.selectedIndex].value == "5")) {
        //alert("IN COMB");
        ChBx_MAPIAllowed.checked = true;
        CB_RPCOverHTTP.checked = true;
        CB_MAPIOverHTTP.checked = true;
        ChBx_OWAUMIntegration.checked = true;
        ChBx_OwAActiveSync.checked = true;
        ChBx_OLNonCachedModeAllowed.checked = true;
        ChBx_EXActiveSyncAllowed.checked = true;
        CB_EWSAcessAlwd.checked = true;
        if (ChBx_OwAPublicFolder != null) {
            ChBx_OwAPublicFolder.checked = true;
        }
        if (DDL_SPLAType.options[DDL_SPLAType.selectedIndex].value == "2") {    //Standard

        }
        else if (DDL_SPLAType.options[DDL_SPLAType.selectedIndex].value == "3") {    //Standard Plus
            if (ChBx_OutLookCAL != null) {
                ChBx_OutLookCAL.checked = true;

            }
        }
        else if (DDL_SPLAType.options[DDL_SPLAType.selectedIndex].value == "4") {    //Enterprise
            //ChBx_UM.checked = true;
            //ChBx_ArchiveMBs.checked = true;
        }
        else if (DDL_SPLAType.options[DDL_SPLAType.selectedIndex].value == "5") {    //Enterprise Plus
            //ChBx_UM.checked = true;
            if (ChBx_OutLookCAL != null) {
                ChBx_OutLookCAL.checked = true;

            }
            //ChBx_ArchiveMBs.checked = true;
        }
    }
}

function SPLATypeChangedAdv(DDL, CB) {
    var DDL_SPLAType = document.getElementById(DDL);
    var ChBx = document.getElementById(CB);
    //alert("IN");
    if ((DDL_SPLAType.options[DDL_SPLAType.selectedIndex].value == "1") || (DDL_SPLAType.options[DDL_SPLAType.selectedIndex].value == "2") || (DDL_SPLAType.options[DDL_SPLAType.selectedIndex].value == "3") || (DDL_SPLAType.options[DDL_SPLAType.selectedIndex].value == "4") || (DDL_SPLAType.options[DDL_SPLAType.selectedIndex].value == "5")) {
        //        if ((TxBx.disabled == false) && (ChBx.checked == false) && (TxBx.value > 0))
        //            DDL_SPLAType.options[0].selected = true;
        if (ChBx.checked == true)
            setTimeout(function () { DDL_SPLAType.selectedIndex = 0; $(DDL_SPLAType).trigger('change'); }, 500);
        else if (ChBx.checked == false)
            setTimeout(function () { DDL_SPLAType.selectedIndex = 0; $(DDL_SPLAType).trigger('change'); }, 500);
    }
}

function ChangeSPLATypeAddon(DDL, TxtMAPI, TxtULMailbox, TxtRMailbox, TxtSMailbox, TxtOrg, TxtUM, TxtOCAL, TxtArMB, TxtAS, TxtNCach, TxtASA, TxtOPF, TxtOWAUM,
    TxtPop3, TxtIMAP, TxtOWAHTTP, TxtOWAAL, TxtOWACal, TxtOWAC, TxtOWACP, TxtOWAJ, TxtOWAT, TxtOWASN, TxtOWAPC, TxtOWARN, TxtOWASC, TxtOWASF, TxtOWASig,
    TxtOWAJM, TxtOWATSel, TxtJournaling, TxtAllowLHToCustomer, TxtInPlaceHoldAllowed, TxtEWSAllowed) {
    var DDL_SPLAType = document.getElementById(DDL);
    var TxBx_MAPIAllowed = document.getElementById(TxtMAPI);
    var TxBx_ExchOrgs = document.getElementById(TxtOrg);
    var TxBx_UM = document.getElementById(TxtUM);
    var TxBx_OutLookCAL = document.getElementById(TxtOCAL);
    var TxBx_ArchiveMBs = document.getElementById(TxtArMB);
    var TxBx_OwAActiveSync = document.getElementById(TxtAS);
    var TxBx_OLNonCachedModeAllowed = document.getElementById(TxtNCach);
    var TxBx_EXActiveSyncAllowed = document.getElementById(TxtASA);
    var TxBx_OwAPublicFolder = document.getElementById(TxtOPF);
    var TxBx_OWAUMIntegration = document.getElementById(TxtOWAUM);
    var TxBx_Journaling = document.getElementById(TxtJournaling);
    var TxBx_AllowLHToCustomer = document.getElementById(TxtAllowLHToCustomer);
    var TxBx_InPlaceHoldAllowed = document.getElementById(TxtInPlaceHoldAllowed);
    var TxBx_EWSAllowed = document.getElementById(TxtEWSAllowed);

    PopulateProductAddOn(TxtULMailbox, TxtRMailbox, TxtSMailbox, TxtOrg, TxtPop3);
    PopulateProductAddOn(TxtULMailbox, TxtRMailbox, TxtSMailbox, TxtOrg, TxtIMAP);
    PopulateProductAddOn(TxtULMailbox, TxtRMailbox, TxtSMailbox, TxtOrg, TxtMAPI);
    PopulateProductAddOn(TxtULMailbox, TxtRMailbox, TxtSMailbox, TxtOrg, TxtOWAHTTP);
    PopulateProductAddOn(TxtULMailbox, TxtRMailbox, TxtSMailbox, TxtOrg, TxtOWAAL);
    PopulateProductAddOn(TxtULMailbox, TxtRMailbox, TxtSMailbox, TxtOrg, TxtOWACal);
    PopulateProductAddOn(TxtULMailbox, TxtRMailbox, TxtSMailbox, TxtOrg, TxtOWAC);
    PopulateProductAddOn(TxtULMailbox, TxtRMailbox, TxtSMailbox, TxtOrg, TxtOWACP);
    PopulateProductAddOn(TxtULMailbox, TxtRMailbox, TxtSMailbox, TxtOrg, TxtOWAJ);
    PopulateProductAddOn(TxtULMailbox, TxtRMailbox, TxtSMailbox, TxtOrg, TxtOWAT);
    PopulateProductAddOn(TxtULMailbox, TxtRMailbox, TxtSMailbox, TxtOrg, TxtOWASN);
    PopulateProductAddOn(TxtULMailbox, TxtRMailbox, TxtSMailbox, TxtOrg, TxtOWAPC);
    PopulateProductAddOn(TxtULMailbox, TxtRMailbox, TxtSMailbox, TxtOrg, TxtOWARN);
    PopulateProductAddOn(TxtULMailbox, TxtRMailbox, TxtSMailbox, TxtOrg, TxtOWASC);
    PopulateProductAddOn(TxtULMailbox, TxtRMailbox, TxtSMailbox, TxtOrg, TxtOWASF);
    PopulateProductAddOn(TxtULMailbox, TxtRMailbox, TxtSMailbox, TxtOrg, TxtOWASig);
    PopulateProductAddOn(TxtULMailbox, TxtRMailbox, TxtSMailbox, TxtOrg, TxtOWAJM);
    PopulateProductAddOn(TxtULMailbox, TxtRMailbox, TxtSMailbox, TxtOrg, TxtOWATSel);
    if (TxBx_UM != null)
        PopulateProductAddOn(TxtULMailbox, TxtRMailbox, TxtSMailbox, TxtOrg, TxtUM);
    if (TxBx_Journaling != null)
        PopulateProductAddOn(TxtULMailbox, TxtRMailbox, TxtSMailbox, TxtOrg, TxtJournaling);
    if (TxBx_AllowLHToCustomer != null)
        PopulateProductAddOn(TxtULMailbox, TxtRMailbox, TxtSMailbox, TxtOrg, TxtAllowLHToCustomer);
    if (TxBx_InPlaceHoldAllowed != null)
        PopulateProductAddOn(TxtULMailbox, TxtRMailbox, TxtSMailbox, TxtOrg, TxtInPlaceHoldAllowed);
    if (TxBx_EWSAllowed != null)
        PopulateProductAddOn(TxtULMailbox, TxtRMailbox, TxtSMailbox, TxtOrg, TxtEWSAllowed);
    if (TxBx_ArchiveMBs != null)
        PopulateProductAddOn(TxtULMailbox, TxtRMailbox, TxtSMailbox, TxtOrg, TxtArMB);
    PopulateProductAddOn(TxtULMailbox, TxtRMailbox, TxtSMailbox, TxtOrg, TxtAS);
    PopulateProductAddOn(TxtULMailbox, TxtRMailbox, TxtSMailbox, TxtOrg, TxtNCach);
    PopulateProductAddOn(TxtULMailbox, TxtRMailbox, TxtSMailbox, TxtOrg, TxtASA);
    if (TxBx_OwAPublicFolder != null) {
        PopulateProductAddOn(TxtULMailbox, TxtRMailbox, TxtSMailbox, TxtOrg, TxtOPF);
    }
    PopulateProductAddOn(TxtULMailbox, TxtRMailbox, TxtSMailbox, TxtOrg, TxtOWAUM);
    PopulateProductAddOn(TxtULMailbox, TxtRMailbox, TxtSMailbox, TxtOrg, TxtOCAL);

    //********************************************************************************
    //************Product will be populated for all Permissions and OWA settings,
    //************only significant will be reset below as per SPLA Type Selection
    //********************************************************************************

    //Refresh all controls if SPLA isn't Custom
    if (DDL_SPLAType.options[DDL_SPLAType.selectedIndex].value != "0") {
        TxBx_MAPIAllowed.value = '';
        TxBx_OwAActiveSync.value = '';
        TxBx_OLNonCachedModeAllowed.value = '';
        TxBx_EXActiveSyncAllowed.value = '';
        TxBx_OWAUMIntegration.value = '';
        TxBx_OutLookCAL.value = '';

        if (TxBx_UM != null)
            TxBx_UM.value = '';
        if (TxBx_Journaling != null)
            TxBx_Journaling.value = '';
        if (TxBx_AllowLHToCustomer != null)
            TxBx_AllowLHToCustomer.value = '';
        if (TxBx_InPlaceHoldAllowed != null)
            TxBx_InPlaceHoldAllowed.value = '';
        if (TxBx_EWSAllowed != null)
            TxBx_EWSAllowed.value = '';
        if (TxBx_ArchiveMBs != null)
            TxBx_ArchiveMBs.value = '';
        if (TxBx_OwAPublicFolder != null) {
            TxBx_OwAPublicFolder.value = '';
        }
    }
    //Refresh all controls Ends here

    if (DDL_SPLAType.options[DDL_SPLAType.selectedIndex].value == "1") { //Basic
        TxBx_MAPIAllowed.value = "0";
        TxBx_OwAActiveSync.value = "0";
        TxBx_OLNonCachedModeAllowed.value = "0";
        TxBx_EXActiveSyncAllowed.value = "0";
        TxBx_OutLookCAL.value = "0";
        TxBx_OWAUMIntegration.value = "0";

        if (TxBx_UM != null)
            TxBx_UM.value = '0';
        if (TxBx_Journaling != null)
            TxBx_Journaling.value = '0';
        if (TxBx_AllowLHToCustomer != null)
            TxBx_AllowLHToCustomer.value = '0';
        if (TxBx_InPlaceHoldAllowed != null)
            TxBx_InPlaceHoldAllowed.value = '0';
        if (TxBx_EWSAllowed != null)
            TxBx_EWSAllowed.value = '0';
        if (TxBx_ArchiveMBs != null)
            TxBx_ArchiveMBs.value = '0';
        if (TxBx_OwAPublicFolder != null) {
            TxBx_OwAPublicFolder.value = "0";
        }
    }
    else if ((DDL_SPLAType.options[DDL_SPLAType.selectedIndex].value == "2") || (DDL_SPLAType.options[DDL_SPLAType.selectedIndex].value == "3") || (DDL_SPLAType.options[DDL_SPLAType.selectedIndex].value == "4") || (DDL_SPLAType.options[DDL_SPLAType.selectedIndex].value == "5")) {

        PopulateProductAddOn(TxtULMailbox, TxtRMailbox, TxtSMailbox, TxtOrg, TxtMAPI);
        PopulateProductAddOn(TxtULMailbox, TxtRMailbox, TxtSMailbox, TxtOrg, TxtOCAL);

        if (TxBx_UM != null)
            PopulateProductAddOn(TxtULMailbox, TxtRMailbox, TxtSMailbox, TxtOrg, TxtUM);
        if (TxBx_Journaling != null)
            PopulateProductAddOn(TxtULMailbox, TxtRMailbox, TxtSMailbox, TxtOrg, TxtJournaling);
        if (TxBx_AllowLHToCustomer != null)
            PopulateProductAddOn(TxtULMailbox, TxtRMailbox, TxtSMailbox, TxtOrg, TxtAllowLHToCustomer);
        if (TxBx_InPlaceHoldAllowed != null)
            PopulateProductAddOn(TxtULMailbox, TxtRMailbox, TxtSMailbox, TxtOrg, TxtInPlaceHoldAllowed);
        if (TxBx_EWSAllowed != null)
            PopulateProductAddOn(TxtULMailbox, TxtRMailbox, TxtSMailbox, TxtOrg, TxtEWSAllowed);
        if (TxBx_ArchiveMBs != null)
            PopulateProductAddOn(TxtULMailbox, TxtRMailbox, TxtSMailbox, TxtOrg, TxtArMB);

        PopulateProductAddOn(TxtULMailbox, TxtRMailbox, TxtSMailbox, TxtOrg, TxtAS);
        PopulateProductAddOn(TxtULMailbox, TxtRMailbox, TxtSMailbox, TxtOrg, TxtNCach);
        PopulateProductAddOn(TxtULMailbox, TxtRMailbox, TxtSMailbox, TxtOrg, TxtASA);
        if (TxBx_OwAPublicFolder != null) {
            PopulateProductAddOn(TxtULMailbox, TxtRMailbox, TxtSMailbox, TxtOrg, TxtOPF);
        }
        PopulateProductAddOn(TxtULMailbox, TxtRMailbox, TxtSMailbox, TxtOrg, TxtOWAUM);

        if (DDL_SPLAType.options[DDL_SPLAType.selectedIndex].value == "2") { //Standard
            TxBx_OutLookCAL.value = "0";

            if (TxBx_Journaling != null)
                TxBx_Journaling.value = '0';

            if (TxBx_AllowLHToCustomer != null)
                TxBx_AllowLHToCustomer.value = '0';

            if (TxBx_InPlaceHoldAllowed != null)
                TxBx_InPlaceHoldAllowed.value = '0';

            if (TxBx_ArchiveMBs != null)
                TxBx_ArchiveMBs.value = '0';
        }
        else if (DDL_SPLAType.options[DDL_SPLAType.selectedIndex].value == "3") { //Standard Plus
            if (TxBx_Journaling != null)
                TxBx_Journaling.value = '0';

            if (TxBx_AllowLHToCustomer != null)
                TxBx_AllowLHToCustomer.value = '0';

            if (TxBx_InPlaceHoldAllowed != null)
                TxBx_InPlaceHoldAllowed.value = '0';

            if (TxBx_ArchiveMBs != null)
                TxBx_ArchiveMBs.value = '0';
        }
        else if (DDL_SPLAType.options[DDL_SPLAType.selectedIndex].value == "4") { //Enterprise
            TxBx_OutLookCAL.value = '0';
        }
        else if (DDL_SPLAType.options[DDL_SPLAType.selectedIndex].value == "5") { //Enterprise Plus
            //All should be active
        }
    }
}
function ChangeSPLAExAddonTemplate(DDL, DDLEx, TBPerm, TBOWA, TBAr, TXTAMB, TXTAW, TXTAQ, TxtULMailbox, TxtRMailbox, TxtSMailbox, TxtOrg) {
    var DDL_SPLAType = document.getElementById(DDL);
    var DDL_ExAddOn = document.getElementById(DDLEx);
    var Tbl_Permissions = document.getElementById(TBPerm);
    var Tbl_OWA = document.getElementById(TBOWA);
    var Tbl_Archive = document.getElementById(TBAr);
    var TxBx_ArchiveMBs = document.getElementById(TXTAMB);
    var TxBx_ArchiveWarning = document.getElementById(TXTAW);
    var TxBx_ArchiveQuota = document.getElementById(TXTAQ);

    if ((DDL_ExAddOn.value == "1") || (DDL_ExAddOn.value == "3")) { //Custom & Additional MB
        //alert("EX IN");
        Tbl_Permissions.style.display = '';
        Tbl_OWA.style.display = '';
        Tbl_Archive.style.display = '';
        if (DDL_SPLAType.options[DDL_SPLAType.selectedIndex].value == "0") { //Custom
            Tbl_Permissions.style.display = '';
            Tbl_OWA.style.display = '';
            Tbl_Archive.style.display = '';
            //TxBx_ArchiveMBs.value = '';
            PopulateProductAddOn(TxtULMailbox, TxtRMailbox, TxtSMailbox, TxtOrg, TXTAMB);
            TxBx_ArchiveWarning.value = '';
            TxBx_ArchiveQuota.value = '';
            //alert("SPLA IN");
        }
        else if ((DDL_SPLAType.options[DDL_SPLAType.selectedIndex].value == "1") || (DDL_SPLAType.options[DDL_SPLAType.selectedIndex].value == "2") || (DDL_SPLAType.options[DDL_SPLAType.selectedIndex].value == "3") || (DDL_SPLAType.options[DDL_SPLAType.selectedIndex].value == "4") || (DDL_SPLAType.options[DDL_SPLAType.selectedIndex].value == "5")) {
            //alert("SPLA ELSE");
            Tbl_Permissions.style.display = 'none';
            Tbl_OWA.style.display = 'none';
            if ((DDL_SPLAType.options[DDL_SPLAType.selectedIndex].value == "4") || (DDL_SPLAType.options[DDL_SPLAType.selectedIndex].value == "5")) {
                Tbl_Archive.style.display = '';
                //TxBx_ArchiveMBs.value = '';
                PopulateProductAddOn(TxtULMailbox, TxtRMailbox, TxtSMailbox, TxtOrg, TXTAMB);
                TxBx_ArchiveWarning.value = '';
                TxBx_ArchiveQuota.value = '';
            }
            else {
                Tbl_Archive.style.display = 'none';
                TxBx_ArchiveMBs.value = '0';
                TxBx_ArchiveWarning.value = '1';
                TxBx_ArchiveQuota.value = '1';
            }
        }
    }
}

//No need to multiply orgs quota
function PopulateProductAddOn(TXT11, TXT12, TXT13, TXT2, TXTRES) {
    var TxBx_ULMBPerOrg = document.getElementById(TXT11);   // User/Linked Mailbox
    var TxBx_RMBPerOrg = document.getElementById(TXT12);    // Resource Mailbox
    var TxBx_SMBPerOrg = document.getElementById(TXT13);    // Shared Mailbox
    var TxBx_ExchOrgs = document.getElementById(TXT2);
    var TxBx_Res = document.getElementById(TXTRES);
    var ExchOrgs = TxBx_ExchOrgs.value;
    var ULMBPerOrg = TxBx_ULMBPerOrg.value;
    var RMBPerOrg = TxBx_RMBPerOrg.value;
    var SMBPerOrg = TxBx_SMBPerOrg.value;

    if ((TxBx_ExchOrgs.value == "") || (TxBx_ExchOrgs.value == "0"))
        ExchOrgs = 1;
    if (ULMBPerOrg == "" || ULMBPerOrg == "0")
        ULMBPerOrg = 0;
    if (RMBPerOrg == "" || RMBPerOrg == "0")
        RMBPerOrg = 0;
    if (SMBPerOrg == "" || SMBPerOrg == "0")
        SMBPerOrg = 0;
    if (TxBx_Res != null) {
        if (ULMBPerOrg == 0 && RMBPerOrg == 0 && SMBPerOrg == 0) {
            TxBx_Res.value = "0";
        }
        else if (ULMBPerOrg > 0 || RMBPerOrg > 0 || SMBPerOrg > 0) {
            TxBx_Res.value = ExchOrgs * (parseInt(ULMBPerOrg) + parseInt(RMBPerOrg) + parseInt(SMBPerOrg));
            //TxBx_Res.value = (parseInt(ULMBPerOrg) + parseInt(RMBPerOrg) + parseInt(SMBPerOrg));
        }
        //else if (TxBx_MBPerOrg.value > "0" && TxBx_ExchOrgs.value > "0") {
        //    TxBx_Res.value = TxBx_MBPerOrg.value * TxBx_ExchOrgs.value;
        //}
        else {
            TxBx_Res.value = '';
        }
    }
}

function SPLATypeChangedAddOn(DDL, TXT) {
    var DDL_SPLAType = document.getElementById(DDL);
    var TxBx = document.getElementById(TXT);
    //alert("IN");
    if ((DDL_SPLAType.options[DDL_SPLAType.selectedIndex].value == "1") || (DDL_SPLAType.options[DDL_SPLAType.selectedIndex].value == "2") || (DDL_SPLAType.options[DDL_SPLAType.selectedIndex].value == "3") || (DDL_SPLAType.options[DDL_SPLAType.selectedIndex].value == "4") || (DDL_SPLAType.options[DDL_SPLAType.selectedIndex].value == "5")) {
        //if ((TxBx.disabled == false) && (ChBx.checked == false) && (TxBx.value > 0))
        setTimeout(function () { DDL_SPLAType.selectedIndex = 0; $(DDL_SPLAType).trigger('change'); }, 500);
        //        if (ChBx.checked == true)
        //            DDL_SPLAType.options[0].selected = true;
        //        else if (ChBx.checked == false)
        //            DDL_SPLAType.options[0].selected = true;
    }
}

function ExchOrgAndMailbox(TXTEORG, TXTULMB, TXTRMB, TXTSMB, Msg) {
    var TxBx_ExchOrgs = document.getElementById(TXTEORG);
    var TxBx_ULMBPerOrg = document.getElementById(TXTULMB);
    var TxBx_RMBPerOrg = document.getElementById(TXTRMB);
    var TxBx_SMBPerOrg = document.getElementById(TXTSMB);
    if (TxBx_ULMBPerOrg.value == "0" && TxBx_RMBPerOrg.value == "0" && TxBx_SMBPerOrg.value == "0" && TxBx_ExchOrgs.value > "0") {
        alert(Msg);
        TxBx_ExchOrgs.focus();
        return false;
    }
}

function ChangeSPLATypeMailBox(DDL, CBMAPI, CBOutlook) {
    var DDL_SPLAType = document.getElementById(DDL);
    var CB_MAPIAcessAlwd = document.getElementById(CBMAPI);
    var CB_OutlookLicense = document.getElementById(CBOutlook);


    if (DDL_SPLAType.options[DDL_SPLAType.selectedIndex].value == "1") {
        CB_MAPIAcessAlwd.checked = false;
        CB_OutlookLicense.checked = false;
    }
    else if ((DDL_SPLAType.options[DDL_SPLAType.selectedIndex].value == "2") || (DDL_SPLAType.options[DDL_SPLAType.selectedIndex].value == "3")) {

        CB_MAPIAcessAlwd.checked = true;

        if (DDL_SPLAType.options[DDL_SPLAType.selectedIndex].value == "3") {
            CB_OutlookLicense.checked = true;
        }
        else {
            CB_OutlookLicense.checked = false;
        }
    }
}


function expand(source, e) {

    var parentCtrl = $(source).parents('table').get(0);
    $('div.collapsiblecontainer').hide('50');
    $('input.hfclass').val('collapsed');
    $('.lbexpand').show();
    $('.lbcollapse').hide();
    var dv = $('div.collapsiblecontainer', parentCtrl).get(0);
    if (dv.style.display != 'none') {

        $(dv).fadeOut(100);
        $(dv).hide('50');
        $('.lbexpand', parentCtrl).show();
        $('.lbcollapse', parentCtrl).hide();
        //find hidden field and set status
        $('input.hfclass', dv).val('collapsed');
    }
    else {

        $(dv).show('50');
        $(dv).fadeIn(100);
        $('.lbexpand', parentCtrl).hide();
        $('.lbcollapse', parentCtrl).show();
        //find hidden field and set status
        $('input.hfclass', dv).val('expanded');
    }
    if (e)
        e.preventDefault();

    return false;
}

function expand2(source, e) {

    var parentCtrl = $(source).parents('table').get(0);
    $('div.collapsiblecontainer2').hide('50');
    $('input.hfclass2').val('collapsed');
    $('.lbexpand2').show();
    $('.lbcollapse2').hide();
    var dv = $('div.collapsiblecontainer2', parentCtrl).get(0);

    if (dv.style.display != 'none') {
        $(dv).fadeOut(100);
        $(dv).hide('50');
        $('.lbexpand2', parentCtrl).show();
        $('.lbcollapse2', parentCtrl).hide();
        //find hidden field and set status
        $('input.hfclass2', dv).val('collapsed');
    }
    else {
        $(dv).show('50');
        $(dv).fadeIn(100);
        $('.lbexpand2', parentCtrl).hide();
        $('.lbcollapse2', parentCtrl).show();
        //find hidden field and set status
        $('input.hfclass2', dv).val('expanded');
    }
    e.preventDefault();
    return false;
}

function SetDisclaimerText(Id) {
    var Ctrl = document.getElementById(Id);
    var val = Ctrl.value;
    val = val.replace(new RegExp("<", "g"), "&lt;");
    val = val.replace(new RegExp(">", "g"), "&gt;");

    Ctrl.value = val;
}
function SetOOOText(Internal, External) {
    var Ctrl = document.getElementById(External);

    if (Ctrl != null) {

        var val = Ctrl.value;
        val = val.replace(new RegExp("<", "g"), "&lt;");
        val = val.replace(new RegExp(">", "g"), "&gt;");

        Ctrl.value = val;

        var Ctrl2 = document.getElementById(Internal);
        var val2 = Ctrl2.value;
        val2 = val2.replace(new RegExp("<", "g"), "&lt;");
        val2 = val2.replace(new RegExp(">", "g"), "&gt;");

        Ctrl2.value = val2;
    }
}

function ValidNumericOrBlank(Id) {
    var Ctrl = document.getElementById(Id);
    var Val = Ctrl.value;
    if (!Ctrl.value.length == 0) {
        if (isNaN(Val)) {
            Ctrl.value = '';
        }
        else {
            Ctrl.value = Ctrl.value * 1;
            if (Ctrl.value.indexOf(".") >= 0) {
                Ctrl.value = Ctrl.value.substring(0, Ctrl.value.indexOf("."));
            }
            if (Ctrl.value < 0) {
                Ctrl.value = '';
            }
        }
    }
}

function verifyIP(Id) {

    var Ctrl = document.getElementById(Id);
    var Val = Ctrl.value;

    if (!Ctrl.value.length == 0) {

        var ipPattern = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
        var ipArray = Val.match(ipPattern);

        if (Val == "0.0.0.0")
            Ctrl.value = '';
        else if (Val == "255.255.255.255")
            Ctrl.value = '';

        if (ipArray == null)

            Ctrl.value = '';


        else {
            for (i = 0; i < 4; i++) {
                var thisSegment = ipArray[i];
                if (thisSegment > 255) {
                    Ctrl.value = '';
                    i = 4;
                }

                if ((i == 0) && (thisSegment > 255)) {
                    Ctrl.value = '';
                    i = 4;
                }

            }
        }
    }
}
function verifyIPList(Id) {

    var Ctrl = document.getElementById(Id);
    var Val = Ctrl.value;
    var valArray = val.split(',');

    for (var i = 0; i < valArray.length; i++) {
        if (!valArray[i].length == 0) {
            var ipPattern = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
            var ipArray = valArray[i].match(ipPattern);

            if (valArray[i] == "0.0.0.0")
                Ctrl.value = '';
            else if (valArray[i] == "255.255.255.255")
                Ctrl.value = '';
            if (ipArray == null)
                Ctrl.value = '';
            else {
                for (i = 0; i < 4; i++) {
                    var thisSegment = ipArray[i];
                    if (thisSegment > 255) {
                        Ctrl.value = '';
                        i = 4;
                    }

                    if ((i == 0) && (thisSegment > 255)) {
                        Ctrl.value = '';
                        i = 4;
                    }
                }
            }
        }
    }
}

function UpdateLabel(Lblid, Domid) {

    var TxBx_DomainName = document.getElementById(Domid);
    var Lbl_Domain = document.getElementById(Lblid);

    Lbl_Domain.innerHTML = '@' + TxBx_DomainName.value;
}

function myParseFloat(No, S, gS) {

    if (No.substring(No.indexOf('&nbsp;')) >= 0) {
        No = No.substring(No.indexOf('&nbsp;'));
    }

    No = No.replace('&nbsp;', '');
    No = No.replace(gS, '');

    if (gS == ' ') {

        var pieces = No.match(/\d+/g);
        var NewNo = new String('');
        for (i = 0; i < pieces.length; i++) {
            NewNo = NewNo + pieces[i];
        }
        var SepIndex = No.indexOf(S);
        if (S != -1) {
            SepIndex = No.length - SepIndex;
            NewNo = NewNo.substring(0, NewNo.length - SepIndex + 1) + S + NewNo.substring(NewNo.length - SepIndex + 1);
            No = NewNo;
        }

    }

    No = No.replace(S, '.');
    No = parseFloat(No);
    return No;
}

function ChangeCurrency(DDL, Amount, S, gS, fMt, Min) {

    var DDL_Currency = document.getElementById(DDL);
    var TxBx_MinAmount = document.getElementById(Amount);
    TxBx_MinAmount.value = DDL_Currency.options[DDL_Currency.selectedIndex].value.split("|")[1] + ' ' + Min;
    FormatPrice(Amount, DDL_Currency.options[DDL_Currency.selectedIndex].value.split("|")[1] + ' ', S, gS, fMt);

}
function GenerateInvoicePriceChange(DDL, PriceTxBx, QuantityTxBx, S, gS, fMt) {

    var DDL_Cycle = document.getElementById(DDL);
    var TxBx_Price = document.getElementById(PriceTxBx);
    var TxBx_Quantity = document.getElementById(QuantityTxBx);
    var Price = myParseFloat(DDL_Cycle.options[DDL_Cycle.selectedIndex].value.split("|")[1], S, gS);
    if (DDL_Cycle.options[DDL_Cycle.selectedIndex].value.split("|")[0] == '18') {
        TxBx_Quantity.value = "1";
    }
    if (parseInt(TxBx_Quantity.value) == 0) {
        TxBx_Quantity.value = "1";
    }
    Price = Price * TxBx_Quantity.value;
    TxBx_Price.value = DDL_Cycle.options[DDL_Cycle.selectedIndex].value.split("|")[2];
    TxBx_Price.value = FormatLblPrice(NumberRounding(Price, 2), DDL_Cycle.options[DDL_Cycle.selectedIndex].value.split("|")[2] + ' ', S, gS, fMt);
}

function SelectText(Tx, DDL) {
    var DDL_Control = document.getElementById(DDL);
    var Tx_Control = document.getElementById(Tx);
    Tx_Control.value = DDL_Control.options[DDL_Control.selectedIndex].value;
}
function findControl(parent, tagName, serverId) {
    var items = parent.getElementsByTagName(tagName);
    for (var i = 0; i < items.length; i++) {
        var ctl = items[i];
        if (ctl && ctl.id) {
            var subId = ctl.id.substring(ctl.id.length - serverId.length);
            if (subId == serverId) {
                return ctl;
            }
        }
    }
    return null;
}
function CB_Checked_VisisbleTextBox(CB_Id, Tr_Id, RFV_Id) {

    var Tr = document.getElementById(Tr_Id);
    var CB = document.getElementById(CB_Id);
    var RFV = document.getElementById(RFV_Id);

    if (CB.checked == true) {

        Tr.style.display = '';

        ValidatorEnable(RFV, true);

    }
    else {

        Tr.style.display = 'none';
        ValidatorEnable(RFV, false);
    }
}

function CB_Checked_ValidatorToggle(CB_Id, RFV_Id) {

    var CB = document.getElementById(CB_Id);
    var RFV = document.getElementById(RFV_Id);

    if (CB.checked == true) {
        ValidatorEnable(RFV, true);
    }
    else {
        ValidatorEnable(RFV, false);
    }
}
function CB_Checked_ValidatorToggleBetween2(CB_Id, RFV_IdToEnable, RFV_IdToDisable) {

    var CB = document.getElementById(CB_Id);
    var RFV = document.getElementById(RFV_IdToEnable);
    var RFV2 = document.getElementById(RFV_IdToDisable);

    if (CB.checked == true) {
        ValidatorEnable(RFV, true);
        ValidatorEnable(RFV2, false);
    }
    else {
        ValidatorEnable(RFV, false);
        ValidatorEnable(RFV2, true);
    }
}
function CB_Checked_TextBoxValidatorToggle(CB_Id, TxBx_Id, RFV_Id) {

    var TxBx = document.getElementById(TxBx_Id);
    var CB = document.getElementById(CB_Id);
    var RFV = document.getElementById(RFV_Id);

    if (CB.checked == true) {
        ValidatorEnable(RFV, false);
        TxBx.disabled = true;
        $(TxBx).addClass('disabled');
        TxBx.value = ''
    }
    else {
        ValidatorEnable(RFV, true);
        TxBx.disabled = false;
        $(TxBx).removeClass('disabled');
    }
}
function CB_Checked_TextBoxValidatorToggle(CB_Id, TxBx_Id, RFV_Id, defaultValue) {

    var TxBx = document.getElementById(TxBx_Id);
    var CB = document.getElementById(CB_Id);
    var RFV = document.getElementById(RFV_Id);

    if (CB.checked == true) {
        TxBx.disabled = true;
        $(TxBx).addClass('disabled');
        TxBx.value = defaultValue
        ValidatorEnable(RFV, false);
    }
    else {
        TxBx.disabled = false;
        $(TxBx).removeClass('disabled');
        TxBx.value = ''
        ValidatorEnable(RFV, true);
    }
}
function loadTabPanel(sender, e) {

    var tabContainer = sender;

    if (tabContainer) {

        var updateControlId = "Btn_Tab" + tabContainer.get_activeTabIndex();
        var activeTab = tabContainer.get_activeTab();

        if (findControl(activeTab.get_element(), "div", "Pnl_TabContent" + tabContainer.get_activeTabIndex())) {
            if ($("#" + tabContainer._element.id).prev().attr('class') == 'RefreshTab');
            {
                $("#" + tabContainer._element.id).prev().click();
                //$( ".RefreshTab" )[0].click();           
            }
        }
        else {
            var updateControl = findControl(activeTab.get_element(), "input", updateControlId);

            if (updateControl) {
                var HF_Ajax = document.getElementById('HF_Ajax');
                if (HF_Ajax) {
                    HF_Ajax.value = tabContainer.get_activeTabIndex();
                }

                updateControl.click();
            }
        }
    }

}
function ConfirmAction(Message) {
    if (confirm(Message)) {
        return true;
    }
    else {
        return false;
    }
}
function ConfirmAndPostBack(Message, PostBackControl, HF, Argument) {
    if (ConfirmAction(Message) == true) {
        document.getElementById(HF).value = Argument;
        __doPostBack(PostBackControl, '');
        return false;
    }
    else {
        return false;
    }
}
function ShowHide(WhichLayer) {

    if (document.getElementById) {

        // this is the way the standards work
        var style2 = document.getElementById(WhichLayer).style;
        if (style2.display == '') {
            style2.display = "none";
        }
        else {
            style2.display = '';
        }

    }
    else if (document.all) {

        // this is the way old msie versions work
        var style2 = document.all[WhichLayer].style;
        style2.display = "none";
        if (style2.display == '') {
            style2.display = "none";
        }
        else {
            style2.display = '';
        }
    }
    else if (document.layers) {

        // this is the way nn4 works
        var style2 = document.layers[WhichLayer].style;
        style2.display = "none";
        if (style2.display == '') {
            style2.display = "none";
        }
        else {

            style2.display = '';
        }
    }
}

function ShowElement(WhichLayer) {
    if (document.getElementById) {
        // this is the way the standards work
        var style2 = document.getElementById(WhichLayer).style;
        style2.display = '';
    }
    else if (document.all) {
        // this is the way old msie versions work
        var style2 = document.all[WhichLayer].style;
        style2.display = '';
    }
    else if (document.layers) {
        // this is the way nn4 works
        var style2 = document.layers[WhichLayer].style;
        style2.display = '';
    }
}

function HideElement(WhichLayer) {
    if (document.getElementById) {
        // this is the way the standards work
        var style2 = document.getElementById(WhichLayer).style;
        style2.display = "none";
    }
    else if (document.all) {
        // this is the way old msie versions work
        var style2 = document.all[WhichLayer].style;
        style2.display = "none";
    }
    else if (document.layers) {
        // this is the way nn4 works
        var style2 = document.layers[WhichLayer].style;
        style2.display = "none";
    }
}

function SetChecked(val, chkName) {
    var dml = document.forms[0];
    var len = dml.elements.length;
    var i = 0;
    for (i = 0; i < len; i++) {
        if (dml.elements[i].name != chkName && dml.elements[i].type == "checkbox") {
            if (dml.elements[i].disabled == false) {
                dml.elements[i].checked = val;
            }
        }
    }
}

function SetCheckSingle(val, chkName) {

    var CheckAll = document.getElementById(chkName);
    var dml = document.forms[0];
    var len = dml.elements.length;

    if (val == true) {
        CheckAll.checked = true;
    }
    else {
        CheckAll.checked = false;
    }

    if (CheckAll.checked == true) {
        var i = 0;
        for (i = 0; i < len; i++) {
            if (dml.elements[i].checked != true && dml.elements[i].type == "checkbox") {
                CheckAll.checked = false;
            }
        }
    }
}

function SetCheckedaddon(val, chkName, CBit) {
    if (CBit != '1') {
        var dml = document.forms[0];
        var len = dml.elements.length;
        var i = 0;
        for (i = 0; i < len; i++) {
            if (dml.elements[i].name != chkName && dml.elements[i].type == "checkbox") {
                if (dml.elements[i].name.indexOf('ChkBx') != '-1') {
                    if (dml.elements[i].disabled == false) {
                        dml.elements[i].checked = val;
                    }
                }
            }
        }
    }
}

function SetChecked2(val, chkName, parentid) {

    var dml = document.forms[0];
    var len = dml.elements.length;
    var i = 0;
    for (i = 0; i < len; i++) {
        if (dml.elements[i].name != chkName && dml.elements[i].type == "checkbox" && dml.elements[i].value == parentid) {
            if (dml.elements[i].disabled == false) {
                dml.elements[i].checked = val;
            }
        }
    }
}

function CheckedCount(chkName, Message) {
    var dml = document.forms[0];
    var len = dml.elements.length;
    var checkedcount = 0;
    var i = 0;
    for (i = 0; i < len; i++) {
        if (dml.elements[i].name != chkName && dml.elements[i].type == "checkbox") {
            if (dml.elements[i].checked == true) {
                checkedcount = 1;
            }
        }
    }
    if (checkedcount == 0) {
        alert(Message);
        return false;
    }
    else {
        return true;
    }
}
function CB_CheckedPopulateOne(CB_Id, TxBx_Id) {
    var TxBx = document.getElementById(TxBx_Id);
    var CB = document.getElementById(CB_Id);
    if (CB.checked == true) {
        //alert(CB);
        TxBx.disabled = true;
        $(TxBx).addClass('disabled');
        TxBx.value = '';
    }
    else {
        TxBx.disabled = false;
        $(TxBx).removeClass('disabled');
        TxBx.value = '1';
    }
}


function ValidDiscount(Id) {
    var Ctrl = document.getElementById(Id);
    if (Ctrl) {
        //Ctrl.value = Ctrl.value.replace(".", "");
        var Val = Ctrl.value.split('%');
        var number = parseFloat(parseLocalizedNumberString(Val[0]));
        if (!number) {
            Ctrl.value = '0%';
        }
        else if (number < 0) {
            Ctrl.value = '0%';
        }
        else if (number > 100) {
            Ctrl.value = '100%';
        }
        else {
            Ctrl.value = number.toFixed(2).toString().replace(".", UIDecimalSeparator) + '%';
        }
    }
}

function ValidSfBCallsCommission(Id) {
    var Ctrl = document.getElementById(Id);
    if (Ctrl) {
        var Val = Ctrl.value.split('%');

        var number = parseFloat(Val[0]);
        if (!number) {
            Ctrl.value = '0%';
        }
        else if (number < 0) {
            Ctrl.value = '0%';
        }
        else if (number > 100) {
            Ctrl.value = '100%';
        }
        else {
            Ctrl.value = NumberRounding(number, '3') + '%';
        }
    }
}
function ValidCpuUsage(Id) {
    var Ctrl = document.getElementById(Id);

    var Val = Ctrl.value.split('%');

    var number = parseFloat(Val[0]);
    if (!number) {
        Ctrl.value = '0';
    }
    else if (number < 0) {
        Ctrl.value = '0';
    }
    else if (number > 100) {
        Ctrl.value = '100';
    }
    else {
        Ctrl.value = NumberRounding(number, '2');
    }
}
//
function ValidNumeric(Id) {
    var Ctrl = document.getElementById(Id)
    var Val = Ctrl.value;
    if (!Ctrl.value.length == 0) {
        if (isNaN(Val)) {
            Ctrl.value = '0'
        }
        else {
            Ctrl.value = Ctrl.value * 1
            if (Ctrl.value.indexOf(".") >= 0) {
                Ctrl.value = Ctrl.value.substring(0, Ctrl.value.indexOf("."))
            }
            if (Ctrl.value < 0) {
                //Ctrl.value = parseInt ((Ctrl.value*(-1)));	
                Ctrl.value = '0'
            }
            if (Ctrl.value > 2147483647) {
                Ctrl.value = '2147483647'
            }
        }
    }
    else {
        Ctrl.value = '0'
    }
}
function ValidNumericPopulateOne(Id) {
    var Ctrl = document.getElementById(Id)
    var Val = Ctrl.value;
    if (!Ctrl.value.length == 0) {
        if (isNaN(Val)) {
            Ctrl.value = '0'
        }
        else {
            Ctrl.value = Ctrl.value * 1
            if (Ctrl.value.indexOf(".") >= 0) {
                Ctrl.value = Ctrl.value.substring(0, Ctrl.value.indexOf("."))
            }
            if (Ctrl.value < 0) {
                //Ctrl.value = parseInt ((Ctrl.value*(-1)));	
                Ctrl.value = '0'
            }
            if (Ctrl.value > 2147483647) {
                Ctrl.value = '2147483647'
            }
        }
    }

    if (Ctrl.value == '' || (Ctrl.value == '0')) {
        Ctrl.value = '1';
    }
}
function ValidNumericPopulateMinValue(Id, minVal) {
    var Ctrl = document.getElementById(Id)
    var Val = Ctrl.value;
    if (!Ctrl.value.length == 0) {
        if (isNaN(Val)) {
            Ctrl.value = minVal;
        }
        else {
            //Ctrl.value = Ctrl.value * 1
            if (Ctrl.value.indexOf(".") >= 0) {
                Ctrl.value = Ctrl.value.substring(0, Ctrl.value.indexOf("."))
            }
            if (Ctrl.value <= 0) {
                //Ctrl.value = parseInt ((Ctrl.value*(-1)));	
                Ctrl.value = minVal;
            }
            if (Ctrl.value > 2147483647) {
                Ctrl.value = '2147483647'
            }
        }
    }

    if (Ctrl.value == '' || (Ctrl.value == '0')) {
        Ctrl.value = '1';
    }
}
function ValidNumber(Id) {
    var Ctrl = document.getElementById(Id)
    var Val = Ctrl.value;
    if (!Ctrl.value.length == 0) {
        if (isNaN(Val)) {
            Ctrl.value = '0'
        }
        else {
            Ctrl.value = Ctrl.value * 1
            if (Ctrl.value.indexOf(".") >= 0) {
                Ctrl.value = Ctrl.value.substring(0, Ctrl.value.indexOf("."))
            }
            if (Ctrl.value <= 0) {
                //Ctrl.value = parseInt ((Ctrl.value*(-1)));	
                Ctrl.value = '0'
            }
            if (Ctrl.value > 2097151) {
                Ctrl.value = '2097151'
            }
        }
    }
}
function ValidCurrMaxLoad(Id) {

    var Ctrl;

    if (Id.value != null) {
        Ctrl = Id;//This Reference
    }
    else {
        Ctrl = document.getElementById(Id);
    }

    var Val = Ctrl.value;
    if (!Ctrl.value.length == 0) {
        if (isNaN(Val)) {
            Ctrl.value = ''
            alert("Please enter integer value.")
        }
        else {
            Ctrl.value = Ctrl.value * 1
            if (Ctrl.value.indexOf(".") > 0) {
                Ctrl.value = ''
                alert("Please enter integer value.")
            }
            if (Ctrl.value <= 0) {
                //Ctrl.value = parseInt ((Ctrl.value*(-1)));	
                Ctrl.value = '0'
            }
            if (Ctrl.value > 2147483647) {
                Ctrl.value = '2147483647'
            }
        }
    }

}

var UIDecimalSeparator = '.';
function applyResellerMarginOnPrice(marginInputId) {
    $('.js-input-cost').each(function () {
        copyCostToPriceAndApplyMarginIfAny($(this).attr('id'), marginInputId, $(this).parent('.form-line').parent('.form-group').parent().next().find('.js-input-price').attr('id'));
    });
}

function copyCostToPriceAndApplyMarginIfAny(costInputId, marginInputId, priceInputId) {
    var marginInPercent = 0.0;

    if (marginInputId && document.getElementById(marginInputId))
        marginInPercent = parseFloat(parseLocalizedNumberString($('#' + marginInputId).val().replace('%', '')));



    var $input_cost = $('#' + costInputId);
    var $input_price = $('#' + priceInputId);
    var cost = $input_cost.val();

    if (isNaN(cost)) { //remove 3 char currency symbol if present
        try {
            cost = cost.substr(3, cost.length - 3);
        }
        catch (e) { console.error(e); }
    }
    if (!isNaN(cost) || !isNaN(parseFloat(cost))) {
        cost = Number(parseLocalizedNumberString(cost));
        var price = cost + (cost / 100 * marginInPercent);

        $input_price.val(price.toString().replace('.', UIDecimalSeparator));
        $input_price.trigger('blur');
    }
}

function parseLocalizedNumberString(numberAsString) {
    numberAsString = numberAsString.trim();
    if (numberAsString.match(/\d+(\,\d+)+\.\d+/)) ///10,000,000.00
    {
        UIDecimalSeparator = '.';
        numberAsString = numberAsString.replaceAll(',', '');
    }
    else if (numberAsString.match(/\d+(\.\d+)+\,\d+/)) ///10.000.000,00
    {
        UIDecimalSeparator = ',';
        numberAsString = numberAsString.replaceAll('.', '').replaceAll(',', '.');
    }
    else if (numberAsString.match(/\d+(\s\d+)+\.\d+/)) ///10 000 000.00
    {
        UIDecimalSeparator = '.';
        numberAsString = numberAsString.replaceAll(' ', '');
    }
    else if (numberAsString.match(/\d+(\.\d+)+\s\d+/)) ///10.000.000 00
    {
        UIDecimalSeparator = ' ';
        numberAsString = numberAsString.replaceAll('.', '').replaceAll(' ', '.');
    }
    else if (numberAsString.match(/\d+(\s\d+)+\,\d+/)) ///10 000 000,00
    {
        UIDecimalSeparator = ',';
        numberAsString = numberAsString.replaceAll(' ', '').replaceAll(',', '.');
    }
    else if (numberAsString.match(/\d+(\,\d+)+\s\d+/)) ///10,000,000 00
    {
        UIDecimalSeparator = ' ';
        numberAsString = numberAsString.replaceAll(',', '').replaceAll(' ', '.');
    }
    else if (numberAsString.match(/\d+(\'\d+)+\.\d+/)) ///10'000'000.00
    {
        UIDecimalSeparator = '.';
        numberAsString = numberAsString.replaceAll('\'', '');
    }
    else if (numberAsString.match(/\d+\,\d+/)) ///10,00
    {
        UIDecimalSeparator = ',';
        numberAsString = numberAsString.replaceAll(',', '.');
    }
    else if (numberAsString.match(/\d+\s\d+/)) ///10 00
    {
        UIDecimalSeparator = ' ';
        numberAsString = numberAsString.replaceAll(' ', '.');
    }
    else if (numberAsString.match(/\d+\.\d+/)) ///10.00
    {
        UIDecimalSeparator = '.';
        numberAsString = numberAsString;
    }
    else
        numberAsString = numberAsString;

    if (UIDecimalSeparator != currentCultureNumberDecimalSeparator)
        UIDecimalSeparator = currentCultureNumberDecimalSeparator;

    return numberAsString;
}

function ValidTax(Id) {
    var Ctrl = document.getElementById(Id);

    var number = parseFloat(Ctrl.value);
    if (!number) {
        Ctrl.value = '0';
    }
    else if (number < 0) {
        Ctrl.value = '0';
    }
    else {
        Ctrl.value = NumberRounding(number, '2');
    }
}

function FormatPrice(Id, Symbol, S, gS, fMt) {
    var Ctrl = document.getElementById(Id);
    if (Ctrl) {
        Ctrl.value = PriceCheck(Ctrl.value, Symbol, S, gS, fMt);
    }
}

function FormatTaxRate(Id, Symbol, S, gS, fMt) {
    var Ctrl = document.getElementById(Id);
    //Ctrl.value = 'USD ' + Ctrl.value;
    //alert(Ctrl.value);
    Ctrl.value = PriceCheck(Ctrl.value, Symbol, S, gS, fMt);
    //alert("2: " + Ctrl.value);
    Ctrl.value = Ctrl.value.replace('USD ', '');

}

function FormatLblPrice(Value, Symbol, S, gS, fMt) {
    return PriceCheck(Value, Symbol, S, gS, fMt);
}

function FormatPriceSymbolinDDL(Id, SymbolId, S, gS, fMt) {
    var Ctrl = document.getElementById(Id);
    var DDL = document.getElementById(SymbolId);
    Ctrl.value = PriceCheck(Ctrl.value, DDL.options[DDL.selectedIndex].value.split("|")[1] + ' ', S, gS, fMt);
}

function PriceCheck(number, PriceSymbol, S, gS, fMt) {

    number = number.toString();              // set the number as a string

    number = number.replace(gS, '');

    var formatstring = PriceSymbol + fMt + ";" + PriceSymbol + fMt;

    var neg = (number.indexOf("-") == -1) ? 0 : 1; // index of the format string to use, 1 = second one, which is the negative number format string
    var fmtStrs = formatstring.split(";");   // array of format strings	
    formatstring = fmtStrs[neg];             // choose the negative or positive format string and filter it for special characters

    if (formatstring == "") {
        formatstring = fmtStrs[0];
    }
    while (formatstring.indexOf("0") != -1) {
        formatstring = formatstring.replace("0", "#");
    }
    stringparts = formatstring.split("#");
    numfirst = stringparts[0];
    numlast = stringparts[stringparts.length - 1];
    firstpos = numfirst.length;
    lastpos = formatstring.length;
    if (numlast != "") {
        lastpos = formatstring.indexOf(numlast);
    }
    if (lastpos == firstpos) {
        lastpos = formatstring.length - 1;
    }
    var innerformatstring = formatstring.substring(firstpos, lastpos);
    innerformatstring = innerformatstring.split(S);
    var decimals = (innerformatstring[1]) ? innerformatstring[1].length : 0;
    innerformatstring[0] = innerformatstring[0].split(gS);
    var commadigits = innerformatstring[0][innerformatstring[0].length - 1].length;
    number = number.replace(gS, "X");
    number = number.replace(S, ".");
    number = number.replace("X", ",");
    number = StringFilteration(number, "1234567890.");    /*------------------------*/
    number = parseFloat(number);
    number = NumberRounding(number, decimals);     /*-----------------------------*/
    number = number.toString();
    number = number.split(".");
    if (!number[1]) {
        number[1] = "";
    }
    while (number[1].length < decimals) {
        number[1] = number[1] + "" + "0";
    }
    numdefault = 1 / Math.pow(10, decimals + 1);
    if ((decimals + 1) >= 7)
        numdefault = numdefault.toFixed(decimals + 1);

    numdefault = numdefault.toString().split(".");
    numdefault = numdefault[1].substring(0, decimals);
    if (!numdefault) {
        numdefault = "";
    }
    while (numdefault.length < decimals) {
        numdefault = numdefault + "0";
    }
    if ((numfirst == numlast) && (PriceSymbol != '')) {
        numlast = 0;
    }
    if (parseInt(number[0]) > 0) {

        var numberparts = SplitInPackets(number[0], commadigits, fMt); /* ---------*/

        var endnumber = numfirst + '' + numberparts[0];

        for (i = 1; i < numberparts.length; i++) {
            endnumber = endnumber + gS + numberparts[i];
        }
    }
    else {
        var endnumber = numfirst + '0';
    }
    if (number[1] != "") {
        endnumber = endnumber + '' + S + number[1] + '' + numlast;
    }
    else {
        endnumber = endnumber + '' + S + numdefault + '' + numlast;
    }
    return endnumber;
}

function StringFilteration(str, allowchars) {
    var ret = '';
    for (var i = 0; i < str.length; i++) {
        if (allowchars.indexOf(str.charAt(i)) != -1) {
            ret = ret + '' + str.charAt(i);
        }
    }
    return ret;
}
function NumberRounding(number, decimals) {
    number = parseFloat(number); // get float
    number = number * Math.pow(10, decimals); // multiply times 10 to the power of "decimals"
    number = Math.round(number); // round to whole number
    number = number / Math.pow(10, decimals); // divide by 10 to the power of "decimals"
    return number.toFixed(decimals); // return number
}
function RoundTo2(number) {
    return (number % 1 === 0 ? number : NumberRounding(number, 2));
    //return NumberRounding(number, 2);
}
function SplitInPackets(str, size, fMt) {
    var str2 = str;
    if (fMt == '0,00,000.00') {
        if (str.length > 3) {
            str = str.substring(0, str.length - 3);
            str2 = str2.substring(str2.length - 3, str2.length)
            size = 2;
        }
    }

    var assume = (str.length % size);
    if (assume > 0) assume = size - assume;

    var retarray = new Array();
    for (i = 0; i < str.length / size; i++) {
        retarray[i] = '';
        for (x = 0; x < size; x++) {
            if ((i * size) + x - assume < str.length && (i * size) + x - assume > -1) {
                retarray[i] = retarray[i] + '' + str.charAt((i * size) + x - assume);
            }
        }
    }
    if (fMt == '0,00,000.00')
        retarray[i] = str2;

    return retarray;
}

function CopyValues(TriggerId, TargetId) {
    //alert(TriggerId +' '+ TargetId);
    var TriggerTxt = document.getElementById(TriggerId);
    var TargetTxt = document.getElementById(TargetId);
    if (TriggerTxt != null && TargetTxt != null && TriggerTxt.value != '') {
        TargetTxt.value = TriggerTxt.value;

        try {
            //********** if both target and trigger are DDL then set values accordingly *************
            setTimeout(function () { TargetTxt.selectedIndex = TriggerTxt.selectedIndex; $(TargetTxt).trigger('change'); }, 500);
        }
        catch (ex) { }
    }
    return true
}

function CopyValuesIfTragetEmpty(TriggerId, TargetId) {
    //alert(TriggerId +' '+ TargetId);
    var TriggerTxt = document.getElementById(TriggerId);
    var TargetTxt = document.getElementById(TargetId);
    // && TargetTxt != null && TargetTxt.value == ''
    if (TriggerTxt != null && TargetTxt != null) {
        TargetTxt.value = TriggerTxt.value;

        try {
            //********** if both target and trigger are DDL then set values accordingly *************
            setTimeout(function () { TargetTxt.selectedIndex = TriggerTxt.selectedIndex; $(TargetTxt).trigger('change'); }, 500);
        }
        catch (ex) { }
    }
    return true
}

function CopyValues2(TriggerId, Target1Id, Target2Id, Target3Id) {
    //alert('ParentId: ' +TriggerId +'TargetIId: '+ Target1Id + ' Target2Id: ' + Target2Id + 'Target3Id:  '+ Target3Id);
    var TriggerTxt = document.getElementById(TriggerId);
    var Target1Txt = document.getElementById(Target1Id);
    var Target2Txt = document.getElementById(Target2Id);
    var Target3Txt = document.getElementById(Target3Id);
    if (TriggerTxt != null && Target1Txt != null && Target2Txt != null && Target3Txt != null) {
        Target1Txt.value = TriggerTxt.value;
        Target2Txt.value = TriggerTxt.value;
        Target3Txt.value = TriggerTxt.value;
    }
}
function CopyValues3(IdCollection) {
    //alert(IdCollection);
    var IdArray = IdCollection.split('::');
    var TriggerTxt = document.getElementById(IdArray[0]);
    var Trigger1Txt = document.getElementById(IdArray[1]);
    var Target1Txt = document.getElementById(IdArray[2]);
    var Target2Txt = document.getElementById(IdArray[3]);
    var Target3Txt = document.getElementById(IdArray[4]);
    var Target4Txt = document.getElementById(IdArray[5]);

    if (!TriggerTxt && !TriggerTxt.value && TriggerTxt.value != undefined && TriggerTxt.value != null
        && !Trigger1Txt && !Trigger1Txt.value && Trigger1Txt.value != undefined && Trigger1Txt.value != null) {
        Target1Txt.value = TriggerTxt.value + '-' + Trigger1Txt.value;
        Target2Txt.value = TriggerTxt.value + '-' + Trigger1Txt.value;
        Target3Txt.value = TriggerTxt.value + '-' + Trigger1Txt.value;
        Target4Txt.value = TriggerTxt.value + '-' + Trigger1Txt.value;
    }
}

function CB_CheckedCopy(CBId, TxBxId, TxBxChild1Id) {
    var CB = document.getElementById(CBId);
    var TxBx = document.getElementById(TxBxId);
    //var TxBxParent = document.getElementById(TxBxParentId);
    var TxBxChild1 = document.getElementById(TxBxChild1Id);
    //if (CB != null && TxBx != null && TxBxParent != null && TxBxChild1 != null) {
    if (CB != null && TxBx != null && TxBxChild1 != null) {
        if (!CB.checked) {
            TxBx.disabled = false;
            $(TxBx).removeClass('disabled');
            TxBx.value = '';
            //if (TxBxParent.value == '' || TxBxChild1.value == '') {
            if (TxBxChild1.value == '') {
                TxBx.value = '';
            }
            else {
                //TxBx.value = TxBxParent.value * parseInt(TxBxChild1.value);
                TxBx.value = parseInt(TxBxChild1.value);
            }
        }
        else {
            TxBx.disabled = true;
            $(TxBx).addClass('disabled');
            TxBx.value = '';
        }
    }
}

function CB_QuotaEmailSettings(CBId, TxBxId, DDLId, RFVId) {
    var CB = document.getElementById(CBId);
    var TxBx = document.getElementById(TxBxId);
    var DDL = document.getElementById(DDLId);
    var RFV = document.getElementById(RFVId);

    if (CB != null && TxBx != null && DDL != null) {
        if (CB.checked) {
            TxBx.disabled = false;
            $(TxBx).removeClass('disabled');
            //DDL.disabled = false;
            toggleCombobox(DDLId);
            RFV.disabled = false;
            TxBx.value = '0';

            setTimeout(function () { DDL.selectedIndex = 0; $(DDL).trigger('change'); }, 500);

        }
        else {
            TxBx.disabled = true;
            $(TxBx).addClass('disabled');
            //DDL.disabled = true;
            toggleCombobox(DDLId);
            RFV.disabled = true;
            TxBx.value = '';
            setTimeout(function () { DDL.selectedIndex = 0; $(DDL).trigger('change'); }, 500);
        }
    }
}

function CB_CheckedChanged(CB_Id, Tr_Id) {
    var Tr = document.getElementById(Tr_Id);
    var CB = document.getElementById(CB_Id);
    if (CB.checked == true) {
        Tr.style.display = '';
    }
    else {
        Tr.style.display = 'none';
    }
}
function CB_CheckedChangedExchnage(CB_Id, Tr_Id, RFVId1, RFVId2) {
    var Tr = document.getElementById(Tr_Id);
    var CB = document.getElementById(CB_Id);
    var RFV1 = document.getElementById(RFVId1);
    var RFV2 = document.getElementById(RFVId2);
    if (CB.checked == true) {
        Tr.style.display = '';
        ValidatorEnable(RFV1, true);
        ValidatorEnable(RFV2, true);
    }
    else {
        ValidatorEnable(RFV1, false);
        ValidatorEnable(RFV2, false);
        RFV1.style.display = 'none'
        RFV2.style.display = 'none'
        Tr.style.display = 'none';
    }
}
function Trim(Id) {
    var Ctrl = document.getElementById(Id)
    Ctrl.value = Ctrl.value.trim();
}
function RemoveSpaces(ParentID) {
    var TxBx_Parent = $get(ParentID);

    if (TxBx_Parent != null) {
        var str = TxBx_Parent.value;
        while (str.lastIndexOf(' ') != -1) {
            str = str.replace(' ', '');
        }

        TxBx_Parent.value = str;
    }
}

function IsValidNumber(Id) {
    var Ctrl = document.getElementById(Id)
    var Val = Ctrl.value;
    if (!Ctrl.value.length == 0) {
        if (isNaN(Val)) {
            alert('Invalid ID.');
            Ctrl.value = ''
        }
        else {
            Ctrl.value = Ctrl.value * 1
            if (Ctrl.value.indexOf(".") >= 0) {
                Ctrl.value = Ctrl.value.substring(0, Ctrl.value.indexOf("."))
            }
            if (Ctrl.value <= 0) {
                //Ctrl.value = parseInt ((Ctrl.value*(-1)));	
                alert('ID must be greater than zero.');
                Ctrl.value = ''
            }
            if (Ctrl.value > 2147483647) {
                //Ctrl.value = '2147483647'
                alert('Integer value out of range.');
                Ctrl.value = ''
            }
        }
    }
}

function FocusSelected(LbxId) {
    var lb = document.getElementById(LbxId);
    if (lb != null) {
        var options = lb.options;
        for (var i = options.length - 1; i > 0; i--) {
            if (options[i].selected == true) {
                options[i].focus();
                options[i].selected = true;
                return;
            }
        }
    }
}

/// Luhn algorithm to validate credit card number
function isValidCreditCard(cardNumber) {
    var ccard = new Array(cardNumber.length);
    var i = 0;
    var sum = 0;

    //Remove white spaces and hyphens
    cardNumber = cardNumber.replace(/[\s\-]/g, '');

    // 6 digit is issuer identifier
    // 1 last digit is check digit

    // most card number > 11 digit and < 16
    if (cardNumber.length < 11 || cardNumber.length > 16)
        return false;

    // Init Array with Credit Card Number
    for (i = 0; i < cardNumber.length; i++) {
        ccard[i] = parseInt(cardNumber.charAt(i));
    }

    //Step 1:
    //Double the alternate digits starting from the first digit.
    //From card number:
    //4408 0412 3456 7890
    //    ^ ^  ^ ^  ^ ^  ^ ^  --> to double on step 1

    //(4+4) (0+0) (0+0) (1+1) (3+3) (5+5) (7+7) (9+9)
    //    8     0     0     2     6     10    14    18

    //Step 2:
    //For each result of step 1, if the value is bigger than
    //9 we need to substract by 9 so each value is less than 10.
    //After that we append all of them

    //8     0     0     2     6     10    14    18
    //	                        ^     ^     ^ --> need to substract by 9

    //Hence we have:

    //8  +  0  +  0  +  2  +  6  +  1  +  5  +  9 = 31

    //Step 3:
    //Now add all the non-doubled digits from the credit card number
    //From card number:
    //4408 0412 3456 7890
    //    ^ ^  ^ ^  ^ ^  ^ ^ --> to process on step 3

    //Hence we have: 4 + 8 + 4 + 2 + 4 + 6 + 8 + 0 = 36

    //Step 4:
    //Add the values calculated in step 2 and step 3 together
    //We have 31+36 = 67

    //Step 5 :
    //Take the value calculated in step 4 and calculate the remainder when it is
    //divided by 10. If the remainder is zero, then it's a valid number, otherwise
    //it's invalid.

    //So we have 67 % 10, reminder is 7 not 0 means this card number is invalid

    //If we change the check digit to 3 we will have on step 3 values 39 and hence we have
    //70 on step 4 and 70 % 0 -> reminder is 0 -> means card number is valid.

    // Run step 1-5 above above
    for (i = cardNumber.length - 1; i >= 0; i = i - 2) {
        if ((i - 1) > -1) {
            ccard[i - 1] = ccard[i - 1] * 2;
            if (ccard[i - 1] > 9) {
                ccard[i - 1] = ccard[i - 1] - 9;
            }
        }
    }

    for (i = 0; i < cardNumber.length; i++) {
        sum = sum + ccard[i];
    }
    return ((sum % 10) == 0);
}

//function isValidVISA_MasterCard(cardNumber) {
//    // if you want to accept Mastercard, Visa (Debit/Electron/Credit Card) ONLY!
//    if (cardNumber.charAt(0) == '4' && (cardNumber.length == 13 || cardNumber.length == 16)) {
//        return isValidCreditCard(cardNumber);
//    }
//    if (cardNumber.charAt(0) == '5' &&
//	               (cardNumber.charAt(1) == '1' || cardNumber.charAt(1) == '5')
//	   && cardNumber.length == 16) {
//        return isValidCreditCard(cardNumber);
//    }
//    return false;
//}

//function checkValid(cardNumber) {

//    if (isValidVISA_MasterCard(cardNumber)) {
//        alert('Credit Card number is valid VISA/MasterCard');
//    } else {
//        alert('Credit Card number is NOT valid VISA/MasterCard');
//    }
//}

function ValidateCreditCard(source) {
    var cardNumber = source.value;
    if (cardNumber.match(/(\*)*/) != ',')
        return true;
    if (isValidCreditCard(cardNumber))
        return true;
    else {
        alert('Invalid credit card number');
        return false;
    }
}

//To validate IPAddress
//http://stackoverflow.com/questions/12619293/regular-expression-net-regex-for-ipv6-and-ipv4
//http://forums.intermapper.com/viewtopic.php?t=452
function CheckIPAddress(TxBx_Id) {
    var TxBx = document.getElementById(TxBx_Id);
    //alert(TxBx.value);
    var MyIPAddress = TxBx.value;
    var CheckIP = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
    //var RegularExpression = new RegExp("^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$");
    if (CheckIP.test(MyIPAddress)) {
        //alert("Your IPV4 IP Address Is Valid.");
        //return true;
    }
    else {   //IPV4 is in-valid than test it for IPV6.
        //alert("Your IPV4 IP Address Is Not Valid.");
        CheckIP = /^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$/;
        if (CheckIP.test(MyIPAddress)) {
            //alert("Your IPV6 IP Address Is Valid.");
            //return true;
        }
        else {
            alert("IP Address is not Valid");  // for both IPV4 and IPV6.");
            TxBx.focus();
            TxBx.select();
            return false;
        }
    }

}
//function fCheckIPAddress(sender, args) {
//    alert("IN");
//    args.IsValid = false;
//    alert("IN");
//    var TxBx = document.getElementById("TxBx_IPAddress");
//    var MyIPAddress = TxBx.value
//    alert(MyIPAddress);
//    var CheckIP = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
//    if (CheckIP.test(MyIPAddress)) {
//        //alert("Your IPV4 IP Address Is Valid.");
//        //return true;
//    }
//    else {   //IPV4 is in-valid than test it for IPV6.
//        //alert("Your IPV4 IP Address Is Not Valid.");
//        CheckIP = /^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$/;
//        if (CheckIP.test(MyIPAddress)) {
//            //alert("Your IPV6 IP Address Is Valid.");
//            //return true;
//        }
//        else {
//            alert("IP Address is not Valid");  // for both IPV4 and IPV6.");
//            TxBx.focus();
//            TxBx.select();
//            args.IsValid = false;
//            //return false;
//        }
//    }
//   
//}
/*
function KeyCheck(e, TB1, TB2)
{
    var KeyID = (window.event) ? event.keyCode : e.keyCode;
    var TBox1 = document.getElementById(TB1)
    var TBox2 = document.getElementById(TB2)

   switch(KeyID) {
       case 180:
           if (TBox1.value > 255) {
               TBox1.focus();
               alert("Invalid Octat.");
           }
           else {
               TBox2.focus();
           }
      case 16:
      document.Form1.KeyName.value = "Shift";
      break;       case 17:
      document.Form1.KeyName.value = "Ctrl";
      break;      case 18:
      document.Form1.KeyName.value = "Alt";
      break;      case 19:
      document.Form1.KeyName.value = "Pause";
      break;      case 37:
      document.Form1.KeyName.value = "Arrow Left";
      break;      case 38:
      document.Form1.KeyName.value = "Arrow Up";
      break;      case 39:
      document.Form1.KeyName.value = "Arrow Right";
      break;      case 40:
      document.Form1.KeyName.value = "Arrow Down";
      break;   
   }
}*/

//function InitializeJalaliCalendar(targetControl, popupButton, setDate, autoFill)
//{
//    //alert(setDate);
//    var shamsiDate = ""
//    if (autoFill == true) {
//        shamsiDate = DateToShamsi(setDate);
//        shamsiDate = shamsiDate.replace(/\s+/g, '');
//    }
//    //alert(targetControl);
//    var tc = document.getElementById(targetControl);
//    //alert(autoFill);
//    //alert(shamsiDate);
//    if (tc) {
//        tc.value = shamsiDate;

//        Calendar.setup({
//            inputField: targetControl,
//            button: popupButton,
//            dateType: 'jalali',
//            ifFormat: "%Y/%m/%d",       // format of the input field
//            weekNumbers: false,
//            showOthers: true,
//            autoFillAtStart: autoFill,
//            date: shamsiDate
//        });
//    }

//}

//function PlaceJalaliCalendar(targetControl, popupButton, setDate)
//{
//    var autoFill = setDate == "1/1/1" ? false : true;
//    setTimeout(InitializeJalaliCalendar(targetControl, popupButton, setDate, autoFill), 1000);
//}

function setRtlAlignment(ContentDirection) {
    var isOpera = !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
    // Opera 8.0+ (UA detection to detect Blink/v8-powered Opera)
    var isFirefox = typeof InstallTrigger !== 'undefined';   // Firefox 1.0+
    var isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0;
    // At least Safari 3+: "[object HTMLElementConstructor]"
    var isChrome = !!window.chrome && !isOpera;              // Chrome 1+
    var isIE = /*@cc_on!@*/false || !!document.documentMode;   // At least IE6

    if (ContentDirection) {
        $("html").attr("dir", ContentDirection);
        var attrVal = ContentDirection == "rtl" ? "right" : "left";
        if (ContentDirection.toLowerCase() === 'rtl') {
            $("html").attr("lang", "fa");

            $("*[style]").filter(function () {
                return $(this).attr('style').match(/left/gi) || $(this).attr('style').match(/right/gi) || $(this).attr('style').match(/[0-9]+(px|%)\s+[0-9]+(px|%)\s+[0-9]+(px|%)\s+[0-9]+(px|%)/i);
            }).each(function () {

                if ($(this).attr('style').match(/[0-9]+(px|%)\s+[0-9]+(px|%)\s+[0-9]+(px|%)\s+[0-9]+(px|%)/i)) {
                    //top right bottom left
                    var currStr = $(this).attr('style').match(/[0-9]+(px|%)\s+[0-9]+(px|%)\s+[0-9]+(px|%)\s+[0-9]+(px|%)/i)[0];
                    var dimensions = currStr.split(/\s+/);
                    var rightX = dimensions[1];
                    dimensions[1] = dimensions[3];
                    dimensions[3] = rightX;
                    var newStr = dimensions.join(' ');
                    $(this).attr('style', $(this).attr('style').replace(/[0-9]+(px|%)\s+[0-9]+(px|%)\s+[0-9]+(px|%)\s+[0-9]+(px|%)/i, newStr));
                }

                $(this).attr('style', $(this).attr('style').replace(/left/gi, 'dayan'));
                $(this).attr('style', $(this).attr('style').replace(/right/gi, 'bayan'));
                $(this).attr('style', $(this).attr('style').replace(/dayan/gi, 'right'));
                $(this).attr('style', $(this).attr('style').replace(/bayan/gi, 'left'));
            });

            var styleFiles = document.styleSheets;
            var classRules = new Array();
            for (var i = 0; i < styleFiles.length; i++) {
                if (styleFiles[i].href != null) {
                    if (styleFiles[i].href.match(new RegExp(location.host))) {
                        var rulesList = styleFiles[i].rules ? styleFiles[i].rules : styleFiles[i].cssRules;
                        for (var j = 0; j < rulesList.length; j++)
                            if (rulesList[j].cssRules)
                                for (var k = 0; k < rulesList[j].cssRules.length; k++)
                                    classRules.push(rulesList[j].cssRules[k]);
                            else if (rulesList[j].parentRule)
                                for (var k = 0; k < rulesList[j].parentRule.cssRules.length; k++)
                                    classRules.push(rulesList[j].parentRule.cssRules[k]);
                            else if (rulesList[j].style)
                                classRules.push(rulesList[j]);
                    }
                }
            }


            var rulesToUpdate = classRules.filter(function (o) {
                if (o && o != undefined && o != null) {
                    var ruleText, ruleName;
                    if (o.cssText) {
                        ruleText = o.cssText;
                        ruleName = o.selectorText;
                    }
                    else if (o.CSSStyleRule && o.CSSStyleRule.cssText) {
                        ruleText = o.CSSStyleRule.cssText;
                        ruleName = o.CSSStyleRule.selectorText;
                    }
                    else if (o.style && o.style.cssText) {
                        ruleText = o.style.cssText;
                        ruleName = o.style.selectorText;
                    }
                    else
                        return false;
                    if (ruleText.match(/carousel|glyphicon|mp\-icons|fill/i))
                        return false;

                    return (ruleText.match(/:(\s)?left/gi) || ruleText.match(/left(\s)?:/gi)
                        || ruleText.match(/:(\s)?right/gi) || ruleText.match(/right(\s)?:/gi)
                        || ruleText.match(/[0-9]+(px|%)\s+[0-9]+(px|%)\s+[0-9]+(px|%)\s+[0-9]+(px|%)/i));
                }
                return false;
            });


            for (var i = 0; i < rulesToUpdate.length; i++) {
                var o = rulesToUpdate[i];

                var ruleText, ruleName;

                /*if(o.cssText){
                    ruleText = o.cssText;
                    ruleName = o.selectorText;
                }
                else if(o.CSSStyleRule && o.CSSStyleRule.cssText)
                {
                    ruleText = o.CSSStyleRule.cssText;
                    ruleName = o.CSSStyleRule.selectorText;
                }
                else if(o.style && o.style.cssText)
                {*/
                ruleText = o.style.cssText;
                ruleName = o.style.selectorText;
                //}

                if (ruleText.match(/[0-9]+(px|%)\s+[0-9]+(px|%)\s+[0-9]+(px|%)\s+[0-9]+(px|%)/i)) {
                    //top right bottom left
                    var currStr = ruleText.match(/[0-9]+(px|%)\s+[0-9]+(px|%)\s+[0-9]+(px|%)\s+[0-9]+(px|%)/i)[0];
                    var dimensions = currStr.split(/\s+/);
                    var rightX = dimensions[1];
                    dimensions[1] = dimensions[3];
                    dimensions[3] = rightX;
                    var newStr = dimensions.join(' ');
                    ruleText = ruleText.replace(/[0-9]+(px|%)\s+[0-9]+(px|%)\s+[0-9]+(px|%)\s+[0-9]+(px|%)/i, newStr);
                }

                ruleText = ruleText.replace(/:(\s)?left/gi, ':dayan');
                ruleText = ruleText.replace(/left(\s)?:/gi, 'dayan:');

                ruleText = ruleText.replace(/:(\s)?right/gi, ':bayan');
                ruleText = ruleText.replace(/right(\s)?:/gi, 'bayan:');

                ruleText = ruleText.replace(/dayan/gi, 'right');
                ruleText = ruleText.replace(/bayan/gi, 'left');

                o.style.cssText = ruleText.replace(ruleName, '').replace('{', '').replace('}', '');
            }
        }

    }
}

function SetCheckedHeader(CB, CBC, C) {
    var containerTable = null;
    if (C != '1') {//All Checkbox
        //containerTable = $(CBC).parent('th').parent('tr').parent('tbody').parent('table').first();
        containerTable = $(CBC).parents('table:first');
        $("input:checkbox", containerTable).prop('checked', CB);
    }
    else {
        containerTable = $(CBC).parents('table:first');
        if (CB == false) {
            $("input:checkbox", containerTable).first().prop('checked', false);
        }
    }

    var checked = false;

    $("input:checkbox", containerTable).each(function () {
        if ($(this).prop("checked") == true) {

            if ($(this).prop("disabled") != undefined) {

                if ($(this).prop("disabled") == true) {

                    $(this).prop('checked', false);

                }
                else {

                    checked = true;
                }


            } else {
                checked = true;
            }

        }

    });

    $(":submit[Custom1]").each(function () {
        if (checked == false)
            $(this).hide();
        else
            $(this).show();

    });

    $("table[Custom1]").each(function () {
        if (checked == false)
            $(this).hide();
        else
            $(this).show();

    });

    $("div[Custom1]").each(function () {
        if (checked == false)
            $(this).hide();
        else
            $(this).show();

    });

}
// checks only the checkboxes with specific class name in a specific container/table
function SetCheckedHeaderByClassName(CB, CBC, C, ClassName) {
    var containerTable = null;
    if (C != '1') {
        containerTable = $(CBC).parent('th').parent('tr').parent('tbody').parent('table').first();
        $("." + ClassName + " input:checkbox", containerTable).prop('checked', CB);
    }
    else {
        containerTable = $(CBC).parent('td').parent('tr').parent('tbody').parent('table').first();
        if (CB == false) {
            $("." + ClassName + " input:checkbox.a", containerTable).first().prop('checked', false);
        }
    }

}

function SetCheckedHeaderCustom(CB, CBC, C) {
    var containerTable = null;
    if (C != '1') {//All Checkbox
        //containerTable = $(CBC).parent('th').parent('tr').parent('tbody').parent('table').first();
        containerTable = $(CBC).parents('table:first');
        $("input:checkbox:not(:disabled)", containerTable).prop('checked', CB);
    }
    else {
        containerTable = $(CBC).parents('table:first');
        if (CB == false) {
            $("input:checkbox:not(:disabled)", containerTable).first().prop('checked', false);
        }
    }
}

function SetCheckedHeaderCommercialSaaSProd(CB, CBC, C) {
    var containerTable = null;
    containerTable = $(CBC).parents('table:first');

    if (C != '1') {//All visible Checkboxes
        $('.search-js-prod-row', containerTable).each(function () {
            if (!($(this).hasClass('hide') || $(this).hasClass('d-none')))
                $("input:checkbox:not(:disabled)", $(this)).prop('checked', CB);
        });
    }
    else {
        if (CB == false) {
            $("input:checkbox:not(:disabled)", containerTable).first().prop('checked', false);
        }
    }
}

function setOwnerCookie(source) {

    var ownerVal;
    if (typeof (source) == 'object')
        ownerVal = source.options[source.selectedIndex].value;
    else
        ownerVal = source;

    //if (ownerVal == 1 || ownerVal == 0 || ownerVal == -1) //below function is written in master page
    setCookie('OwnerOption', ownerVal, 10);
}


function setLeadViewCookie(source) {
    var ownerVal = source.options[source.selectedIndex].value;

    setCookie('LeadViewOption', ownerVal, 10);
}


//Disable and enable the combobox
function toggleCombobox(source) {
    source = '#' + source;
    if ($(source).hasClass('combobox')) {
        if ($(source).hasClass('disabled') || ($(source).attr('disabled')
            && ($(source).attr('disabled') == 'disabled' || $(source).attr('disabled') == true || $(source).attr('disabled') == 1)))
            $(source).removeClass('disabled').removeAttr('disabled').combobox('enable');
        else
            $(source).addClass('disabled').attr('disabled', true).combobox('disable');
    }
    else {
        if ($(source).hasClass('disabled') || ($(source).attr('disabled')
            && ($(source).attr('disabled') == 'disabled' || $(source).attr('disabled') == true || $(source).attr('disabled') == 1)))
            $(source).removeClass('disabled').removeAttr('disabled');
        else
            $(source).addClass('disabled').attr('disabled', true);
    }
}

function IpRangeValidation(TBLastIp, TBFirstIp) {

    //This function is primarly used to set the ip range on Subnet User control, codded by Numan dated 28 Jan 2015.

    var LastIpValue = document.getElementById(TBLastIp).value;
    var FirstIpValue = document.getElementById(TBFirstIp).value;
    var FirstIpStart = FirstIpValue.split('.');
    FirstIpValue = FirstIpStart[3];

    if (LastIpValue >= 255)  //It will check the last ip text box value. if the value is equal or greater then 255 then it will set it to 254 as maximum value of the ip can be 254.
    {
        document.getElementById(TBLastIp).value = 254;
    }

    if (parseInt(FirstIpValue) > parseInt(LastIpValue)) //It will check the first ip text box value and last ip value. If user has entered last ip value less then start ip value then it will automatically set it to the starting ip address.
    {

        document.getElementById(TBLastIp).value = FirstIpValue;
    }
}

function CPUCoresAndMaxVPSCheck(CPUCores, MaxVPSMemebers) {

    if ((parseInt(document.getElementById(MaxVPSMemebers).value)) > (parseInt(document.getElementById(CPUCores).value))) {
        // document.getElementById(CPUCores).focus();
        alert("CPU Cores must be greate then maximum VPS");
        return false;

        //alert("Hi");
    }
}

function MaxMinMbpsCheck(MaxMbps, MinMbps) {

    if ((parseInt(document.getElementById(MinMbps).value)) > (parseInt(document.getElementById(MaxMbps).value))) {
        // document.getElementById(CPUCores).focus();
        alert("Max Mbps value must be greater then min Mbps.");

        //alert("Hi");
    }
}

function MinimumMaximumValueCheck(MinimumValue, MaximumValue, ProvidedValue) {
    if (isNaN(parseFloat(document.getElementById(ProvidedValue).value))) {
        //alert("query is a string");
        document.getElementById(ProvidedValue).value = MinimumValue;
        return;
    }
    MinimumValueCheck(MinimumValue, ProvidedValue);
    MaximumValueCheck(MaximumValue, ProvidedValue);
}

function MinimumValueCheck(MinimumValue, ProvidedValue) {

    if ((parseInt(document.getElementById(ProvidedValue).value)) < MinimumValue) {
        document.getElementById(ProvidedValue).value = MinimumValue;
        //alert(MinimumValue);
    }
}
function MaximumValueCheck(MaximumValue, ProvidedValue) {

    if ((parseInt(document.getElementById(ProvidedValue).value)) > MaximumValue) {
        document.getElementById(ProvidedValue).value = MaximumValue;
        //alert(MinimumValue);
    }
}

/*client side search in listbox (select with multiple option) start*/

function replaceSpecialChars(inputVal) {
    if (inputVal && inputVal != '') {

        var specialChars = ['^', '$', '.', '|', '{', '}', '[', ']', '(', ')', '*', '+', '?', '\\', '\''];

        var inputCharArray = inputVal.split('');

        for (var x = 0; x < inputCharArray.length; x++)
            for (var y = 0; y < specialChars.length; y++)
                if (inputCharArray[x] == specialChars[y])
                    inputCharArray[x] = '\\' + inputCharArray[x];

        inputVal = inputCharArray.join('');

    }
    return inputVal;
}
//var currentSearchText = '';
function SearchInMultipleSelect(source, e, selectItem1Id, selectItem2Id) {

    if (source.value.length > 1 && e.keyCode == 13) {


        //currentSearchText = source.value;

        //console.log("currentSearchText" + currentSearchText);
        //setTimeout(function () { searchMultiSelect(source.value, $get(selectItem1Id), $get(selectItem2Id)) }, 100);

        searchMultiSelect(source.value, $get(selectItem1Id), $get(selectItem2Id));
    }
}

//function searchMSelect(searchText, lbx) {

//    let lbxArray = new Array();
//    lbx.selectedIndex = -1

//    for (let i = 0; i < lbx.options.length; i++) {
//        if (lbx.options[i].text.toLowerCase().indexOf(searchText) != -1) {
//            lbx.options[i].selected = true;
//            lbxArray.push(lbx.options[i]);
//        }
//    }

//    for (let i = 0; i < lbx.options.length; i++) {
//        if (lbx.options[i].selected == false)
//            lbxArray.push(lbx.options[i]);
//    }

//    lbx.innerHTML = null;

//    for (let i = 0; i < lbxArray.length; i++) {
//        lbx.appendChild(lbxArray[i]);
//    }

//    lbxArray = null;
//    lbx = null;

//}

function searchMSelect(searchText, lbx) {
    if (!lbx || !lbx.options) return;

    const text = searchText.toLowerCase();
    const matches = [];
    const others = [];

    // Separate matching and non-matching options
    for (const opt of lbx.options) {
        if (opt.text.toLowerCase().includes(text)) {
            opt.selected = true;
            matches.push(opt);
        } else {
            opt.selected = false;
            others.push(opt);
        }
    }

    // Rebuild options with matches first
    lbx.replaceChildren(...matches, ...others);
}

function searchMultiSelect(searchText, lbx1, lbx2) {

    searchText = searchText.toLowerCase();

    searchMSelect(searchText, lbx1);

    if (lbx2 != null && lbx2 != undefined)
        searchMSelect(searchText, lbx2);

}


function ScrollToSelectedItem(selectItemId) {
    if ($('#' + selectItemId + ' option:selected').first() != null && $('#' + selectItemId + ' option:selected').first() != undefined) {
        var container = $('#' + selectItemId),
            scrollTo = $('#' + selectItemId + ' option:selected').first()
        if (container.offset() != null && container.offset() != undefined
            && scrollTo.offset() != null && scrollTo.offset() != undefined)
            container.animate({ scrollTop: scrollTo.offset().top - container.offset().top + container.scrollTop() }, 500);
    }
}

function bringSelectedItemsToTop(selectItemId, searchText) {
    $("#" + selectItemId + " option:selected")
        .each(function () {
            if (searchText == currentSearchText) {
                var $option = $(this);
                setTimeout(function () { $option.prependTo("#" + selectItemId) }, 5);
            }
        });
}
function setInputTextCaretPosition(elemId, caretPos) {
    var elem = document.getElementById(elemId);

    if (elem != null) {
        if (elem.createTextRange) {
            var range = elem.createTextRange();
            range.move('character', caretPos);
            range.select();
        }
        else {
            if (elem.selectionStart) {
                elem.focus();
                elem.setSelectionRange(caretPos, caretPos);
            }
            else
                elem.focus();
        }
    }
}

function ClearDefault(source) {
    source.value = '';
    if ($('section.content div[onkeypress^="javascript:return WebForm_FireDefaultButton(event, "]').length > 0) {
        $('section.content div[onkeypress^="javascript:return WebForm_FireDefaultButton(event, "]').each(function () {
            let defaultBtn = $(this).attr('onkeypress');
            defaultBtn = defaultBtn.replace("javascript:return WebForm_FireDefaultButton(event, '", "").replace("')", "");
            if (document.getElementById(defaultBtn))
                document.getElementById(defaultBtn).setAttribute("disabled", "disabled");
        });
    }
}

function SetDefaultValue(source, value) {
    source.value = value;
    if ($("section.content div[onkeypress^='javascript:return WebForm_FireDefaultButton(event, ']").length > 0) {
        $("section.content div[onkeypress^='javascript:return WebForm_FireDefaultButton(event, ']").each(function () {
            let defaultBtn = $(this).attr('onkeypress');
            defaultBtn = defaultBtn.replace("javascript:return WebForm_FireDefaultButton(event, '", "").replace("')", "");
            if (document.getElementById(defaultBtn))
                document.getElementById(defaultBtn).removeAttribute("disabled");
        });
    }
}

function SetDefaultValueIfBlank(source, value) {
    if (source.value == '')
        SetDefaultValue(source, value)
    else if (source.value != value)
        SetDefaultValue(source, value);
}

function ClearDefaultIfNotChanged(source, defaultValue) {
    if (source.value == defaultValue)
        ClearDefault(source);
}

/*client side search in listbox (select with multiple option) end*/

function ShowHideRowAndEnableDisableTextboxOnButton(chk, txt, divSelect, divQuantity, showMe) {
    var chkboxid = document.getElementById(chk);
    var txtBoxid = document.getElementById(txt);
    var divS = document.getElementById(divSelect);
    var divQ = document.getElementById(divQuantity);

    if (showMe == '1') {
        divQ.style.display = '';
        chkboxid.checked = true;
        txtBoxid.value = 1;
        divS.style.display = 'none';
    }
    else {
        divS.style.display = '';
        chkboxid.checked = false;
        txtBoxid.value = '';
        divQ.style.display = 'none';
    }
}

function SelectUnSelect(chk, divSelect, divQuantity, showMe) {
    var chkboxid = document.getElementById(chk);
    var divS = document.getElementById(divSelect);
    var divQ = document.getElementById(divQuantity);

    if (showMe == '1') {

        chkboxid.checked = true;
        divQ.style.display = '';
        divS.style.display = 'none';
    }
    else {
        divS.style.display = '';
        chkboxid.checked = false;
        divQ.style.display = 'none';
    }
}

function RowShowHideonCheckBox(chk, tr) {

    var chkboxid = document.getElementById(chk);
    var trid = document.getElementById(tr);

    if (chkboxid.checked == true) {
        trid.style.display = '';
    }
    else {
        trid.style.display = 'none';
    }
}

function RowShowHideonClientClick(tr) {

    var trid = document.getElementById(tr);

    if (trid.style.display == '') {
        trid.style.display = 'none';
    }
    else {
        trid.style.display = '';
    }
}

function ShowHideRowAndEnableDisableTextboxonCheckbox(chk, txt, tr) {
    EnableDisableOfferAddonTextBoxWithQuantity(chk, txt);
    if (tr != null)
        RowShowHideonCheckBox(chk, tr);

}
function EnableDisableOfferAddonTextBoxWithQuantity(chk, txt) {

    var chkboxid = document.getElementById(chk);
    var txtBoxid = document.getElementById(txt);

    if (chkboxid.checked == true) {
        txtBoxid.disabled = false;
        $(txtBoxid).removeClass('disabled');
        txtBoxid.value = 1;
    }
    else {
        txtBoxid.disabled = true;
        $(txtBoxid).addClass('disabled');
        txtBoxid.value = '';
    }
}

function EnableDisableBandwidthTextBox(chk, txt) {

    var chkboxid = document.getElementById(chk);
    var txtBoxid = document.getElementById(txt);

    if (chkboxid.checked == true) {
        txtBoxid.value = '';
        txtBoxid.disabled = true;
        $(txtBoxid).addClass('disabled');
    }
    else {
        txtBoxid.disabled = false;
        $(txtBoxid).removeClass('disabled');
    }
}

function ValidateEmail(email) {
    // Regular expression for validating email
    const regex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;

    // Test the email against the regular expression
    return regex.test(email);
}

function ValidateCommaSeparatedEmails(emails) {
    if (!emails) return false; // Handle empty input

    // Split the input by commas and trim whitespace
    const emailList = emails.split(',').map(email => email.trim());

    // Validate each email address
    for (const email of emailList) {
        if (!ValidateEmail(email)) {
            return false; // Return false if any email is invalid
        }
    }

    return true; // All emails are valid
}

function TwoFAOptionSelection(chk) {

    var divCusPINThroughEmail = document.getElementById(chk);
    var divCusPINThroughSMS = document.getElementById(chk.replace("divCusPINThroughEmail", "divCusPINThroughSMS"));
    var divCusGoogleAuthenticator = document.getElementById(chk.replace("divCusPINThroughEmail", "divCusGoogleAuthenticator"));
    var divCusDuoAuthentication = document.getElementById(chk.replace("divCusPINThroughEmail", "divCusDuoAuthentication"));

    if (divCusPINThroughEmail != null) {
        var divEmail = document.getElementById(chk.replace("divCusPINThroughEmail", "divEmail"));
        var rdb_PINThroughEmail = document.getElementById(chk.replace("divCusPINThroughEmail", "rdb_PINThroughEmail"));
        divEmail.style.display = rdb_PINThroughEmail.checked ? '' : 'none';
    }

    if (divCusPINThroughSMS != null) {
        var divPhoneNumber = document.getElementById(chk.replace("divCusPINThroughEmail", "divPhoneNumber"));
        var rdb_PINThroughSMS = document.getElementById(chk.replace("divCusPINThroughEmail", "rdb_PINThroughSMS"));
        divPhoneNumber.style.display = rdb_PINThroughSMS.checked ? '' : 'none';
    }

    if (divCusGoogleAuthenticator != null) {
        var divGoogleMsg = document.getElementById(chk.replace("divCusPINThroughEmail", "divGoogleMsg"));
        var rdb_GoogleAuthenticator = document.getElementById(chk.replace("divCusPINThroughEmail", "rdb_GoogleAuthenticator"));
        divGoogleMsg.style.display = rdb_GoogleAuthenticator.checked ? '' : 'none';
    }

    if (divCusDuoAuthentication != null) {
        var divDuoMsg = document.getElementById(chk.replace("divCusPINThroughEmail", "divDuoMsg"));
        var rdb_DuoAuthentication = document.getElementById(chk.replace("divCusPINThroughEmail", "rdb_DuoAuthentication"));
        divDuoMsg.style.display = rdb_DuoAuthentication.checked ? '' : 'none';
    }

}

function TwoFAMobileNumberReq(div, rdb, TxBx, chk) {

    var DivShow = document.getElementById(div);
    var RdbSMS = document.getElementById(rdb);
    var TxBxSMS = document.getElementById(TxBx);
    var ChkEnab = document.getElementById(chk);


    var RdbEmail = document.getElementById(chk.replace("Cb_EnabledCus", "rdb_PINThroughEmail"));
    var RdbGoogle = document.getElementById(chk.replace("Cb_EnabledCus", "rdb_GoogleAuthenticator"));
    var RdbDuoAuth = document.getElementById(chk.replace("Cb_EnabledCus", "rdb_DuoAuthentication"));


    if (ChkEnab.checked && (RdbSMS != null && RdbSMS.checked == false) && (RdbEmail != null && RdbEmail.checked == false) && (RdbGoogle != null && RdbGoogle.checked == false) && (RdbDuoAuth != null && RdbDuoAuth.checekd == false)) {
        alert('Please select one option for authentication.');
        return false;
    }
    //else
    if (RdbSMS.checked && TxBxSMS.value.trim() == '') {
        DivShow.style.display = '';

        return false;
    }
    else {
        DivShow.style.display = 'none';

        return true;
    }

}


function RowShowHideTwoRowsonCheckBox(chk, tr1, tr2) {

    var chkboxid = document.getElementById(chk);
    var trid = document.getElementById(tr1);
    var tr2id = document.getElementById(tr2);

    if (trid)
        trid.style.display = chkboxid.checked ? '' : 'none';
    if (tr2id)
        tr2id.style.display = chkboxid.checked ? '' : 'none';
}

function toggleOfferAddons(source, e) {
    var $source = $('#' + source.id);
    if ($source.is(':checkbox')) {
        if (source.checked) {
            $source.parent().next().show();
            $source.siblings('a').first().text($source.siblings('a').first().data('hide-text'));
        }
        else {
            $source.parent().next().hide();
            $source.siblings('a').first().text($source.siblings('a').first().data('show-text'));
        }
    }
    else {
        if ($source.text() == $source.data('show-text')) {
            $source.closest('.row-label').next().show();
            $source.text($source.data('hide-text'));
        }
        else {
            $source.closest('.row-label').next().hide();
            $source.text($source.data('show-text'));
        }
    }
}

function filterOffers(txbx) {
    $('.search-js-offer-row').removeClass('hide');
    $('#accordion_1 .panel.panel-primary').removeClass('hide');
    if (txbx.value != '' && txbx.value.length > 1) {
        var searchPattern = new RegExp(replaceSpecialChars(txbx.value), "gi");
        $('.search-js-offer-row').each(function () {
            $this = $(this);
            if (!$('.row-label label', $this).html().match(searchPattern))
                $this.addClass('hide');
            else
                $this.removeClass('hide');
        });

        $('#accordion_1 .panel.panel-primary').each(function () {
            $this = $(this);
            var hidePanel = true;
            $this.find('.search-js-offer-row').each(function () {
                if (!$(this).hasClass('hide'))
                    hidePanel = false;
            });
            if (hidePanel)
                $this.addClass('hide');
            else
                $this.removeClass('hide');
        });

        $('#accordion_1 .panel.panel-primary:not(.hide)').children('.panel-collapse').collapse('show');
    }
}

function filterCSPOffers(txbx) {
    //show all offer rows
    $('.search-js-offer-row').removeClass('hide');
    if (txbx.value != '' && txbx.value.length > 1) {
        var searchPattern = new RegExp(replaceSpecialChars(txbx.value), "gi");
        $('.search-js-offer-row').each(function () {
            $this = $(this);
            if (!$('input.search-js-offer-text', $this).val().match(searchPattern))
                $this.addClass('hide');
            else
                $this.removeClass('hide');
        });
    }
}

function filterSubscriptions(txbx) {
    $('.search-js-offer-row').removeClass('hide');
    $('.addon-row').removeClass('hide');
    $('.search-js-addon-row').removeClass('hide');

    if (txbx.value != '' && txbx.value.length > 1) {
        var searchPattern = new RegExp(replaceSpecialChars(txbx.value), "gi");
        $('.search-js-offer-row').each(function () {
            $this = $(this);
            try {
                if (!$('.shade span', $this).html().match(searchPattern)) {
                    // hide offer and addons
                    $this.addClass('hide');
                    $this.next('.addon-row').addClass('hide');
                }
                else {
                    // show offer row
                    $this.removeClass('hide');
                    // check addons for search text
                    $this.next('.addon-row').find('.search-js-addon-row').each(function () {
                        $that = $(this);
                        if (!$('.child-listing-first-col span', $that).html().match(searchPattern))
                            $that.addClass('hide');
                        else
                            $that.removeClass('hide');
                    });
                }
            }
            catch (err) { }
        });
    }
}

function checkAllPermissions(cb, containerid) {
    var chbk = document.getElementById(cb);

    var c = chbk.checked;



    $('#' + containerid).find("tr").css('display', '');

    $('#' + containerid).find("input:checkbox:not([disabled])").prop('checked', c ? 'checked' : '');//.trigger('click');

}

function insertAtCursor(myField, myValue) {
    var TextBox = document.getElementById(myField);
    var DDL = document.getElementById(myValue);
    if (DDL.selectedIndex > 0) {
        myValue = DDL.options[DDL.selectedIndex].value;

        var editPanel = oboutGetEditorByClientId(myField);
        editPanel.InsertHTML(myValue);
        //editPanel.setContent(editPanel.getContent() + myValue);

        setTimeout(function () { DDL.selectedIndex = 0; $(DDL).trigger('change'); }, 500);
    }
}
function insertAtCursorTextArea(myField, myValue) {
    var TextBox = document.getElementById(myField);
    var DDL = document.getElementById(myValue);
    if (DDL.selectedIndex > 0) {
        myValue = DDL.options[DDL.selectedIndex].value;
        TextBox.value += myValue;

        setTimeout(function () { DDL.selectedIndex = 0; $(DDL).trigger('change'); }, 500);
    }
}

function IsDefaultShowHide(IsDef, TRDel, CBDel) {
    var Isd = document.getElementById(IsDef);
    var TRD = document.getElementById(TRDel);
    var CBD = document.getElementById(CBDel);

    if (Isd.checked == true) {
        TRD.style.display = 'none';
        CBD.checked = false;
    }
    else {
        TRD.style.display = '';
        CBD.checked = false;
    }
}

function GenerateRandomStr(strLength) {
    var characters = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r',
        's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
        'X', 'Y', 'Z'];
    var randomString = "";
    for (var i = 0; i < strLength; i++) {
        randomString = randomString + characters[Math.floor(Math.random() * characters.length)];
    }
    return randomString;
}

function RemoveWWWFromDomain(myField) {
    var TextBox = document.getElementById(myField);
    if (TextBox.value.trim().toLowerCase().indexOf("www.") == 0)
        TextBox.value = TextBox.value.trim().toLowerCase().substring(4);
}

function onOkCancelAddon(TxBx_ItemComments, Btn_Pop_OK, MP1Addon, Msg) {

    if (document.getElementById(TxBx_ItemComments).value != '') {
        __doPostBack(Btn_Pop_OK, '');
    }
    else {
        alert(Msg);
        $find(MP1Addon).show();
    }

}
function onCancelCancelAddon() {
    //  __doPostBack('ctl00$RightContentPlaceHolder$Btn_Pop_Cancel','');
    //      __doPostBack('ctl00$RightContentPlaceHolder$GV_TicketList$ctl02$LBtn_Del','')
}
// Debounce function for jQuery
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func.apply(this, args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

//function Update_HF_SelectedMembers(LBX, HF, HFT) {
//    debounce(function () {
//        $('#' + HF).val('');
//        $('#' + HFT).val('');
//        let lbxCtrl = document.getElementById(LBX);
//        let hfCtrl = document.getElementById(HF);
//        let hftCtrl = document.getElementById(HFT)

//        let newVal = '';
//        for (i = 0; i < lbxCtrl.options.length; i++) {
//            newVal += '×' + lbxCtrl.options[i].value;
//        }
//        hfCtrl.value = newVal;
//        hftCtrl.value = newVal;
//    }, 250)();

//}

// Create a reusable debouncer (defined once globally)
const debounceUpdate = (() => {
    let timer;
    return (callback, delay = 250) => {
        clearTimeout(timer);
        timer = setTimeout(callback, delay);
    };
})();

function Update_HF_SelectedMembers(LBX, HF) {

    debounceUpdate(() => {

        document.getElementById(HF).value = Array.from(document.getElementById(LBX).options)
            .map(opt => `×${opt.value}`)
            .join('');

    }, 250);
}


//Function to Sort ListBoxItems by Text.
//function SortListBoxItemsByText(LBX) {

//    let lst = document.getElementById(LBX);
//    let opts = document.getElementById(LBX).options;

//    let A = new Array();
//    for (i = 0; i < opts.length; i++) {
//        let opt = new Object();
//        opt.text = opts[i].text;
//        opt.value = opts[i];
//        A.push(opt);
//    }

//    A.sort(function (x, y) {
//        let a = x.text.toLowerCase();
//        let b = y.text.toLowerCase();
//        return a == b ? 0 : a > b ? 1 : -1;
//    });

//    opts = null;
//    lst.innerHTML = null;

//    for (i = 0; i < A.length; i++)
//        lst.appendChild(A[i].value);

//    A = null;

//}

function SortListBoxItemsByText(LBX) {
    const list = document.getElementById(LBX);
    if (!list) return;

    // Convert options to array and sort by text (case-insensitive)
    const sortedOptions = Array.from(list.options).sort((a, b) =>
        a.text.localeCompare(b.text, undefined, { sensitivity: 'base' })
    );

    // Rebuild the list efficiently
    list.replaceChildren(...sortedOptions);
}

//Function to Sort ListBoxItems by VALUE.
//function SortListBoxItemsByValue(LBX) {

//    let lst = document.getElementById(LBX);
//    let opts = document.getElementById(LBX).options;

//    let A = new Array();
//    for (i = 0; i < opts.length; i++) {
//        let opt = new Object();
//        opt.text = opts[i].value;
//        opt.value = opts[i];
//        A.push(opt);
//    }

//    if (A.length > 0)
//        if (!isNaN(A[0].text)) {
//            A.sort(function (x, y) {
//                let a = parseInt(x.text);
//                let b = parseInt(y.text);
//                return (a - b);
//            });

//        }
//        else {
//            A.sort(function (x, y) {
//                return x.text == y.text ? 0 : x.text > y.text ? 1 : -1;
//            });
//        }

//    opts = null;
//    lst.innerHTML = null;

//    for (i = 0; i < A.length; i++)
//        lst.appendChild(A[i].value);

//    A = null;

//}

function SortListBoxItemsByValue(LBX) {
    const list = document.getElementById(LBX);
    if (!list) return;

    const options = Array.from(list.options);
    if (options.length === 0) return;

    // Detect if sorting should be numeric or text-based
    const isNumeric = !isNaN(parseFloat(options[0].value));

    options.sort((a, b) => {
        if (isNumeric) {
            return parseFloat(a.value) - parseFloat(b.value);
        }
        return a.value.localeCompare(b.value, undefined, { sensitivity: 'base' });
    });

    list.replaceChildren(...options);
}


//function CopySelectedListBoxItemsValueToHiddenField(HF, LBX) {

//    $('#' + HF).val('');
//    let HTxBx = HF.replace('HF_', 'HTxBx_');


//    $('#' + LBX + ' option[selected="selected"]').each(function () {
//        $('#' + HF).val($('#' + HF).val() + '×' + $(this).val());
//    });
//    $('#' + HTxBx).val($('#' + HF).val());
//}

function CopySelectedListBoxItemsValueToHiddenField(HF, LBX) {

    document.getElementById(HF).value = Array.from(document.getElementById(LBX).selectedOptions)
        .map(opt => `×${opt.value}`)
        .join('');

}


//function CopyAllListBoxItemsValueToHiddenField(HF, LBX) {

//    $('#' + HF).val('');
//    let HFValue = "";
//    LBX.forEach(function (o) {
//        //alert($(this).prop('selected'));
//        HFValue = HFValue + '×' + o.value + "~" + (o.selected ? "1" : "0");
//    });
//    $('#' + HF).val(HFValue);
//}

function CopyAllListBoxItemsValueToHiddenField(HF, LBX) {

    document.getElementById(HF).value = LBX.map(o => `${o.value}×`).join('');

}


//function MoveSelectableSelectedListItems(LBX_From, LBX_To, MoveAll, HF_Selected, SortByValue) {


//    let fromList = document.getElementById(LBX_From);
//    let toList = document.getElementById(LBX_To);

//    let fromArray = new Array();
//    let toArray = new Array();

//    for (i = 0; i < fromList.options.length; i++)
//        if (fromList.options[i].getAttribute('Syncing') != "1")
//            if (MoveAll == '1' || fromList.options[i].selected) {
//                toArray.push(fromList.options[i]);//Move Selected item where sync is off.
//            }
//            else
//                fromArray.push(fromList.options[i]);
//        else
//            fromArray.push(fromList.options[i]);

//    for (i = 0; i < toList.options.length; i++)//Move items already in tolist.
//        toArray.push(toList.options[i]);

//    if (SortByValue.toLowerCase() == 'true') {

//        toArray.sort(function (x, y) {
//            if (isNaN(x.value) || isNaN(y.value)) {
//                let a = x.value.toLowerCase();
//                let b = y.value.toLowerCase();
//                return a == b ? 0 : a > b ? 1 : -1;
//            }
//            else {
//                let a = parseInt(x.value);
//                let b = parseInt(y.value);
//                return (a - b);
//            }
//        });
//    }
//    else {

//        toArray.sort(function (x, y) {
//            let a = x.text.toLowerCase();
//            let b = y.text.toLowerCase();
//            return a == b ? 0 : a > b ? 1 : -1;
//        });
//    }

//    fromList.innerHTML = null;

//    debounce(function (f, fList) {
//        for (i = 0; i < f.length; i++)
//            fList.appendChild(f[i]);
//    }, 0)(fromArray, fromList);

//    toList.innerHTML = null;
//    debounce(function (t, tList) {
//        for (i = 0; i < t.length; i++)
//            tList.appendChild(t[i]);
//    }, 0)(toArray, toList);


//    let HT = HF_Selected.replace("HF_SelectedMembers", "HTxBx_SelectedMembers");

//    if (LBX_From.toLowerCase().indexOf('lbx_selected') > -1) {
//        CopyAllListBoxItemsValueToHiddenField(HF_Selected, fromArray);
//    }
//    else {
//        CopyAllListBoxItemsValueToHiddenField(HF_Selected, toArray);
//    }

//    $('#' + HT).val($('#' + HF_Selected).val());

//    fromArray = null
//    toArray = null;

//    HT = null;
//    fromList = null;
//    toList = null;

//    return false;

//}

function MoveSelectableSelectedListItems(LBX_From, LBX_To, MoveAll, HF_Selected, SortByValue) {
    const fromList = document.getElementById(LBX_From);
    const toList = document.getElementById(LBX_To);
    if (!fromList || !toList) return false;

    const moveAll = MoveAll === '1';
    const sortByValue = SortByValue.toLowerCase() === 'true';

    const fromArray = [];
    const toArray = [];

    // Collect items to move and retain
    for (const opt of fromList.options) {
        const syncing = opt.getAttribute('Syncing') === '1';
        if (!syncing && (moveAll || opt.selected)) {
            toArray.push(opt);
        } else {
            fromArray.push(opt);
        }
    }

    // Include items already in the destination list
    for (const opt of toList.options) {
        toArray.push(opt);
    }

    // Sort combined destination list
    toArray.sort((a, b) => {
        const valA = sortByValue
            ? (isNaN(a.value) ? a.value.toLowerCase() : parseInt(a.value))
            : a.text.toLowerCase();
        const valB = sortByValue
            ? (isNaN(b.value) ? b.value.toLowerCase() : parseInt(b.value))
            : b.text.toLowerCase();

        return valA > valB ? 1 : valA < valB ? -1 : 0;
    });

    // Replace options efficiently
    fromList.replaceChildren(...fromArray);
    toList.replaceChildren(...toArray);


    const sourceArray = LBX_From.toLowerCase().includes('lbx_selected') ? fromArray : toArray;
    CopyAllListBoxItemsValueToHiddenField(HF_Selected, sourceArray);

    return false;
}


//function MoveDown(LBX_Members, HF_Selected) {
//    var selectedOption = $('#' + LBX_Members + ' option:selected:last');
//    var nextOption = $('#' + LBX_Members + ' option:selected:last').next("option");
//    if ($(nextOption).text() != "") {
//        $(selectedOption).remove();
//        $(nextOption).after($(selectedOption));

//        UpdateHiddenField(LBX_Members, HF_Selected);
//    }
//    return false;
//}

function MoveDown(LBX_Members, HF_Selected) {
    const list = document.getElementById(LBX_Members);
    if (!list) return false;

    const selected = list.selectedIndex;
    if (selected === -1 || selected === list.options.length - 1) return false;

    const option = list.options[selected];
    const nextOption = list.options[selected + 1];

    // Swap positions
    list.insertBefore(nextOption, option);

    // Preserve selection
    nextOption.selected = false;
    option.selected = true;

    UpdateHiddenField(LBX_Members, HF_Selected);

    return false;
}


//function MoveUp(LBX_Members, HF_Selected) {
//    var selectedOption = $('#' + LBX_Members + ' option:selected:first');
//    var prevOption = $('#' + LBX_Members + ' option:selected:first').prev("option");
//    if ($(prevOption).text() != "") {
//        $(selectedOption).remove();
//        $(prevOption).before($(selectedOption));

//        UpdateHiddenField(LBX_Members, HF_Selected);
//    }

//    return false;
//}

function MoveUp(LBX_Members, HF_Selected) {
    const list = document.getElementById(LBX_Members);
    if (!list) return false;

    const selectedIndex = list.selectedIndex;
    if (selectedIndex <= 0) return false; // nothing selected or already at top

    const option = list.options[selectedIndex];
    const prevOption = list.options[selectedIndex - 1];

    // Swap option upward
    list.insertBefore(option, prevOption);

    // Preserve selection
    option.selected = true;

    UpdateHiddenField(LBX_Members, HF_Selected);

    return false;
}


//function MoveTop(LBX_Members, HF_Selected) {
//    var selectedOption = $('#' + LBX_Members + ' option:selected:first');
//    var firstOption = $('#' + LBX_Members + ' option:first');
//    if (!($(selectedOption).is($(firstOption))) && $(firstOption).text() != "") {
//        $(selectedOption).remove();
//        $(firstOption).before($(selectedOption));

//        UpdateHiddenField(LBX_Members, HF_Selected);
//    }

//    return false;
//}

function MoveTop(LBX_Members, HF_Selected) {
    const list = document.getElementById(LBX_Members);
    if (!list) return false;

    const selectedIndex = list.selectedIndex;
    if (selectedIndex <= 0) return false; // already at top or nothing selected

    const option = list.options[selectedIndex];
    const firstOption = list.options[0];

    // Move the selected option before the first one
    list.insertBefore(option, firstOption);

    // Keep it selected
    option.selected = true;

    UpdateHiddenField(LBX_Members, HF_Selected);

    return false;
}


//function MoveBottom(LBX_Members, HF_Selected) {
//    var selectedOption = $('#' + LBX_Members + ' option:selected:last');
//    var lastOption = $('#' + LBX_Members + ' option:last');
//    if (!($(selectedOption).is($(lastOption))) && $(lastOption).text() != "") {
//        $(selectedOption).remove();
//        $(lastOption).after($(selectedOption));

//        UpdateHiddenField(LBX_Members, HF_Selected);
//    }

//    return false;
//}

function MoveBottom(LBX_Members, HF_Selected) {
    const list = document.getElementById(LBX_Members);
    if (!list) return false;

    const options = list.options;
    const selectedIndex = list.selectedIndex;
    if (selectedIndex < 0 || selectedIndex === options.length - 1) return false; // nothing selected or already last

    const option = options[selectedIndex];
    list.appendChild(option); // moves the selected option to the bottom
    option.selected = true;   // keep it selected

    UpdateHiddenField(LBX_Members, HF_Selected);

    return false;
}


//function UpdateHiddenField(LBX_Members, HF_Selected) {
//    var HT = HF_Selected.replace("HF_SelectedMembers", "HTxBx_SelectedMembers");
//    if (LBX_Members.toLowerCase().indexOf('lbx_selected') > -1) {
//        CopyAllListBoxItemsValueToHiddenField(HF_Selected, LBX_Members);
//    }
//    $('#' + HT).val($('#' + HF_Selected).val());

//    //alert($('#' + HF_Selected).val());
//}

function UpdateHiddenField(LBX_Members, HF_Selected) {
    const hf = document.getElementById(HF_Selected);
    if (!hf) return;

    const list = document.getElementById(LBX_Members);
    if (!list) return;

    // Update the hidden field if source list matches condition
    if (LBX_Members.toLowerCase().includes('lbx_selected')) {
        CopyAllListBoxItemsValueToHiddenField(HF_Selected, list);
    }

}


function AlertOnSaveIfCheckboxIsChecked(CheckBoxName, Msg) {

    var checkbox = document.getElementById(CheckBoxName);
    var confirm_value = document.createElement("INPUT");
    confirm_value.type = "hidden";
    confirm_value.name = "confirm_value";
    confirm_value.value = "No";
    document.forms[0].appendChild(confirm_value);
    if (checkbox.checked == true) {
        var Opt = confirm(Msg);
        if (Opt == true) {
            confirm_value.value = "Yes";
            document.forms[0].appendChild(confirm_value);
        }

    }
}

$("body").on("click", ".ShowHide", function () {
    $('#more-detail-panel').toggle();
});

$(document).ready(function () {

    if (window.PublicKeyCredential === undefined ||
        typeof window.PublicKeyCredential !== "function") {
        $('.passworless-controls').hide();
    }

    setTimeout(function () {
        if ($('#ctl00_CPH_Content_CB_CommissionBasedReseller')) {

            $('.Obout-Editor').addClass('hide');

            if ($('#ctl00_CPH_Content_CB_CommissionBasedReseller').attr('checked') == 'checked') {

                $('#ctl00_CPH_Content_CB_CommissionBasedReseller').parent().parent().parent().find('.Reseller-Panel').css("display", "''");

            }
            else {

                $('#ctl00_CPH_Content_CB_CommissionBasedReseller').parent().parent().parent().find('.Reseller-Panel').css("display", "none");
            }
        }

        if ($('#ctl00_CPH_Content_CB_SubscriptionBasedReseller')) {

            $('.Obout-Editor').addClass('hide');

            if ($('#ctl00_CPH_Content_CB_SubscriptionBasedReseller').attr('checked') == 'checked') {



                $('#ctl00_CPH_Content_CB_SubscriptionBasedReseller').parent().parent().parent().find('.Reseller-Panel').css("display", "''");

            }
            else {

                $('#ctl00_CPH_Content_CB_SubscriptionBasedReseller').parent().parent().parent().find('.Reseller-Panel').css("display", "none");
            }
        }
    }, 1000);


    $('.resellerterm-show-detail').on('click', function () {

        $(this).parent().find('.resellerterm-hide-detail').removeClass('hide');
        $(this).addClass('hide');
        $(this).parent().parent().find('.Obout-Editor').removeClass('hide');

    });

    $('.resellerterm-hide-detail').on('click', function () {

        $(this).parent().find('.resellerterm-show-detail').removeClass('hide');
        $(this).addClass('hide');
        $(this).parent().parent().find('.Obout-Editor').addClass('hide');

    });



    //End change text of accordion on expand and collapse       
    scopeInlineStyleTagsIfAny();

    //trigger blur event handler to fill default text
    $('.TypeToSearch').trigger('blur');
    HideDisabledCheckBoxListItems();

    $('input.hfclass, input.hfclass2').each(function () {
        if ($(this).val() && $(this).val() == 'expanded') {
            $(this).parent('div.collapsiblecontainer, div.collapsiblecontainer2').show();
        }
    });
    if ($('[data-toggle="tooltip"]').length != 0) {
        $('[data-toggle="tooltip"]').tooltip();
    }

    // Tooltip only Text
    $('.masterTooltip').hover(function () {
        // Hover over code

        var title = $(this).attr('title');
        $(this).data('tipText', title).removeAttr('title');
        //alert(title);
        $('<p class="tooltip"></p>')
            .text(title)
            .appendTo('body')
            .fadeIn('slow');
    }, function () {
        // Hover out code
        $(this).attr('title', $(this).data('tipText'));
        $('.tooltip').remove();
    }).mousemove(function (e) {
        var mousex = e.pageX + 20; //Get X coordinates
        var mousey = e.pageY + 10; //Get Y coordinates
        $('.tooltip')
            .css({ top: mousey, left: mousex })
    });

    $('.carousel-inner').each(function () {
        if ($(this).children('div').length === 1) $(this).siblings('.carousel-control, .carousel-indicators').hide();
    });

    $('.pager-row').each(function () {
        $(this).closest('tr').addClass("modal-col-white");
    });


    // Restricts input for each element in the set of matched elements to the given inputFilter.
    (function ($) {
        $.fn.inputFilter = function (inputFilter) {
            return this.on("input keydown keyup mousedown mouseup select contextmenu drop", function () {
                if (inputFilter(this.value)) {
                    this.oldValue = this.value;
                    this.oldSelectionStart = this.selectionStart;
                    this.oldSelectionEnd = this.selectionEnd;
                } else if (this.hasOwnProperty("oldValue")) {
                    this.value = this.oldValue;
                    this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
                }
            });
        };
    }(jQuery));


    // Install input filters.
    $(".allowonlyintegervalues").inputFilter(function (value) {
        return /^\d*$/.test(value);
    });
    $('.allowonlynumbers').keypress(function (event) {
        if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
            event.preventDefault();
        }
    });

    // wizard cancel button handling
    $(".wizard-cancel").on('click', function () {
        return ConfirmAction("Are you sure to cancel?");
    });

    $(function () {
        $('.password-group').find('.password-box').each(function (index, input) {
            var $input = $(input);
            $input.parent().find('.password-visibility').click(function () {
                //alert('clicked');
                var change = "";
                if ($(this).find('i').hasClass('icon-eye')) {
                    //alert('hidden');
                    $(this).find('i').removeClass('icon-eye')
                    $(this).find('i').addClass('icon-eye-slash')
                    change = "text";
                } else {
                    //alert('shown');
                    $(this).find('i').removeClass('icon-eye-slash')
                    $(this).find('i').addClass('icon-eye')
                    change = "password";
                }
                var rep = $("<input type='" + change + "' />")
                    .attr('id', $input.attr('id'))
                    .attr('name', $input.attr('name'))
                    .attr('class', $input.attr('class'))
                    .val($input.val())
                    .insertBefore($input);
                $input.remove();
                $input = rep;
            }).insertAfter($input);
        });
    });
});
var CurrentCultureDateFormat = "";
var DateInvalidMsg = "";

function SetCurrentCultureDateFormat(DateFormate, strDateInvalidMsg) {
    CurrentCultureDateFormat = DateFormate;
    DateInvalidMsg = strDateInvalidMsg;
}

function InitializeDate() {


    //It will enable datetextboxes and will check the Current Date format,
    //if it is not correct then will shoot and alert Msg and replace the date to current date in correct format.
    jQuery('.txBxDate').each(function () {
        $(this).attr('disabled', false);
        $(this).on('blur', function () {
            var Txtboxdate = $(this).val();
            if ((Date.parseExact(Txtboxdate, CurrentCultureDateFormat) == null) || (Date.parseExact(Txtboxdate, CurrentCultureDateFormat.replace("MM", "M").replace("dd", "d") == null))) // matching the provided date in textbox with current culture dateformat.
            {
                alert(DateInvalidMsg.replace("#Format", CurrentCultureDateFormat));
                $(this).val(Date.today().toString(CurrentCultureDateFormat));  //Placing today date in textbox and formating it to current culture date format.
            }
        });
    });
}

function HideDisabledCheckBoxListItems() {
    //Below code is used to hide the checkbox list items, checkboxlist item should have class name hide-disabled-items and the item which is ned to be hidden should be disabled.
    $('.hide-disabled-items').each(function () {
        $('span[disabled="disabled"]', $(this)).closest('tr').hide();
    });
    ///

    CheckUnCheckParent();
}

function CheckUnCheckParent() {
    $('.hide-disabled-items').each(function () {
        var $parentContext = $(this);

        var $headercheckbox = $parentContext.closest('tr').prev('tr.parent-checkbox').find('input[type=checkbox]');


        $headercheckbox.prop('checked', true);
        $parentContext.find('input[type=checkbox][disabled!="disabled"]').each(function () {

            if (!$(this).get(0).checked) {
                $headercheckbox.prop('checked', false);
            }


            $(this).on('click', function () {
                if (!$(this).get(0).checked) {

                    $headercheckbox.prop('checked', false);
                }
                else {

                    $headercheckbox.prop('checked', true);
                    $parentContext.find('input[type=checkbox][disabled!="disabled"]').each(function () {

                        if (!$(this).get(0).checked) {
                            $headercheckbox.prop('checked', false);
                        }
                    });
                }
            });


        });

    });
}

function enableDisableOnCheckChange(sourceCB, targetControl, enableOnCheck) {
    if ($('#' + sourceCB).is(':checked') && enableOnCheck)//enable on check and checkbox is checked
        $('#' + targetControl).removeAttr('disabled');
    else if (!$('#' + sourceCB).is(':checked') && !enableOnCheck) //enable on uncheck and checkbox is unchecked
        $('#' + targetControl).removeAttr('disabled');
    else
        $('#' + targetControl).attr('disabled', 'disabled');

    //$('#' + targetControl).selectpicker('refresh');
    initVirtualSelectPlugin('#' + targetControl);
}

function CB_EnableOnSelection(RB, CR) {

    var CBG = document.getElementById(RB);
    var CRG = document.getElementById(CR);
    $('#' + CR).attr('disabled', 'disabled');

    if (CBG.checked == true) {
        if (CRG.tagName === 'SELECT' || CRG.type === 'submit') {
        }
        else
            CRG.value = '';
        $('#' + CR).removeAttr('disabled');
        $('#' + CR).removeClass('disabled');
    }

    //$('#' + CR).selectpicker('refresh');
    initVirtualSelectPlugin('#' + CR);
}

//// remove multiple, leading or trailing spaces 
//function trim(txtId) {
//    var txt = document.getElementById(txtId);
//    var s = txt.value;
//    s = s.replace(/(^\s*)|(\s*$)/gi, "");
//    s = s.replace(/[ ]{2,}/gi, " ");
//    s = s.replace(/\n /, "\n");
//    txt.value = s;
//    alert(txt.value);
//}

//Accordian with plus and minus for O365Hosting.aspx page
function toggleIcon(e) {
    $(e.target)
        .prev('.panel-headings')
        .find(".more-less")
        .toggleClass('glyphicon-plus glyphicon-minus');
}
$('.panel-group').on('hidden.bs.collapse', toggleIcon);
$('.panel-group').on('shown.bs.collapse', toggleIcon);

//generic blink function
//param: selector: class (.myclass) or id (#myId)
//param: counter: start counter, set to 0
//param: repeat: number of repeat to blink an item
function blink(selector, counter, repeat) {
    if ($(selector).get(0) && counter < repeat) {
        $(selector).fadeOut('slow', function () {
            $(this).fadeIn('slow', function () {
                counter++;
                blink(this, counter, repeat);
            });
        });
    }
}

function bringOptionsColToStart() {
    var tableSelector = '.table.table-bordered.table-striped';
    if ($(tableSelector).find('tr').siblings('tr').find('td:last a[href]').length > 0) {
        removeClonnedOptionsCol();
        $(tableSelector).find('tr').each(function () {
            $this = $(this);
            if (!($this.closest("table").hasClass("small"))) {
                if ($this.find('th:last').length > 0) {
                    var $original_th = $this.find('th:last');
                    var $clonned_th = $original_th.clone();
                    $original_th.addClass('hide').hide();
                    $clonned_th.addClass('temp-th');
                    $this.prepend($clonned_th);
                }
                if ($this.find('td:last').length > 0) {
                    var $original_td = $this.find('td:last');
                    var $clonned_td = $original_td.clone();
                    $original_td.addClass('hide').hide();
                    $clonned_td.addClass('temp-td');
                    if ($clonned_td.find('ul.option-menu li.dropdown ul.dropdown-menu').length > 0)
                        $clonned_td.find('ul.option-menu li.dropdown ul.dropdown-menu').removeClass('pull-right').addClass('pull-left');
                    $this.prepend($clonned_td);
                }
            }

        });
    }
}

function removeClonnedOptionsCol() {
    var tableSelector = '.table.table-bordered.table-striped';
    $(tableSelector).find('.temp-td, .temp-th').remove();
    $(tableSelector).find('tr').find('td.hide:last').removeClass('hide').show();
    $(tableSelector).find('tr').find('th.hide:last').removeClass('hide').show();
}

var originalValidatorUpdateDisplay = window.ValidatorUpdateDisplay;
function extendedValidatorUpdateDisplay(obj) {
    // Calls the original method
    if (typeof originalValidatorUpdateDisplay === "function") {
        originalValidatorUpdateDisplay(obj);
    }
    // Retrieves control status (valid or invalid) 
    // And adds or removes the has-error class
    var control = document.getElementById(obj.controltovalidate);
    var validator;
    if (control) {
        var isValid = true;
        for (var i = 0; i < control.Validators.length; i += 1) {
            if (!control.Validators[i].isvalid) {
                isValid = false;
                validator = control.Validators[i];
                break;
            }
        }



        if ($(control).closest(".form-group").length < 1)
            control = validator;

        if (isValid) {
            $(control).closest(".form-group").removeClass("validation-failed");
        } else {
            setTimeout(function () { $('.page-loader-wrapper').hide(); }, 100);
            $(control).closest(".form-group").addClass("validation-failed");

            if ($(control).closest(".form-group").children('.form-line').length > 0)
                setTimeout(function () { $(control).closest(".form-group").children('.form-line').addClass('focused'); }, 100);
        }
    }
}

var DefaultValidatorReplaced = false;
function replaceWindowValidatorUpdateDisplay() {
    if (!DefaultValidatorReplaced) {
        DefaultValidatorReplaced = true;
        // Replaces the ValidatorUpdateDisplay method
        originalValidatorUpdateDisplay = window.ValidatorUpdateDisplay;
        window.ValidatorUpdateDisplay = extendedValidatorUpdateDisplay;
    }
}

function UnCheck_AllCheckbox_OnChildUnCheck(ChildCBId, AllCBId) {
    var ChildCB = document.getElementById(ChildCBId);
    var AllCB = document.getElementById(AllCBId);

    if (ChildCB.checked == false)
        AllCB.checked = false;
}


function HandleInputHtmlTags() {
    try {
        jQuery('.allowhtml, .ctl00_CPH_Content_TC_ExchangeAccounts_Pnl_Disclaimer_Disclaimer1_FTB_AppendedDisclaimer_HtmlBox').each(function () {
            var currentElement = $(this);
            var value = currentElement.val();
            value = value.replace(new RegExp("<", "g"), "&lt;");
            value = value.replace(new RegExp(">", "g"), "&gt;");
            currentElement.val(value);
        });
    }
    catch (err) { }

}

function findIdOrClassOfElementOrAnyParent($elem) {
    if ($elem.attr('id'))
        return '#' + $elem.attr('id');
    else if ($elem.attr('class'))
        return '.' + $elem.attr('class');
    else
        return findIdOrClassOfElementOrAnyParent($elem.parent());
}

function scopeInlineStyleTagsIfAny() {
    try {
        $('style').filter(function (i) {
            //if <style> tag is not in head tag, then it must be scoped to parent element
            //to avoid any UI css rules overriding bugs
            if ($(this).parent() && $(this).parent()[0] && $(this).parent()[0].tagName != 'HEAD')
                return true;
            else
                return false;
        }).each(function () {
            var styleSheet = $(this).get(0).sheet;
            var rulesList = styleSheet.rules ? styleSheet.rules : styleSheet.cssRules;
            var parentClassOrId = findIdOrClassOfElementOrAnyParent($(this).parent());
            var rulesToClone = new Array();
            for (var j = 0; j < rulesList.length; j++) {
                if (rulesList[j].selectorText)
                    rulesToClone.push(parentClassOrId + ' ' + rulesList[j].cssText);
                else
                    rulesToClone.push(rulesList[j].cssText);
            }
            $(this).html(rulesToClone.join('\n\r'));
        })
    }
    catch (e) { console.warn(e); }
}

//Morris graph JS Start
$(function () {
    eval($('#code').text());
    eval($('#code2').text());
    // prettyPrint();
});
//Morris graph JS end

function DigiCertCycleChange(Lbl, DDL, HF, S, gS, fMt) {
    var Lbl_Price = document.getElementById(Lbl);
    var Array = Lbl.split('Lbl_Price');
    var DDL_Cycles = document.getElementById(DDL);
    var HF_CurrencySymbol = document.getElementById(HF);
    var Values = DDL_Cycles.options[DDL_Cycles.selectedIndex].value.split('|');

    Lbl_Price.innerHTML = FormatLblPrice(Values[1], HF_CurrencySymbol.value + ' ', S, gS, fMt);

}

function synchAlerts(BaseURL, Data) {
    var param;
    param = "{Data:'" + Data + "'}";
    $.ajax({
        type: "POST",
        url: BaseURL + "/WebServices/VPS.asmx/SynchAlertOperations",
        data: param,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: synchAlertserrorHandlerOnSuccess,
        error: synchAlertserrorHandlererrorHandler
    });
    setTimeout(function () { synchAlerts(BaseURL, Data) }, 120000);
}

function synchVoiceCompany(BaseURL, NodeId) {
    var param;
    param = "{NodeId:'" + NodeId + "'}";
    $.ajax({
        type: "POST",
        url: BaseURL + "/WebServices/Voice.asmx/SyncCompany",
        data: param,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
            //Do Nothing
        },
        error: function (data) {
            //Do Nothing
        }
    });
}

function synchAlertserrorHandlererrorHandler(jqXHR, exception) {

    setNotificationVisibility(false);
}

function setNotificationVisibility(visibilityFlag) {
    //$get('dvCustomers').style.width = visibilityFlag ? 250 : 0;
    //$get('dvCustomers').style.height = visibilityFlag ? 450 : 0;
    if ($get('ctl00_LB_SeeMore') != null) {
        $get('ctl00_LB_SeeMore').innerHTML = visibilityFlag ? '>> See all' : 'No pending notifications';
        $get('ctl00_LB_SeeMore').href = visibilityFlag ? "javascript:__doPostBack('ctl00$LB_SeeMore','')" : '#';
    }
    if ($get('ctl01_LB_SeeMore') != null) {
        $get('ctl01_LB_SeeMore').innerHTML = visibilityFlag ? '>> See all' : 'No pending notifications';
        $get('ctl01_LB_SeeMore').href = visibilityFlag ? "javascript:__doPostBack('ctl01$LB_SeeMore','')" : '#';
    }

    if ($get('ctl00_Li_Alerts') != null && !visibilityFlag) {
        $('#ctl00_Lbl_SubsCount').attr('style', 'display:none');
        $('#ctl00_Li_Alerts').attr('style', 'display:none');
    }
    else if (visibilityFlag) {
        $('#ctl00_Lbl_SubsCount').attr("style", "display:''");
        $('#ctl00_Li_Alerts').attr("style", "display:''");
    }
}

function synchAlertserrorHandlerOnSuccess(response) {

    var recordCount = 0;
    var xmlDoc = $.parseXML(response.d);
    var xml = $(xmlDoc);
    var customers = xml.find("Alerts");
    $("#dvCustomers").html("");
    customers.each(function () {
        recordCount = recordCount + 1;
        var customer = $(this);
        rowCount = customer.find("Success").text();
        //alert(rowCount);
        $('#ctl00_Lbl_SubsCount').html(rowCount);
        //  var newBadge = "";
        if (rowCount > 0) {
            $('#ctl00_Lbl_SubsCount').removeAttr('style');
            //newBadge = '<span class="pull-right badge">New</span>';
        }
        else {
            $('#ctl00_Lbl_SubsCount').attr('style', 'display:none');
        }

        d = document.createElement('li');
        $(d).addClass('')
            .html(customer.find("Description").text())
            .appendTo($("#dvCustomers")) //main div
    });

    setNotificationVisibility((recordCount > 0));
}


//function MoveSelectableSelectedListItemsInChild(HF_List_ToChild, LBX_Selectable_ToChild, LBX_Selected_ToChild, HTxBx_Selected_ToChild,
//    LBX_Selectable_FromParent, LBX_Selected_FromParent, _HTxBx_Selected_FromParent, MoveOption, SortByValue) {

//    //hidden list 
//    var hiddenJsonData = $.parseJSON($('#' + HF_List_ToChild).val());

//    if (MoveOption == '1') {

//        $('#' + LBX_Selected_FromParent + " > option").each(function () {
//            var $this = this;
//            $.each(hiddenJsonData, function (index, element) {
//                if (element.CollectionName = $this.text) {
//                    //add to selectable if not exist
//                    if ($('#' + LBX_Selectable_ToChild + "  option[value='" + element.Alias + '|' + element.CollectionName + "']").length == 0 && $('#' + LBX_Selected_ToChild + "  option[value='" + element.Alias + '|' + element.CollectionName + "']").length == 0) {
//                        $('#' + LBX_Selectable_ToChild).append('<option value="' + element.Alias + '|' + element.CollectionName + '">' + element.Alias + ' [' + element.CollectionName + ']</option>');
//                    }
//                }
//            });
//        });
//    }

//    if (MoveOption == '2') {

//        $('#' + LBX_Selectable_FromParent + " > option").each(function () {
//            var $this = this;
//            $.each(hiddenJsonData, function (index, element) {
//                if (element.CollectionName = $this.text) {
//                    //remove from child selectable and selected if exist
//                    $('#' + LBX_Selectable_ToChild + "  option[value='" + element.Alias + '|' + element.CollectionName + "']").remove();
//                    $('#' + LBX_Selected_ToChild + "  option[value='" + element.Alias + '|' + element.CollectionName + "']").remove();
//                }
//            });
//        });
//    }

//    if (MoveOption == '3') {
//        $.each(hiddenJsonData, function (index, element) {
//            if (element.CollectionName = $('#' + LBX_Selected_FromParent + " > option:selected").text()) {
//                //add to selectable if not exist
//                if ($('#' + LBX_Selectable_ToChild + "  option[value='" + element.Alias + '|' + element.CollectionName + "']").length == 0) {
//                    $('#' + LBX_Selectable_ToChild).append('<option value="' + element.Alias + '|' + element.CollectionName + '">' + element.Alias + ' [' + element.CollectionName + ']</option>');
//                }
//            }
//        });
//    }

//    if (MoveOption == '4') {
//        $.each(hiddenJsonData, function (index, element) {
//            if (element.CollectionName = $('#' + LBX_Selectable_FromParent + " > option:selected").text()) {
//                //remove from child selectable and selected if exist
//                $('#' + LBX_Selectable_ToChild + "  option[value='" + element.Alias + '|' + element.CollectionName + "']").remove();
//                $('#' + LBX_Selected_ToChild + "  option[value='" + element.Alias + '|' + element.CollectionName + "']").remove();
//            }
//        });
//    }

//    //$('#' + LBX_From + ' option:selected').remove().appendTo('#' + LBX_To).prop('selected', false);

//    ////$('#' + LBX_To + ' option').prop('selected', false);

//    //var HT = HF_Selected.replace("HF_SelectedMembers", "HTxBx_SelectedMembers");

//    //if (LBX_From.toLowerCase().indexOf('lbx_selected') > -1) {
//    //    CopyAllListBoxItemsValueToHiddenField(HF_Selected, LBX_From);
//    //}
//    //else {
//    //    CopyAllListBoxItemsValueToHiddenField(HF_Selected, LBX_To);
//    //}

//    //$('#' + HT).val($('#' + HF_Selected).val());

//    if (SortByValue.toLowerCase() == 'true')
//        SortListBoxItemsByValue(LBX_Selectable_ToChild);
//    else
//        SortListBoxItemsByText(LBX_Selectable_ToChild);

//    return false;

//}

function PulseTypeChanged(DDL, DIV) {
    var Ddl_PulseType = document.getElementById(DDL);
    var Div = document.getElementById(DIV);
    Div.style.display = 'none';

    if (Ddl_PulseType.options[Ddl_PulseType.selectedIndex].value == "1")    // per second
    {
        Div.style.display = '';
    }
}

function AllowArrowKeysInFilteredTextBoxExtender(ControlId) {
    setTimeout(function () {
        if ($find(ControlId)) {
            var validChars = $find(ControlId).get_ValidChars();
            validChars = validChars + String.fromCharCode(37) + String.fromCharCode(39);
            $find(ControlId).set_ValidChars(validChars);
        }
    }, 500);
}

function CopyTxtValues(ParentID, Child1ID, Child2ID) {
    var TxBx_Parent = $get(ParentID);
    var TxBx_Child1 = $get(Child1ID); //Display Name
    var TxBx_Child2 = $get(Child2ID); //Unique Name                
    if (TxBx_Parent != null && TxBx_Child1 != null && TxBx_Child2 != null) {

        if (TxBx_Parent.value.toLowerCase().replace(/\s/g, '') == 'addneworganization') {
            TxBx_Parent.value = '';
        }

        var str = TxBx_Parent.value;
        while (str.lastIndexOf(' ') != -1) {
            str = str.replace(' ', '');
        }
        while (str.lastIndexOf(',') != -1) {
            str = str.replace(',', '');
        }
        while (str.lastIndexOf('.') != -1) {
            str = str.replace('.', '');
        }
        while (str.lastIndexOf('-') != -1) {
            str = str.replace('-', '');
        }
        while (str.lastIndexOf('_') != -1) {
            str = str.replace('_', '');
        }
        TxBx_Child1.value = TxBx_Parent.value.toString().replace('-', '_'); //Display Name can have spaces, and .
        TxBx_Child2.value = str;
    }
}

function RemoveInvalidStringsInOrgName(Id) {
    var Ctrl = document.getElementById(Id)

    if (Ctrl.value.toLowerCase().replace(/\s/g, '') == 'addneworganization') {
        Ctrl.value = '';
    }
}

/*function HandleStateOrProvinceValidators() {
    if (typeof Page_Validators != 'undefined') {
        for (i = 0; i < Page_Validators.length; i++) {
            if (Page_Validators[i] != null) {
                if (Page_Validators[i].controltovalidate.toString().match(/province/gi) || Page_Validators[i].controltovalidate.toString().match(/state/gi)) {
                    $get(Page_Validators[i].controltovalidate.toString()).value = 'NA';
                    ValidatorEnable(Page_Validators[i], false);
                }
            }
        }
    };
}

$(function () {
    if (typeof HandleStateOrProvinceValidators === "function")
        HandleStateOrProvinceValidators();
});

Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function (sender, args) {
    if (typeof HandleStateOrProvinceValidators === "function")
        HandleStateOrProvinceValidators();
});*/

function CopyDDLTextInTextbox(DDL, TB) {
    var txt = $('#' + TB);
    var selText = $("#" + DDL + " option:selected").text();
    var selValue = $("#" + DDL + " option:selected").val();

    //alert(selText);
    if (selValue != '-1')
        txt.val(selText + '\\');
    else
        txt.val('');
}

function HTTPRedirectorMethod(RBL, TXT) {
    var RBL_Method = document.getElementById(RBL);
    var TXT_Cloaked = document.getElementById(TXT);

    TXT_Cloaked.disabled = true;
    $(TXT_Cloaked).addClass('disabled');
    var SelectedOption = 0;

    var radio = RBL_Method.getElementsByTagName("input");
    for (var i = 0; i < radio.length; i++) {
        if (radio[i].checked) {
            SelectedOption = radio[i].value;
            break;
        }
    }

    if (SelectedOption == "2") {
        TXT_Cloaked.disabled = false;
        $(TXT_Cloaked).removeClass('disabled');
    }


}

function ShowDeletedClicked(DDLStatus) {

    var DDL = document.getElementById(DDLStatus);

    setTimeout(function () { DDL.selectedIndex = 0; $(DDL).trigger('change'); }, 500);
}

function CB_ShowWarningOnUncheck(CBEnableArchiveSettings) {
    var EnableArchiveSettings = document.getElementById(CBEnableArchiveSettings);

    if (EnableArchiveSettings.checked == false) {
        if (!confirm("This will remove archive mailbox permanently, please confirm to continue!")) {
            EnableArchiveSettings.checked = true;
        }
    }
}

function filterCommercialSaaSProds(txbx) {
    $('.search-js-prod-row').removeClass('hide');

    if (txbx.value != '' && txbx.value.length > 1) {
        var searchPattern = new RegExp(replaceSpecialChars(txbx.value), "gi");
        $('.search-js-prod-row').each(function () {
            $this = $(this);
            if (!$('.prod-title', $this).html().match(searchPattern))
                $this.addClass('hide');
            else
                $this.removeClass('hide');
        });
    }
}

function ShowCustomOption(DDL, DIV) {
    var Ddl_TimePeriod = document.getElementById(DDL);
    var Div = document.getElementById(DIV);

    Div.style.display = 'none';

    if (Ddl_TimePeriod.options[Ddl_TimePeriod.selectedIndex].value == "0")    // custom
    {
        Div.style.display = '';
    }
}

function triggerClick(popId) {
    $('#' + popId).trigger("click");
}

function O365GrantHelpIconPopover(iconId, popoverTitle, popoverContent) {
    $('#' + iconId).popover({
        title: popoverTitle, content: popoverContent, trigger: "hover", html: true, width: '450px', container: 'body'
    });
}


function isElementVisible(element) {
    return element.offsetWidth > 0 || element.offsetHeight > 0 || element.getClientRects().length > 0;
}

function hasVisibleElements(div) {

    div = document.getElementById(div);

    let hasVisibleElement = false;

    if (div) {

        const children = div.children;

        if (div.children) {

            for (let i = 0; i < children.length; i++) {
                if (isElementVisible(children[i]) && window.getComputedStyle(children[i]).visibility !== 'hidden' && window.getComputedStyle(children[i]).opacity !== '0') {
                    hasVisibleElement = true;
                    break;
                }
            }
        }
    }

    return hasVisibleElement;
}


function initVirtualSelect(selectId, hfOptions, hfSelectedText, btnAutoPostBack, hfSelectedValue, enabled, placeHolderText) {

    var DDLId = '#' + selectId;

    if (!document.querySelector(DDLId)) return;

    // Destroy if already initialized
    if (document.querySelector(DDLId).virtualSelect) {
        document.querySelector(DDLId).virtualSelect.destroy();
    }

    const optionsJson = document.getElementById(hfOptions).value;
    const parsed = optionsJson ? JSON.parse(optionsJson) : []; //JSON.parse(document.getElementById('<%= hfOptions.ClientID %>').value).filter(x => !x.l.toLowerCase().includes('dummy')),

    VirtualSelect.init({
        ele: DDLId,
        options: parsed,
        placeholder: placeHolderText,
        labelKey: 'l',
        valueKey: 'v',
        multiple: false,          // ✅ Only one item can be selected
        allowNewOption: false,    // Optional: prevent custom typing
        disableSelectAll: true,   // Optional: hides "Select All"
        search: true,             // Optional: enable search
        required: true,           // ✅ Makes it a required field
        hideClearButton: true    // ✅ Hides the “×” clear/remove icon
    });

    setTimeout(function () {
        {
            document.querySelector(DDLId).setValue(document.getElementById(hfSelectedValue).value);
            updateHiddenFields(selectId, hfSelectedText, btnAutoPostBack, hfSelectedValue);

            $(DDLId).change(function () {
                updateHiddenFields(selectId, hfSelectedText, btnAutoPostBack, hfSelectedValue);
            });
        }
    }, 300);

    if (enabled == 'false')
        $(DDLId).addClass('disabled').attr('disabled', true);

    // Ensure latest values before any postback (button click or form submit)
    document.addEventListener('submit', function () {
        updateHiddenFields(selectId, hfSelectedText, btnAutoPostBack, hfSelectedValue);
    });

}

// 🔹 Sync hidden fields with selection
function updateHiddenFields(selectId, hfSelectedText, btnAutoPostBack, hfSelectedValue) {

    const sel = document.getElementById(selectId);
    if (!sel) return;

    const vs = sel.virtualSelect;
    if (!vs) return;

    const hfTextEl = document.getElementById(hfSelectedText);
    const hfValueEl = document.getElementById(hfSelectedValue);
    const btn = document.getElementById(btnAutoPostBack);

    // Cache values once
    const newText = vs.getDisplayValue() || '';
    const newSelectedValue = vs.getValue() || '';

    if (!btn.disabled && (hfValueEl.value != newSelectedValue)) {
        hfTextEl.value = newText;
        hfValueEl.value = newSelectedValue;
        btn.click();
    }

    hfTextEl.value = newText;
    hfValueEl.value = newSelectedValue;

}

function EnableDisableTextBoxOnSpecificValue(DDL, DisableValue, TXT) {

    var selectedValue = $("#" + DDL).val();
    var txtCtrl = $("#" + TXT);

    if (selectedValue === DisableValue) {
        txtCtrl.val("1");
        txtCtrl.prop("disabled", true);
        txtCtrl.addClass("disabled");
    } else {
        txtCtrl.prop("disabled", false);
        txtCtrl.removeClass("disabled");
    }

}

//function initMultiSelectOptions(selectableSelect, selectedSelect, hfSelectableSelect, hfSelectedSelect) {

//    if (!document.querySelector('#' + hfSelectableSelect)) return;

//    let data = JSON.parse(document.getElementById(hfSelectableSelect).value || '[]');

//    let select = document.getElementById(selectableSelect);

//    select.classList.add("mp-multiselect");

//    // Clear existing options (optional)
//    select.innerHTML = "";
//    select.removeAttribute('name');

//    let opt = null;
//    // Loop through JSON and add options
//    data.forEach(item => {
//        opt = null;
//        opt = document.createElement("option");
//        opt.text = item.l;   // label
//        opt.value = item.v;  // value
//        if (item.s && item.s != '' && item.s == '1') {
//            $(opt).attr('syncing', item.s);
//            $(opt).attr('style', 'color: red')
//        }
//        select.add(opt);
//    });

//    data = JSON.parse(document.getElementById(hfSelectedSelect).value || '[]');

//    select = document.getElementById(selectedSelect);

//    select.classList.add("mp-multiselect");

//    // Clear existing options (optional)
//    select.innerHTML = "";
//    select.removeAttribute('name');

//    // Loop through JSON and add options
//    data.forEach(item => {
//        opt = null;
//        opt = document.createElement("option");
//        opt.text = item.l;   // label
//        opt.value = item.v;  // value
//        if (item.s && item.s != '' && item.s == '1') {
//            $(opt).attr('syncing', item.s);
//            $(opt).attr('style', 'color: red')
//        }
//        select.add(opt);
//    });
//    opt = null;

//}

function initMultiSelectOptions(selectableSelect, selectedSelect, hfSelectableSelect, hfSelectedSelect) {
    const hfSelectableEl = document.getElementById(hfSelectableSelect);
    const hfSelectedEl = document.getElementById(hfSelectedSelect);
    if (!hfSelectableEl || !hfSelectedEl) return;

    // Helper function to populate a select efficiently
    function populateSelect(selectId, jsonStr) {
        const select = document.getElementById(selectId);
        if (!select) return;

        select.classList.add("mp-multiselect");
        select.removeAttribute('name');

        // Parse JSON safely
        let data;
        try {
            data = JSON.parse(jsonStr || '[]');
        } catch {
            data = [];
        }

        // Clear existing options without innerHTML (less GC pressure)
        select.options.length = 0;

        // Use a DocumentFragment for minimal reflows
        //const fragment = document.createDocumentFragment();

        //for (let i = 0, len = data.length; i < len; i++) {
        //    const item = data[i];
        //    const opt = document.createElement("option");
        //    opt.text = item.l || '';
        //    opt.value = item.v || '';

        //    if (item.s === '1') {
        //        opt.setAttribute('syncing', '1');
        //        opt.style.color = 'red';
        //    }

        //    fragment.appendChild(opt);
        //}

        select.innerHTML = data.map(item =>
            `<option value="${item.v}" ${item.s === '1' ? 'style="color:red" syncing="1"' : ''}>${item.l}</option>`
        ).join('');


        //select.appendChild(fragment);
    }

    // Populate both lists
    populateSelect(selectableSelect, hfSelectableEl.value);
    populateSelect(selectedSelect, hfSelectedEl.value);
}

function initVirtualSelectPlugin(querySelector) {
    // Collect options from DropDownList ASP.NET rendered

    $(querySelector).each((index, element) => {
        setTimeout((i, e) => {
            $this = $(e);

            let ddl = $this.get(0);// document.getElementById($this.attr('id'));
            if (!ddl || !ddl.options)
                return;

            if (ddl.id == 'ddl-search-menu')
                return;//skip search menu ddl

            $parent = $this.parent();

            if (!ddl.id || ddl.id == '' || ddl.id == null || ddl.id == undefined) {
                ddl.id = 'ddl_vs_' + Math.ceil((i + 1) * 1000 * 10000 * Math.random() * Math.random()).toString();
            }

            let vsWrapperId = ddl.id + '_vsWrapper';

            let vsWrapper = document.getElementById(vsWrapperId);
            let pluginAlreadyInitialized = true;
            if (vsWrapper == null || vsWrapper == undefined || !vsWrapper) {
                vsWrapper = document.createElement('div');
                vsWrapper.id = vsWrapperId
                vsWrapper.classList.add('vscomp-ele');
                $parent.get(0).insertBefore(vsWrapper, $this.get(0).nextSibling);
                pluginAlreadyInitialized = false;
            }

            let items = Array.from(ddl.options).map(opt => ({
                label: opt.text,
                value: opt.value
            }));

            // Reference to VirtualSelect instance
            let vs = document.querySelector('#' + vsWrapper.id);

            if (pluginAlreadyInitialized)
                try {
                    vs.destroy();
                } catch (e) { }

            try {
                // Initialize VirtualSelect with extracted items
                VirtualSelect.init({
                    ele: '#' + vsWrapperId,
                    options: items,
                    search: true,
                    multiple: false,
                    hideClearButton: true,
                    disabled: ddl.disabled
                });
            }
            catch (e) {
                console.error('error:' + e.toString());
            }

            if (!pluginAlreadyInitialized) {
                // Hide the original ASP.NET select
                ddl.style.display = "none";

                // Sync VirtualSelect selection back to DropDownList
                vs.addEventListener('change', function (e) {
                    if (vs.value != ddl.value) {
                        ddl.value = vs.value;   // sets selected ASP.NET <select> value
                        //console.log('trigger change:' + ddl.id);
                        //$(ddl).trigger('change');
                        let event = new Event('change', { bubbles: true }); // Create a change event
                        ddl.dispatchEvent(event); // Dispatch the event
                    }
                });
            }

            // Optional: set initial selection from ASP.NET control
            if (ddl.value) {
                vs.setValue(ddl.value);
            }

        }, 10 + index * 10, index, element);
    });
}

function clearnUpInActiveTabPanels() {

    // Find all TabContainers via CSS classes added by AjaxControlToolkit
    $('.ajax__tab_container').each(function () {
        var containerId = $(this).attr('id');
        var tabContainer = $find(containerId);
        if (tabContainer && !tabContainer._initialized) {
            // Attach loaded event
            tabContainer.add_loaded(function (sender) {
                //console.log('TabContainer loaded:', sender.get_id());


                let inactiveTabs = document.querySelectorAll('.ajax__tab_panel[style*="display:none"], .ajax__tab_panel[style*="display: none"]');

                inactiveTabs.forEach((tab) => {

                    //console.log(tab);

                    Sys.Application.disposeElement(tab, true);

                    let contentPanels = Array.from(tab.querySelectorAll(`[id*="Pnl_TabContent"]`));

                    if (contentPanels && contentPanels.length > 0 && contentPanels[0].children && contentPanels[0].children.length > 0)
                        for (let i = 0; i < contentPanels[0].children.length; i++) {
                            let c = contentPanels[0].children[i];
                            try {
                                cleanElementEventsAndBindings(c, false);
                            } catch (e) { }
                        }
                    contentPanels = null;
                    tab = null;
                });
                inactiveTabs = null;


            });
            tabContainer._initialized = true;
        }
    });


}