
function loadHTML(file, containerId, enableCaching, maxAge) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', file, true);
    xhr.onreadystatechange = function () {
        if (this.readyState !== 4) return;
        if (this.status !== 200) return; // or whatever error handling you want
        document.getElementById(containerId).innerHTML = this.responseText;
    };
    if (enableCaching)
        xhr.setRequestHeader("Cache-Control", "max-age=" + maxAge ? 0 : maxAge.toString());
    xhr.send();
}

var LocalPostBackLoader = false;

function SearchOption() {
    var HF_SearchOption = document.getElementById("ctl00_HF_SearchOption");
    var selectBox = document.getElementById("selectBox");
    HF_SearchOption.value = selectBox.options[selectBox.selectedIndex].value;
}

function HideResellerOptions(CompanyId) {
    if (CompanyId != "1") {
        var selectBox = $get('selectBox');
        if (selectBox) {
            var child = $get('ResellerGroup');
            selectBox.removeChild(child);
        }
    }
}

function Load(CompanyId) {

    if (CompanyId != "1") {
        var selectBox = $get('selectBox');
        if (selectBox) {
            var child = $get('ResellerGroup');
            selectBox.removeChild(child);
        }
    }

    var HF_Ajax = document.getElementById('HF_Ajax');

    if (HF_Ajax) {

        if (HF_Ajax.value != '0') {
            if (window.location.indexOf("?") > -1) {
                document.location = window.location + "&Tab=" + HF_Ajax.value;
            }
            else {
                document.location = window.location + "?Tab=" + HF_Ajax.value;
            }
        }
    }
}

function smallImg(BaseURL, EmpId, IsEmp, CImg) {
    //var HF_Visited = document.getElementById("ctl00_HF_Visited");
    //HF_Visited.value = '0';
    //location.reload();
    //alert("IN: " + EmpId + " : " + IsEmp);
    var CountImage = document.getElementById(CImg);
    try {

        var param;

        param = "{EmployeeId:'" + EmpId + "',IsEmployee:'" + IsEmp + "'}";

        $.ajax(

            {
                type: "POST",
                url: BaseURL + "/WebServices/VPS.asmx/UpdateAlertViewedOn",
                data: param,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {
                    if (msg.d) {
                        //Success
                        //alert(msg.d);
                        //console.log(JSON.stringify(msg));
                        CountImage.innerHTML = '';
                        //CountImage.style.display = 'none';
                    }
                }
            });
    }
    catch (err) {
        if (CountImage) {
            CountImage.innerHTML = '';
            CountImage.style.display = 'none';
        }
    }
}

function adjustmodalpopupforscreen() {


    $('.width-modal-popup-auto').each(function () {

        $modal = $(this);

        $modal.css('left', $(window).width() <= 768 ? '5%' : ((screen.availWidth / 2) - ($modal.width() / 2)));
        $modal.css('top', $(window).height() <= 300 ? '10%' : ((screen.availHeight / 2) - ($modal.height() / 2)));

        //hieght of modal is set to 80% of the screen in css
        //height of body cannot be given in percent as its position must be relative an not absolute/fixed
        //hence we need to find the 80% of the screen in pix and minus the header and footer heights
        $modal.find('.card').filter(':first').children('.body').css('max-height', ($(window).height() / 100) * 80 - 100);

        $modal.find('.card').filter(':first').children('.directrouting').css('max-height', ($(window).height() / 100) * 80 - 130);

    });
}

function AdminBSBThemeChanges() {

    //AdminBSB Theme Changes:
    ModifyTabControlCssClasses();

    $('.row-label').each(function () {//Add div content in label to adjust display where Lael column data is not added in label control

        if ((!($(this).children('label').length)) && ($(this).next().find('input').length || $(this).next().find('select').length)) {
            $(this).html('<label>' + $(this).html() + '</label>');
        }

    });

    $('.modalBackground, .width-modal-popup-auto').css('position', 'fixed');

    $('.width-modal-popup-auto').css('left', $(window).width() <= 768 ? '5%' : (($(window).width() - $('.width-modal-popup-auto').width()) / 2));
    $('.width-modal-popup-auto').css('top', $(window).height() <= 300 ? '10%' : (($(window).height() - $('.width-modal-popup-auto').height()) / 8));


    $('.width-modal-popup-auto').each(function () {
        $modal = $(this);
        //hieght of modal is set to 80% of the screen in css
        //height of body cannot be given in percent as its position must be relative an not absolute/fixed
        //hence we need to find the 80% of the screen in pix and minus the header and footer heights
        $modal.find('.card').filter(':first').children('.body').css('max-height', ($(window).height() / 100) * 80 - 100);
        $modal.find('.card').filter(':first').children('.directrouting').css('max-height', ($(window).height() / 100) * 80 - 130);
        $modal.find('.card').filter(':first').children('.body').css('overflow-y', 'auto');
        $modal.find('.card').filter(':first').children('.body').css('overflow-x', 'hidden');
    });

    setTimeout(function () {
        let c = Sys.Application.getComponents();
        for (var i = 0; i < c.length; i++) {
            //console.log(c[i]);
            let id = c[i].get_id();
            let type = Object.getType(c[i]).getName();
            if (type == 'AjaxControlToolkit.ModalPopupBehavior') {
                var modalPopup = $find(id);
                modalPopup.add_shown(function () {
                    //console.log('adjustmodalpopupforscreen');
                    adjustmodalpopupforscreen();
                    //modalPopup._backgroundElement.addEventListener("click", function () {
                    //    modalPopup.hide();
                    //});
                });

            }
        }
    }, 1000);

    $(window).on('scroll resize', function () {
        adjustmodalpopupforscreen();
    });

    //disable body scroll when inside modal popup.
    $('.width-modal-popup-auto').mouseenter(function (event) {
        $('body').css('overflow', 'hidden');
    }).mouseleave(function (event) {
        $('body').css('overflow', '');
    });

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

    $('.form-group .selectpicker').addClass('form-control');

    //for modal popup we don't need to set container for bootstrap select plugin
    //as it hides behind the modal
    //if container is set then html of the inner menu for select option is appended at the end of the document
    //and positioned dynamically (absolute) with x,y positioning.
    //otherwise plugin inner menu is appended in the parent control of the original select option.
    $('select:not(.ms, .HE_top_bar select, .width-modal-popup-auto select)').attr("data-container", "body");

    //$('select:not(.ms, .HE_top_bar select)').selectpicker();
    initVirtualSelectPlugin('select:not(.ms, .HE_top_bar select)')


    $('input[type = checkbox]').addClass("filled-in");
    $('input[type = radio]').addClass("with-gap");
    $('input[type = text]').addClass("form-control");
    $('input[type = password]').addClass("form-control form-password");

    $('.form-control.form-password').on('keyup change blur focus', function () {
        if ($(this).val().indexOf('<') != -1 || $(this).val().indexOf('>') != -1) {
            $(this).val('');
            $(this).focus();
            alert('greater then ">" and less then "<" symbols are not allwoed in passwords.');
        }
        //e.preventDefault();
    });

    $('.form-float .form-line').each(function () {

        $parent = $(this);

        if ($parent.find('input[type=text]').val() != '' && $parent.find('input[type=text]').val() != undefined)
            $parent.addClass("focused");

        if ($parent.find('input[type=password]').val() == '' && $parent.find('input[type=password]').val() == undefined)
            $parent.removeClass("focused");

    });

    $('input[type = checkbox]').each(function () {
        if ($(this).closest(".form-group").length) {
            $(this).closest("div").parent("div").css("top", "7px");
        }
        else {
            $(this).parent("span").parent("div").css("top", "7px");
            $(this).parent("div").css("top", "7px");
        }
    });

    //Tooltip
    $('[data-toggle="tooltip"]').tooltip({
        container: 'body'
    });

    //Popover
    $('[data-toggle="popover"]').popover();


    //Handling Select All checkbox, example usage in ClientsList Page.
    $('label').each(function () {
        if (($(this).prev().is("input[type='radio']") || ($(this).prev().is("input[type='checkbox']")))) {
            $(this).attr("for", $(this).prev().attr('id'));
            if ($(this).closest("table").hasClass("no-padding")) {
                $(this).attr("style", "padding-right:20px;");
            }
        }
    });

    //AdminBSB Theme Changes End

    //double horizontal scroll for expanded table/div
    SetDoubleScroll()

    $('[role="tabpanel"]').each(function () {

        if ($(this).hasClass('collapse') || $(this).hasClass('panel-collapse')) {

            $(this).prev().addClass('collapsed');

        }

    });


    //Fix: Search panel on search comes expanded but "+" icon appears instead of "-"
    loadSearchPanelPreferences();


    setTimeout(function () { if ($(window).width() < 768) bringOptionsColToStart(); }, 100);
    $(window).on('resize', function () {
        if ($(this).width() < 768)
            bringOptionsColToStart();
        else
            removeClonnedOptionsCol();
    });

    replaceWindowValidatorUpdateDisplay();

    initSearchPanelToggleEvent();

    $('th .option-menu, td .option-menu').each(function () {

        $(this).parent().addClass('align-center');

    });

    //code for open option-menu onmouseover
    $('.option-menu').hover(optionMenuMouseHoverHandler);

    $('.option-menu').mouseleave(optionMenuMouseLeaveHandler);

    wrapGrids();
}

function initSearchPanelToggleEvent() {
    setTimeout(() => {
        $(".panel-group.search-panel .header")
            .click(
                function () {
                    let $this = $(this);

                    setTimeout(($headerCtrl) => {

                        var BaseURL = $(location).attr('protocol') + '//' + $(location).attr('host');

                        var param;

                        var IsCollapsed = false;

                        if ($headerCtrl.hasClass("collapsed"))
                            IsCollapsed = true;


                        param = "{SearchPanelURL:'" + $(location).attr('href') + '/' + $headerCtrl.attr('href') + "', IsCollapsed:'" + IsCollapsed + "'}";

                        $.ajax({
                            type: "POST",
                            url: BaseURL + "/WebServices/VPS.asmx/SaveSearchPanelCollapsed",
                            data: param,
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",
                            success: function () { },
                            error: function () { console.log("Search preference save failed: " + param); }
                        });

                    }, 100, $this);

                });
    }, 50);

}

function loadSearchPanelPreferences() {
    setTimeout(() => {
        $(".panel-group.search-panel").each(function () {

            //if ($(this).find(".body").hasClass("collapse") && $(this).find(".body").hasClass("in")) {
            //    $(this).find(".header").removeClass("collapsed");
            //    //console.log('removed from header');
            //}

            var BaseURL = $(location).attr('protocol') + '//' + $(location).attr('host');

            var param;

            param = "{SearchPanelURL:'" + $(location).attr('href') + '/' + $(this).find(".header").attr('href') + "', Id:'" + $(this).attr('Id') + "'}";

            $.ajax({
                type: "POST",
                url: BaseURL + "/WebServices/VPS.asmx/GetSearchPanelCollapsed",
                data: param,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {

                    if (response.d.IsCollapsed == true) {
                        //Collapsed search panel

                        if ($('#' + response.d.Id).find(".body").hasClass("collapse") && $('#' + response.d.Id).find(".body").hasClass("in")) {//Expanded already                        
                            //$('#' + response.d.Id).find(".header").trigger('click');//Click to hide
                            $('#' + response.d.Id).find(".header").addClass('collapsed');
                            $('#' + response.d.Id).find(".body").collapse('hide');//Click to hide
                        }

                    }
                    else {

                        //Expand search panel            
                        if ($('#' + response.d.Id).find(".body").hasClass("in") == false) {//Not already expanded.
                            //$('#' + response.d.Id).find(".header").trigger('click');//Click to show
                            $('#' + response.d.Id).find(".header").removeClass('collapsed');
                            $('#' + response.d.Id).find(".body").collapse('show');//Click to show
                            //console.log('removed from header22');
                        }

                    }

                },
                error: function () { console.log("Search preference get failed: " + param); }
            });

        });
    }, 100);
}

function convertBrowserAgentToWebKit() {
    //For loading issues fix, in chrome some pages struck on loading, error in console is: cannot Read Property '_notified' of Null
    Sys.Browser.WebKit = {};
    if (navigator.userAgent.indexOf('WebKit/') > -1) {
        Sys.Browser.agent = Sys.Browser.WebKit;
        Sys.Browser.version = parseFloat(navigator.userAgent.match(/WebKit\/(\d+(\.\d+)?)/)[1]);
        Sys.Browser.name = 'WebKit';
    }
    //End 
}

function handleServerDisabledControls() {
    $("*[data-server-state='disabled']").each(function () {
        $(this).addClass('disabled');
        $(this).attr("disabled", "disabled");
    }
    );
}


//function initRequestHandler(sender, args) {

//    var target = "";
//    if (sender && sender._postBackSettings && sender._postBackSettings.asyncTarget != '')
//        target = sender._postBackSettings.asyncTarget;

//    if (target != '')
//        target = target.toLowerCase();

//    if (target != '' && (target.endsWith('cancel') || target.includes('$btn_tab') || target.includes('$lb_'))) {

//        if (target.includes('$lb_') && !document.getElementById(sender._postBackSettings.asyncTarget.replaceAll('$', '_')).parentElement.classList.contains('label-default'))
//            return;

//        var HF_SelectedMembers = "";

//        $(".mp-multiselect").each(function () {

//            if ($(this).attr('name') && $(this).attr('name').endsWith('HF_SelectedMembers'))
//                HF_SelectedMembers = $(this).attr('name').replaceAll('$', '%24');

//            $(this).val('');

//        });

//        if (HF_SelectedMembers != '') {
//            var HF_DummyEndField = HF_SelectedMembers.replace('HF_SelectedMembers', 'HF_DummyEndField');

//            let req = args.get_request();
//            let body = req._body;

//            req._body = body.substring(0, body.indexOf(HF_SelectedMembers)) + body.substring(body.indexOf(HF_DummyEndField));
//        }
//    }
//}

function ScrollTopIfError() {
    if (($('.errorMsg').get(0)) || ($('.infoMsg').get(0)) || ($('.warnMsg').get(0)) || ($('.successMsg').get(0) && $('.successMsg').html() != '')) {
        $('html,body').animate({ scrollTop: 10 }, 500);
    }
}

function ScrollToTopOfPage() {

    $('html,body').animate({ scrollTop: $('#ctl00_MasterBody').position().top }, 100);

}

function HandlePassAutoFill() {

    $("#DummyUserId").val("");
    $("#DummyPassword").val("");

}

function ModifyTabControlCssClasses() {

    $(".ajax__tab_xp").each(function () {

        $(this).removeAttr('class');

    });

    $('.ajax__tab_header').removeClass('ajax__tab_header').addClass('TabControlTabHeader');

    $(".ajax__tab_active").find('.ajax__tab_tab').removeClass('ajax__tab_tab').addClass('TabControlTab');

    $('.ajax__tab_tab').removeClass('ajax__tab_tab').addClass('TabControlTabInActive');

    $(".ajax__tab_body").removeClass('ajax__tab_body').addClass('TabControlTabBody');

}

function isEmpty(str) {
    return (!str || 0 === str.length);
}

Sys.UI.Point = function Sys$UI$Point(x, y) {
    x = Math.round(x);
    y = Math.round(y);

    var e = Function._validateParams(arguments, [
        { name: "x", type: Number, integer: true },
        { name: "y", type: Number, integer: true }
    ]);
    if (e) throw e;
    this.x = x;
    this.y = y;
}

Sys.WebForms.PageRequestManager.prototype['_onFormElementActive'] = function Sys$WebForms$PageRequestManager$_onFormElementActive(element, offsetX, offsetY) {
    if (element.disabled) {
        return;
    }
    this._postBackSettings = this._getPostBackSettings(element, element.name);
    if (element.name) {
        var tagName = element.tagName.toUpperCase();
        if (tagName === 'INPUT') {
            var type = element.type;
            if (type === 'submit') {
                this._additionalInput = encodeURIComponent(element.name) + '=' + encodeURIComponent(element.value);
            }
            else if (type === 'image') {
                offsetX = Math.round(offsetX);
                offsetY = Math.round(offsetY);
                this._additionalInput = encodeURIComponent(element.name) + '.x=' + offsetX + '&' + encodeURIComponent(element.name) + '.y=' + offsetY;
            }
        }
        else if ((tagName === 'BUTTON') && (element.name.length !== 0) && (element.type === 'submit')) {
            this._additionalInput = encodeURIComponent(element.name) + '=' + encodeURIComponent(element.value);
        }
    }
}

setTimeout(function () { blink('.sys-alert', 0, 2); }, 1000);

function SetDoubleScroll() {
    if ($(".double-scroll-wrapper2 table").get(0)) {
        var tableWidth = $(".double-scroll-wrapper2 table").get(0).style.width;

        if (tableWidth == null || tableWidth == 0) {
            tableWidth = $(".double-scroll-wrapper2 table").get(0).getBoundingClientRect().width;
        }

        $(".double-scroll-wrapper2 div").first().width(tableWidth);

        $(".double-scroll-wrapper1 div").first().width(tableWidth);

        //$(".double-scroll-wrapper2").height($(".double-scroll-wrapper2 div").first().height());

        $(".double-scroll-wrapper1").scroll(function () {
            $(".double-scroll-wrapper2")
                .scrollLeft($(".double-scroll-wrapper1").scrollLeft());
        });

        $(".double-scroll-wrapper2").scroll(function () {
            $(".double-scroll-wrapper1")
                .scrollLeft($(".double-scroll-wrapper2").scrollLeft());
        });

        //$(".double-scroll-wrapper2 table .pager-row").width($(".breadcrumb-custom").width() - 20);

        $pagerrow = $(".double-scroll-wrapper2 table .pager-row").clone();

        $(".double-scroll-wrapper2 table .pager-row").remove();

        $(".double-scroll-wrapper2").parent().append($pagerrow);

    }
    if ($(".double-scroll-wrapper4 table").get(0)) {
        var tableWidth = $(".double-scroll-wrapper4 table").get(0).style.width;

        if (tableWidth == null || tableWidth == 0) {
            tableWidth = $(".double-scroll-wrapper4 table").get(0).getBoundingClientRect().width;
        }

        $(".double-scroll-wrapper4 div").first().width(tableWidth);

        $(".double-scroll-wrapper3 div").first().width(tableWidth);

        //$(".double-scroll-wrapper2").height($(".double-scroll-wrapper2 div").first().height());

        $(".double-scroll-wrapper3").scroll(function () {
            $(".double-scroll-wrapper4")
                .scrollLeft($(".double-scroll-wrapper3").scrollLeft());
        });

        $(".double-scroll-wrapper4").scroll(function () {
            $(".double-scroll-wrapper3")
                .scrollLeft($(".double-scroll-wrapper4").scrollLeft());
        });

        //$(".double-scroll-wrapper2 table .pager-row").width($(".breadcrumb-custom").width() - 20);

        $pagerrow = $(".double-scroll-wrapper4 table .pager-row").clone();

        $(".double-scroll-wrapper4 table .pager-row").remove();

        $(".double-scroll-wrapper4").parent().append($pagerrow);

    }
}

$(document).ready(function () {
    $(".pager-row")
        .parent("td").addClass("parent-pager-row");

    handleServerDisabledControls();
    /*$('[id*="Lbl_Organization"]').each(function () {
 
        var DDL_AL = $(this).parent().parent().parent().find('select[Id$="DDL_AL"]');
 
        if (DDL_AL != null) {
 
            DDL_AL.val($(this).text() + " AL");
 
            $(this).parent().parent().parent().find('[Id$="TxBx_DomainName"]').val($(this).text());
 
            $(this).parent().parent().parent().find('select[Id$="DDL_GAL"]').val($(this).text() + " GAL");
            $(this).parent().parent().parent().find('select[Id$="DDL_RAL"]').val($(this).text() + " Rooms AL");
            $(this).parent().parent().parent().find('select[Id$="DDL_OAB"]').val($(this).text() + " OAB");
            $(this).parent().parent().parent().find('select[Id$="DDL_ABP"]').val($(this).text() + " ABP");
 
            setTimeout(function () { initVirtualSelectPlugin('select:not(.ms, .HE_top_bar select)'); }, 500);
 
        }
    });*/

    $('.width-modal-popup-auto').on('visibility', function () {
        var $element = $(this);
        var timer = setInterval(function () {
            if ($element.is(':visible')) {
                //$('html,body').animate({ scrollTop: 10 }, 500);
                //console.log('visiblity');
                adjustmodalpopupforscreen();
            }
        }, 2000);
    }).trigger('visibility');

    convertBrowserAgentToWebKit();

    setCookie('JSEnabled', '1', 7);
    $('[id*=noscript_div]').hide();

    //InitializeMenu();

    setTimeout(HandlePassAutoFill, 10);

    InitializeDate();

    AdminBSBThemeChanges();

    //Needed for Material design effect on Ajax call back.
    $.AdminBSB.input.activate();
    setTimeout(function () { $.AdminBSB.dropdownMenu.activate(); }, 100);

    ScrollTopIfError();

    $('#notification-carousel').carousel({
        interval: 4000
    });

    $('#chatContainer').removeClass('hide').show('blind', null, 700);

    $('#notification-carousel .carousel-inner .caption').slimScroll({
        height: '100px',
        size: '6px',
        color: 'rgba(4,4,4,0.5)',
        alwaysVisible: true,
        borderRadius: '3',
        railBorderRadius: '3',
        smoothWheelScroll: false
    });

    $("#notification-carousel").on('slid.bs.carousel', function () {
        $('#notification-carousel .carousel-inner .caption').slimScroll({ scrollTo: 0 });
    });

    //show progress bar on click of navigation links also. 
    //handler is written in 'utility.js' file
    jQuery("a").each(anchorClickShowProgressHandler);

    document.forms[0].onsubmit = function (e) {

        HandleInputHtmlTags();
        if ((typeof Page_IsValid == 'undefined') ||      // asp page has no validator
            (Page_IsValid != null && Page_IsValid && LocalPostBackLoader == false)) {
            $('.page-loader-wrapper').show();
        }
    }

    jQuery("input[type=text], textarea").keyup(function (event) {
        //skip freetextbox htmleditor control
        var str = $(this)[0].className;
        if (!(str.match(/_HtmlBox/g) || str.match(/allowhtml/g))) {
            txtValue = $(this).val();
            txtValue = txtValue.replace(/[\<\>]+/g, '');
            if (txtValue != $(this).val()) {
                $(this).val(txtValue);
            }
        }

    });

    setTimeout(function () { adjustmodalpopupforscreen(); }, 200);

    clearnUpInActiveTabPanels();

});


//https://learn.microsoft.com/en-us/previous-versions/aspnet/bb398976(v=vs.100)
//PageRequestManager Events Lifecycle
(function () {
    function injectCustomPageRequestHandlers() {
        if (typeof Sys === 'undefined' || !Sys.WebForms || !Sys.WebForms.PageRequestManager) {
            setTimeout(injectCustomPageRequestHandlers, 100);
            return;
        }

        var prm = Sys.WebForms.PageRequestManager.getInstance();

        /*
        Raised before the request is initialized for an asynchronous postback. Event data is passed to handlers as an InitializeRequestEventArgs object. 
        The object makes available the element that caused the postback and the underlying request object.
        */
        prm.add_initializeRequest(function (sender, args) {

            // Guard: skip if sender or settings are missing
            if (!sender || !sender._postBackSettings) return;

            //console.log(sender);
            //console.log(args);

            const settings = sender._postBackSettings;
            let target = settings.asyncTarget || "";
            if (!target) return;

            target = target.toLowerCase();

            // Skip unnecessary processing
            if (!target.endsWith('cancel') &&
                !target.includes('$btn_tab') &&
                !target.includes('$lb_') &&
                !target.includes('goback')) return;

            // Handle listbox target case
            if (target.includes('$lb_') && !target.includes('goback')) {
                const el = document.getElementById(settings.asyncTarget.replaceAll('$', '_'));
                if (!el || !el.parentElement.classList.contains('label-default')) return;
            }

            // Find the hidden field name once
            let HF_SelectedMembers = null;

            const selects = document.getElementsByClassName('mp-multiselect');
            for (let i = 0; i < selects.length; i++) {
                const el = selects[i];
                const name = el.getAttribute('name');
                el.value = ''; // reset directly — avoids jQuery overhead

                if (name && name.endsWith('HF_SelectedMembers')) {
                    HF_SelectedMembers = name.replaceAll('$', '%24');

                    const HF_DummyEndField = HF_SelectedMembers.replace('HF_SelectedMembers', 'HF_DummyEndField');
                    const req = args.get_request();
                    const body = req._body;

                    const start = body.indexOf(HF_SelectedMembers);
                    const end = body.indexOf(HF_DummyEndField);

                    req._body = body.slice(0, start) + body.slice(end);

                    HF_SelectedMembers = name.replaceAll('$', '_');

                    $('#' + HF_SelectedMembers.replace('HF_SelectedMembers', 'LBX_SelectableMembers')).off().removeData();
                    $('#' + HF_SelectedMembers.replace('HF_SelectedMembers', 'LBX_SelectedMembers')).off().removeData();

                }

            }

        });

        /*
        Raised just before the asynchronous postback is sent to the server. Event data is passed to handlers as a BeginRequestEventArgs object. 
        The object makes available the element that caused the postback and the underlying request object.
        */
        prm.add_beginRequest(function (sender, args) {

            convertBrowserAgentToWebKit();

            HandleInputHtmlTags();
            if (LocalPostBackLoader == false)
                $('.page-loader-wrapper').show();

            //let updatedPanels = sender._updatePanelClientIDs;
            //if (updatedPanels && updatedPanels.length) {
            // updatedPanels.forEach(panelId => { console.log(panelId); cleanUpdatePanelHeap(document.getElementById(panelId), true); });
            //}

            //args.get_panelsUpdating().forEach(function (panel) {
            //    try {
            //        cleanUpdatePanelHeap(panel, true);
            //    } catch (e) {
            //        console.warn('Cleanup failed for', panel, e);
            //    }
            //});

        });

        /*
        Raised after the response to the most recent asynchronous postback has been received but before any updates to the page have been made.
        Event data is passed to handlers as a PageLoadingEventArgs object.The object makes available information about what panels will be deleted and updated as a result of the most recent asynchronous postback.
        */

        prm.add_pageLoading(function (sender, args) {
            args.get_panelsUpdating().forEach(function (panel) {
                try {
                    //console.log('loading....' + panel.id);
                    cleanUpdatePanelHeap(panel, true);
                } catch (e) {
                    console.warn('Cleanup failed for', panel, e);
                }
            });
        });

        /*
        Raised after page regions are updated after the most recent postback. Event data is passed to handlers as a PageLoadedEventArgs object. 
        The object makes available information about what panels were created or updated. For synchronous postbacks, panels can only be created, but for asynchronous postbacks, panels can be both created and updated.
        */
        //prm.add_pageLoaded(function (sender, args) {
        //
        //});

        /*Raised when request processing is finished. Event data is passed to handlers as an EndRequestEventArgs object. 
        The object makes available information about errors that have occurred and whether the error was handled. It also makes available the response object.
        */
        prm.add_endRequest(function (sender, args) {

            $(".pager-row").parent("td").addClass("parent-pager-row");

            handleServerDisabledControls();

            convertBrowserAgentToWebKit();

            InitializeDate();

            HideDisabledCheckBoxListItems();

            AdminBSBThemeChanges();

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

            //Needed for Material design effect on Ajax call back.
            $.AdminBSB.input.activate();
            setTimeout(function () { $.AdminBSB.dropdownMenu.activate(); }, 100);
            //AdminBSB Theme Changes  End

            error = args.get_error();
            if (args.get_error() == undefined) {

                // Your normal code goes here
                jQuery("input[type=text], textarea").keyup(function (event) {
                    //skip freetextbox htmleditor control
                    var str = $(this)[0].className;
                    if (!(str.match(/_HtmlBox/g) || str.match(/allowhtml/g))) {
                        txtValue = $(this).val();
                        txtValue = txtValue.replace(/[\<\>]+/g, '');
                        if (txtValue != $(this).val()) {
                            $(this).val(txtValue);
                        }
                    }

                });


                ////set right to left alignment when using persian language/locale
                //try {
                //    if ($("html").attr("dir").toUpperCase() == 'RTL')
                //        setRtlAlignment($("html").attr("dir"));
                //} catch (e) { }
            }
            else {
                //IN Exchange we load graph async, wile graph is being loaded and one click on other tab, alert was appearing, aded below check to avoid that message to appear.
                if (!error.message.match(/status code returned from the server was: 0/i)) {


                    if (!(window.location.href.toLowerCase().indexOf("/store/") > -1)) {
                        alert(args.get_error()); // Do something }
                    }

                }
                args.set_errorHandled(true);



            }

            ScrollTopIfError();
            replaceWindowValidatorUpdateDisplay();
            setTimeout(function () { adjustmodalpopupforscreen(); }, 200);

            try {
                $('.fileupload').parent().fileupload();
            } catch (e) { }

            clearnUpInActiveTabPanels();

        });

        /*
        Ajax Client Side Events
        https://learn.microsoft.com/en-us/previous-versions/aspnet/bb386417(v=vs.100)
        Raised before all objects are disposed and before the browser window's window.unload event occurs.
        create a function that which provides a handler for the unload event. 
        The pageUnload event is called just before the page is unloaded from the browser. 
        During this event, can free any resources that code is holding.
        */

    }
    injectCustomPageRequestHandlers();
})();


//window.addEventListener('beforeunload', function (e) {

//    //cleanUpdatePanelHeap(document.querySelector("section.content div.MainContextArea"), false);
//});

//window.addEventListener('unload', function () {

//    //cleanUpdatePanelHeap(document.querySelector("section.content div.MainContextArea"), false);
//});

const cleanUpdatePanelHeap = function (element, cleanSelf) {

    if (!element)
        return;

    //div.modalBackground, div.width-modal-popup-auto, input[type="submit"][value*="Dummy"]
    let list = element.querySelectorAll('select, li, span, label, td, tr, table, a, input[type="submit"][onclick^="javascript:WebForm_DoPostBack"][class^="btn-dummy"]'); //, li, span, a, label, td, tr, table');

    //console.log(list);

    if (list && list.length > 0)
        list.forEach(el => cleanElementEventsAndBindings(el, false)); //for elements keep subtree false to not deep clone

    list = null;

    if (cleanSelf)
        cleanElementEventsAndBindings(element, true); //for element keep subtree true to deep clone

    if (window.gc) window.gc();
}

const cleanElementEventsAndBindings = function (element, keepSubtree) {

    if (typeof Sys === 'undefined' || !Sys.Application || !Sys.Application.disposeElement) {
        setTimeout(cleanElementEventsAndBindings, 100, element);
        return;
    }

    if (element && element.tagName === 'INPUT' && element.type === 'submit' && element.value && element.value.toLowerCase().includes('dummy')) {
        return;
    }

    /*find and dispose and remove relevant ajax component*/
    let ajaxComp = Sys.Application.findComponent(element.id);

    if (!ajaxComp)
        ajaxComp = $find(element.id);

    if (!ajaxComp) {
        let behaviors = Sys.UI.Behavior.getBehaviors(element);

        for (let i = 0; i < behaviors.length; i++) {
            let b = behaviors[i];
            if (b.dispose) {
                ajaxComp = b;
                b = null;
                break; // stop looping immediately
            }
        }
    }

    if (ajaxComp) {

        //dispose component
        try { ajaxComp.dispose(); }
        catch (e) { }

        //remove component to avoid duplicate error at add_init
        try { Sys.Application.removeComponent(ajaxComp); }
        catch (e) { }

        ajaxComp = null;
    }

    try {
        Sys.Application.disposeElement(element, true);
    }
    catch (e) { }

    //Remove all jquery event listeners and data bindings if any
    jQuery(element).off().removeData();

    // Remove all event listeners and data bindings
    if (element && element.parentNode)
        element.parentNode.replaceChild(element.cloneNode(keepSubtree), element);


    element = null;
}


/*var oldPostBack;
var myForm = document.forms['aspnetForm'];
if (!myForm) {
    myForm = document.aspnetForm;
}
 
oldPostBack = __doPostBack;
__doPostBack = customPostBackHandler;
 
function customPostBackHandler(eventTarget, eventArgument) {
 
    if (myForm && (!myForm.onsubmit || (myForm.onsubmit() != false))) {
        HandleInputHtmlTags();
        $('.page-loader-wrapper').show();
        return oldPostBack(eventTarget, eventArgument);
    }
    else
        return oldPostBack(eventTarget, eventArgument);
}*/

var gridPageSize = 10;
function getGridPageSize() {

    let cpsz = getCookie('MachPanel_PageSize');

    if (cpsz && cpsz.indexOf('=') > -1)
        gridPageSize = parseInt(cpsz.split('=')[1]);
    return gridPageSize;
}

getGridPageSize();

setInterval(() => {
    $("a:not([href])")
        .attr('href', 'javascript:void(0)');
    $("a:not([data-show-progress])").each(anchorClickShowProgressHandler);
}, 1000);
