var key;
var ws;
var path_Name = window.location.pathname;
var lastcontrol;
$(document).ready(function () {
    try {
        $('.BestLP').css({ "font-size": "16px" });

        //Added by Shekhar L. @05-Apr-2021

        // $('.menuOverlay').css({ 'visibility': 'hidden' });
		
		//Added by Shekhar L @22-Nov-2021 for remove top extra empty margin in workbench or iframe pages
        if (window.top != window.self) {
             iFrameEvents();
        } 
          //Added by Shekhar L. @02-May-2021 on popup with hidden menu and page title removed top-margin BBVABBVAORINT-231 [UCP Deal Entry] Top Space while entering the deal should be made available in the accordion mode.
        if ((window.location.search.indexOf('Master_Popup') > -1)) {
            var topMargin = 0;
            setTimeout(function () {
                
                if ($('.FinIQ_lblFormName').is(':visible')) {
                    try {
                        
                        topMargin = parseInt($('.FinIQ_lblFormName:visible')[0].offsetHeight);
                        $(window.self.document).find('.mainContentTable').css({ 'margin-top': topMargin + 'px', 'position': 'relative' });
                    } catch (er) {
                        topMargin = parseInt($('.FinIQ_lblFormName:visible').height());
                        $(window.self.document).find('.mainContentTable').css({ 'margin-top': topMargin + 'px', 'position': 'relative' });
                    }
                } else {
                    $(window.self.document).find('.mainContentTable').css({ 'margin-top': '10px' });
                }
            }, 50);

        }
    } catch (er) { console.log(er.message); }
});

// Added by Shekhar L. @26-Nov-2021 in iFrame set focus on first control after tab-out on last control
function iFrameEvents() {
    try {
 if (window.top != window.self) {
     $(window.self.document).find('.mainContentTable').css({ 'margin-top': '0px' }); //.addClass('mainContentTable1').removeClass('mainContentTable');
        //$(window.self.document).find('.lstWarning').css({ 'position': 'absolute' });
   
     $(window.self.document).find('input:visible:not(:disabled), select:visible:not(:disabled), a:visible:not(:disabled), img:visible:not(:disabled), .selectize-control:visible:not(:disabled)').on('keydown', function (event) {
         
         if ((event.which === 9) && !event.shiftKey) {
             visibleElements = $(window.self.document).find('input:visible:not(:disabled), select:visible:not(:disabled), a:visible:not(:disabled), img:visible:not(:disabled), .selectize-control:visible:not(:disabled)').get();
             visibleElements = visibleElements.filter(function (elem) {
                 return $(elem).css("visibility") != "hidden";
             })
             if (this == visibleElements[visibleElements.length - 1]) {
                 event.preventDefault();
                 visibleElements[0].focus(); 
                } 
            }
        });
		Sys.WebForms.PageRequestManager.getInstance().remove_endRequest(iFrameEvents);
     Sys.WebForms.PageRequestManager.getInstance().add_endRequest(iFrameEvents);
 }
    } catch (er) {
        console.log(er.message);
    }
}

var loggedInAT;
(function () {
    $(document).ready(function () {
        if (window.top == window.self) {
            loggedInAT = (loggedInAT == undefined ? window.top.document.title.replace('BBVA SOLAR ', '') : loggedInAT);     //FinIQ replced with BBVA SOLAR by BhagyashriB on 14-Apr-2022 | as discussed with DJ
            window.top.document.title = ('BBVA SOLAR - ' + $(document).find('.FinIQ_lblFormName').find('#pageName').text() + ' ' + loggedInAT);
        }

        //alert(window.localStorage.getItem('FinIQTheme'));
        //Updated By Shekhar L. @07-Sep-2021 for Set Custom themes on Pages load : Mashreq POC Black Theme issues :JIRAID:MASINT-2044
        if (window.localStorage.getItem('FinIQTheme') != null && window.localStorage.getItem('FinIQTheme') != 'Style1') {
            $(document).find('link[href*="Style1"]').attr('href', location.origin + '/FinIQWebApp/App_Themes/' + (window.localStorage.getItem('FinIQTheme') == null ? "Style1" : window.localStorage.getItem('FinIQTheme')) + '.css');
            if (window.localStorage.getItem('FinIQTheme') == "All_Black") {
                $(document).find('img[src*="loading_1.gif"]').attr('src', $(document).find('img[src*="loading_1.gif"]').attr('src').replace("Ajax_loader_White", "All_Black"));
            }
        }
        //Updated by Shekhar L @07-Sep-2021
        $(document).on('click', function (event) {
            //Added By Shekhar L. @07-Sep-2021 for Set Custom themes on Pages load : Mashreq POC Black Theme issues  :JIRAID:MASINT-2044
            $(document).find('iframe').on("load", function () {
                if (window.localStorage.getItem('FinIQTheme') != null) {
                    if ($(document).find('iframe').length > 0) {
                        $(document).find('iframe').each(function (i, elem) {
                            $($(elem).context.contentDocument).find('link[id$="FinIQTheme"], link[href*="Style1"]').attr('href', location.origin + '/FinIQWebApp/App_Themes/' + (window.localStorage.getItem('FinIQTheme') == null ? "Style1" : window.localStorage.getItem('FinIQTheme')) + '.css');
                        });
                    }
                }
            });

            //commented by Shekhar L @02-Sep-2021 :JIRAID:MASINT-2044
            //if (window.localStorage.getItem('FinIQTheme') != null) {  
            //    if ($(document).find('iframe').length > 0 || (window.self != window.top)) {
            //        $(document).find('iframe').each(function (i, elem) {
            //            $($(elem).context.contentDocument).find('link[type="text/css"][id$="FinIQTheme"], link[type="text/css"][href*="Style1"]').attr('href', '../App_Themes/' + (window.localStorage.getItem('FinIQTheme') == null ? "Style1" : window.localStorage.getItem('FinIQTheme')) + '.css');
            //        });
            //    }
            //}
        });
        //Updated by Shekhar L.@03-Oct-2021 issue resolved last integration 
        //Added by Shekhar L. @05-Apr-2021
        window.onscroll = function (event) {
            try {
                event.cancelBubble = false;
                if (parseInt($('.FinIQ_lblFormName:not(:empty)').position().top - window.scrollY) < 0) {
                    $('.FinIQ_lblFormName:not(:empty)').css({ 'position': 'fixed', 'box-shadow': '0px 0px 1px #00000000' });
                } else {
                    $('.FinIQ_lblFormName:not(:empty)').css({ 'position': 'static', 'box-shadow': 'none' });
                }

                event.preventDefault();
                return true;
            } catch (er) {
                console.log(er.message);
            }

        }
    });
    })();

    //Start Updated By Shekhar L @23-Aug-2021 | UBPINT-1430
    function SetMenuBarSize() {
        try {
            var menuWidth = 0;
            $(document).ready(function () {

                if ($(document).width() > window.innerWidth && $('.Menu_FormName').css('position') == 'sticky') {
                    $('.Menu_FormName').css({ "width": $(document).width() });
                    $('#ctl00_trMenu .FinIQ_MenuBG').eq(5).width(Math.abs(Number($(document).width() - window.innerWidth)));
                }
                else {
                    $('table.Menu_FormName > td.FinIQ_MenuBG:last-child').css({ "width": "auto", "min-width": "0px" });
                }
                $(".FinIQ_Menu ul:first-child >  li").each(function (i, el) {
                    menuWidth += parseInt($(el).outerWidth() + 5);
                });
                $(".FinIQ_Menu").width(menuWidth);

                $('.FinIQ_Menu > ul > li').on("mouseover", function () {
                    try {
                        lCount = $(this).find('ul li').length;
                        elems = $(this).find('ul li');

                        var maxWidth = Math.max.apply(null, $(elems).map(function (i, j) {
                            return $(j).width();
                        }).get());
                        lHeight = 30;
                        wHeight = ($(window)[0].innerHeight) - 45;
                        $(this).find('ul').width((maxWidth * (Math.ceil((lCount * lHeight) / wHeight))));
                    } catch (er) { console.log(er.message); }
                });
            })
        } catch (er) {
            console.log(er.message);
            $(".FinIQ_Menu").css({ "width": "max-width" });
        }
    }
    //Updated By Shehar L @23-May-2021
    (function () {
        try {
            if (typeof SetMenuBarSize != undefined) {
                SetMenuBarSize();
            }
            //Added by Shekhar L. @14-Apr-2021
            // if (typeof SetPageTitle_Fixed != undefined) {    
            if (window.addEventListener) {
                window.removeEventListener('scroll', SetPageTitle_Fixed);
                window.addEventListener("scroll", SetPageTitle_Fixed, true);
            } else if (window.attachEvent) {
                window.attachEvent("scroll", SetPageTitle_Fixed);
            }
            // }
        } catch (er) { console.log(er.message); }
    })();
    //Updated By Shekhar L on 23-Aug-2021 | UBPINT-1430

    function SetPageTitle_Fixed(event) {
         //updated function by Shekhar L @14-Mar-2022 multiple pages issue resolved on page scrolled removed extra left padding 
        try {
            //return true;
            event = event || window.event;
            if (event != undefined) {
           
              //  $('.mainContentTable').css({ 'margin-top': parseInt($('.FinIQ_lblFormName:not(:empty)')[0].offsetHeight + $('table.Menu_FormName')[0].offsetHeight), 'margin-left': '40px' });
                if (parseInt(($('.FinIQ_lblFormName:not(:empty)').position().top) - (window.pageYOffset || window.scrollY)) < 0) {
                    $('table.Menu_FormName').css({ 'top': '0px' });//updated by Shekhar @24-Jun-2021 for LGT
                    $('.FinIQ_lblFormName:not(:empty)').css({ 'position': 'fixed', 'top': $('table.Menu_FormName')[0].offsetHeight, 'box-shadow': '0px 0px 1px #00000000', 'z-index': '9909' });

                } else {

                    //$('table.Menu_FormName').css({ 'position': 'fixed' });
                    $('.FinIQ_lblFormName:not(:empty)').css({ 'position': 'fixed', 'top': $('table.Menu_FormName')[0].offsetHeight, 'box-shadow': '0px 0px 1px #00000000', 'z-index': '9909' });

                    //$('.FinIQ_lblFormName:not(:empty)').css({ 'position': 'fixed', 'box-shadow': 'none', 'z-index': '0' });
                }

                if ($(document).find('div[id$="accordionToolbar"]').is(':visible')) {
                    $(document).find("#accordionToolbar").css({ "background-color": $('.FinIQ_MenuBG').css('background-color'), "background": $('.FinIQ_MenuBG').css('background'), "color": $('.FinIQ_MenuBG').css('color') });

                    $('.FinIQ_lblFormName:not(:empty)').css({ 'position': 'fixed', 'left': $(document).find('div[id$="accordionToolbar"]').width(), 'width': 'Calc(100% - 220px)' });

                    $(document).find('.finiq_VerticalMenu').css({ "min-width": $(document).find('div[id$="accordionToolbar"]').width() }).show();
                    $('.mainContentTable').css({ 'table-layout': 'fixed' });
                 //   $('.mainContentTable').css({ 'margin-top': parseInt($('.FinIQ_lblFormName:not(:empty)')[0].offsetHeight + $('table.Menu_FormName')[0].offsetHeight), 'margin-left': '40px' });

                } else {
                    $(document).find('div[id$="accordionToolbar"]').hide();
                    $(document).find('.finiq_VerticalMenu').width('0px').hide();
                    $('.FinIQ_lblFormName:not(:empty)').css({ 'left': '0px', 'width': '100%' });
                    $('.mainContentTable').css({ 'table-layout': '' });
                    // $('.mainContentTable').css({ 'margin-top': parseInt($('.FinIQ_lblFormName:not(:empty)')[0].offsetHeight ), 'margin-left': '40px' });
                  //  $('.mainContentTable').css({ 'margin-top': parseInt($('.FinIQ_lblFormName:not(:empty)')[0].offsetHeight + $('table.Menu_FormName')[0].offsetHeight), 'margin-left': '40px' });

                }
            }
            //$(window.self.document).find('.mainContentTable').css({ 'margin-top': parseInt($(window.self.document).find('.FinIQ_lblFormName:visible')[0].offsetHeight + $(window.self.document).find('table.Menu_FormName:visible')[0].offsetHeight) });
            //return true;
        } catch (er) {
            console.log(er.message);
        }
        //commented by Shekhar L. @14-Mar-2022 scroll event issue in revenue insight pages
        //finally {
        //    event.preventDefault();
        //    if (event.stopPropagation) {
        //        event.stopPropagation();   // W3C model
        //    } else {
        //        event.cancelBubble = true; // IE model
        //    }

        //    return;
        //}
    }
    //END Updated By Shehar L @23-May-2021

    //Updated by Shekhar L. @29-Jul-2021 Mashreq_ClientMASCLI-901 
    var GlobalServerDate;
    function Get_GlobalServerDate() {
        $(document).ready(function () {
            if (GlobalServerDate == undefined) {
                $.ajax({
                    type: 'POST',
                    url: '../FinIQ_User_Controls/FinIQ_WebMethods.aspx/GlobalServerDate',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    crossDomain: true,
                    async: true,//(navigator.vendor == "") ? false : true,
                    success: function (data) {
                        if (data != null) {
                            GlobalServerDate = data.d;
                            // $('#ctl00_lblGlobalServerDate').text('[Business Date : ' + GlobalServerDate + ']');
                        }
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        console.log(thrownError);
                    }
                });
            }
            else {
                // $('#ctl00_lblGlobalServerDate').text('[Business Date : ' + GlobalServerDate + ']');
            }
        });
    }

    //Added by Shekhar L. @29-Jul-2021 Mashreq_ClientMASCLI-901 
    var BusinessDate = "";
    (function Get_BusinessDate() {
        $(document).ready(function () {
            try {
                $.ajax({
                    type: 'POST',
                    url: '../FinIQ_User_Controls/FinIQ_WebMethods.aspx/BusinessDate',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    crossDomain: true,
                    async: true,//(navigator.vendor == "") ? false : true,
                    success: function (data) {
                        if (data != null) {
                            BusinessDate = data.d;
                            if (BusinessDate == "") {
                                $(document).find('#ctl00_lblGlobalServerDate').css({ 'visibility': 'hidden', 'display': 'none' });
                                return true;
                            }
                            $(document).find('#ctl00_lblGlobalServerDate').text('[Business Date : ' + BusinessDate + ']');
                        }
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        $(document).find('#ctl00_lblGlobalServerDate').css({ 'visibility': 'hidden', 'display': 'none' });
                        console.log(thrownError);
                    }
                });
            } catch (er) {
                $(document).find('#ctl00_lblGlobalServerDate').css({ 'visibility': 'hidden', 'display': 'none' });
            }
        });
    })();

    //commented by Shekhar L. @03-Oct-2021 issue
//    //Added by Shekhar L. @05-Apr-2021
//    window.onscroll = function (event) {
//        try {
//            event.cancelBubble = false;
//            if (parseInt($('.FinIQ_lblFormName:not(:empty)').position().top - window.scrollY) < 0) {
//                $('.FinIQ_lblFormName:not(:empty)').css({ 'position': 'fixed', 'box-shadow': '0px 0px 1px #00000000' });
//            } else {
//                $('.FinIQ_lblFormName:not(:empty)').css({ 'position': 'static', 'box-shadow': 'none' });
//            }

//            event.preventDefault();
//            return true;
//        } catch (er) {
//            console.log(er.message);
//        }

//    }
//});

/*Start - Added by Shekhar on 09-Jul-2020*/

function MathRandom() {
    try {
        crypto = window.crypto || window.msCrypto;
        return parseFloat(crypto.getRandomValues(new Uint8Array(1))[0] / (2048 * 8));
    } catch (er) {
        console.log(er.message);
    }
}


function ChooseStyleSheet() {
    try {
        // <Start Updated by Shekhar@10-Mar-2021>
        $(".pnlStyleSheet").hide();
        if (typeof SetDefault_FontProps == "function") {
            SetDefault_FontProps();
        }

        $('#ctl00_rblTheme').change(function (event) {
            window.localStorage.setItem('FinIQTheme', $(this).find(':checked').val());
            $('link#FinIQTheme').attr('href', '../App_Themes/' + $(this).find(':checked').val() + '.css');
            $(document).find('link[href="../App_Themes/Style1.css"]').attr('href', '../App_Themes/' + $(this).find(':checked').val() + '.css');

            window.setTimeout(function () { $('.pnlStyleSheet').css({ 'background-color': $('body').css('background-color') }) }, 1000);
        });

        $('#ctl00_rblFontSize').change(function (event) {
            window.localStorage.setItem('FinIQ_FontSize', $(this).find(':checked').val());
            $('body').css({ "font-size": Number($(this).find(':checked').val()) });
            $('.FinIQ_lblUser, .FinIQ_logout, .lbl, .txt, .ddl, select, htmlselect, .lblerror, .lblError, .LBLERROR, .lblInfo, .lblsuccess, .Grid, .grid, .GridHeaderTitle, .GridHeaderTitle th, .Grid .GridHeaderTitle td, .GridHeaderTitle th a:hover, .GridHeaderTitle a, .GridHeader td, .GridHeader th, .AlternatItemStyle a, .GridItem a, .GridItemSelect a, .GridList, .GridPager, .GridPager a:link, .GridPager a:hover, .GridPager a:active, .GridPager a:visited, .GridPager td span, .GridFooter, .Filter, .tbl, .tbl2, .footer, .FinIQ_MenuBG ul li a, .FinIQ_MenuBG UL li UL > li a, .menu li a, .menu li, .smallfont, .orange1, .purple1, .olive1, .almond1, .QueueButtons, .QueueButtons[disable="disabled"], input[type="text"], input[type="password"], textarea, .ddl, select, .ui-selectmenu-button span.ui-selectmenu-text, .readOnly, input[type="text"][disabled="disabled"], .loading_span, .Dashboard1, .Dashboard, .slidingDiv').css({ "font-size": Number($(this).find(':checked').val()) });

        });

        $('#ctl00_rblFontFamily').change(function (event) { 
            try {
                
                if ($(this).find(':checked').val() == "Montserrat" || $(this).find(':checked').val() == "Roboto") {
                    $(document.head).append($('<link>', { 'id': "lnkMontserrat", "href": "https://fonts.googleapis.com/css?family=" + $(this).find(':checked').val(), "rel": "stylesheet" }));
                } else {
                    $(document.head).find('#lnkMontserrat').remove();
                }
                if ($(this).find(':checked').val() == 'Default') {
                    $('body').css({ "font-Family": window.defaultFontFamily });
                    $('div, td, span, input, textarea, a, a:hover, label, button, selectize').css({ "font-Family": window.defaultFontFamily });
                } else {
                    $('body').css({ "font-Family": $(this).find(':checked').val() });
                    $('div, td, span, input, textarea, a, a:hover, label, button, selectize').css({ "font-Family": $(this).find(':checked').val() });
                }
                window.localStorage.setItem('FinIQ_FontFamily', $(this).find(':checked').val());
                Populate_ThemeArray();
            } catch (er) { console.log(er.message); }

            window.localStorage.setItem('FinIQ_FontFamily', $(this).find(':checked').val());

        });

    } catch (er) { }
}


function SetDefault_FontProps() {

    try {
        if (window.localStorage.getItem('FinIQTheme') != null) {
            if (window.localStorage.getItem('FinIQTheme') == "All_Black") {
                $(document).find('img[src*="loading_1.gif"]').attr('src', $(document).find('img[src*="loading_1.gif"]').attr('src').replace("Ajax_loader_White", "All_Black"));
            }
            $('#ctl00_rblTheme [type="radio"]').filter(function () {
                return this.value == window.localStorage.getItem('FinIQTheme');
            }).prop('checked', "checked");
            $('link#FinIQTheme').attr('href', '../App_Themes/' + window.localStorage.getItem('FinIQTheme') + '.css');
            $(document).find('link[href="../App_Themes/Style1.css"]').attr('href', '../App_Themes/' + window.localStorage.getItem('FinIQTheme') + '.css');
        }

        if (window.localStorage.getItem('FinIQ_FontSize') != null) {
            FinIQ_FontSize = window.localStorage.getItem('FinIQ_FontSize');
            $('body').css({ "font-size": Number(FinIQ_FontSize) });
            $('.FinIQ_lblUser, .FinIQ_logout, .lbl, .txt, .ddl, select, htmlselect, .lblerror, .lblError, .LBLERROR, .lblInfo, .lblsuccess, .Grid, .grid, .GridHeaderTitle, .GridHeaderTitle th, .Grid .GridHeaderTitle td, .GridHeaderTitle th a:hover, .GridHeaderTitle a, .GridHeader td, .GridHeader th, .AlternatItemStyle a, .GridItem a, .GridItemSelect a, .GridList, .GridPager, .GridPager a:link, .GridPager a:hover, .GridPager a:active, .GridPager a:visited, .GridPager td span, .GridFooter, .Filter, .tbl, .tbl2, .footer, .FinIQ_MenuBG ul li a, .FinIQ_MenuBG UL li UL > li a, .menu li a, .menu li, .smallfont, .orange1, .purple1, .olive1, .almond1, .QueueButtons, .QueueButtons[disable="disabled"], input[type="text"], input[type="password"], textarea, .ddl, select, .ui-selectmenu-button span.ui-selectmenu-text, .readOnly, input[type="text"][disabled="disabled"], .loading_span, .Dashboard1, .Dashboard, .slidingDiv').css({ "font-size": Number(FinIQ_FontSize) });

            $('#ctl00_rblFontSize [type="radio"]').filter(function () {
                return this.value == FinIQ_FontSize;
            }).prop('checked', "checked");
        }

        if (window.localStorage.getItem('FinIQ_FontFamily') != null) {
            FinIQ_FontFamily = window.localStorage.getItem('FinIQ_FontFamily');
            $(document.head).find('#lnkMontserrat').remove();

            if (FinIQ_FontFamily == "Montserrat" || FinIQ_FontFamily == "Roboto") {
                $(document.head).append($('<link>', { 'id': "lnkMontserrat", "href": "https://fonts.googleapis.com/css?family=" + FinIQ_FontFamily, "rel": "stylesheet" }));               
            }  
                
                if ($(this).find(':checked').val() == 'Default') {
                    $('body')[0].style.removeProperty('font-family');//.css({ "font-Family": window.defaultFontFamily });
                    $('div, td, span, input, textarea, a, a:hover, label, button, selectize')[0].style.removeProperty('font-family');//.css({ "font-Family": window.defaultFontFamily });
                $('div, td, span, input, textarea, a, a:hover, label, button, selectize').each(function () {
                    $(this)[0].style.removeProperty('font-weight');
                });
                } else {
                    $('body').css({ "font-Family": FinIQ_FontFamily });
                    $('div, td, span, input, textarea, a, a:hover, label, button, selectize').css({ "font-Family": FinIQ_FontFamily });
                }
            if (FinIQ_FontFamily == "Montserrat") {
                $('body').css({ "font-weight": "500" });
                $('div, td, span, input, textarea, a, a:hover, label, button, selectize').css({ "font-weight": "500" });
            }
            if (FinIQ_FontFamily == "Roboto") {
                $('div, td, span, input, textarea, a, a:hover, label, button, selectize').each(function () {
                    $(this)[0].style.removeProperty('font-weight');
                });
            }

            $('#ctl00_UC_CustomTheme_rblFontFamily [type="radio"]').filter(function () {
                return this.value == FinIQ_FontFamily;
            }).prop('checked', "checked");
        }

            $('#ctl00_rblFontFamily [type="radio"]').filter(function () {
                return this.value == FinIQ_FontFamily;
            }).prop('checked', "checked");
         

    } catch (er) { }
}

/*End - Updated by Shekhar@10-Mar-2021*/


//commented by shreyasv For signalr notifications replacement 8-jan-2021 -start  PLEASE CONTACT BONDS TEAM INCASE ANY QUERIES

//function SubScriberr(WebSocketIP, USERID) {

//    //  

//    var TotalChkBx;
//    var Counter;
//    Counter = 0;
//    preM = 'ctl00_MainContent_';
//    secs = 0;
//    count = 0;
//    var rfqid = Math.random();
//    //alert($("#<%=hdn_WebsocketIP.ClientID%>").val())
//    if (WebSocketIP == '' || WebSocketIP == undefined) {
//        WebSocketIP = "localhost";  //$("#<%=hdn_WebsocketIP.ClientID%>").val();
//    }
//    var myPageName = path_Name.substring(path_Name.lastIndexOf('/') + 1);
//    //alert(1);
//    if (1 == 1) {
//        var prem;
//        if (rfqid == "") { }
//        else {

//            $(document).ready(function () {
//                //Change this for the pagename
//                //  
//                // added by Hamza.s on 18 jun 2020 for streaming Prices on trading portal
//                if (myPageName == "FinIQ_EMSX.aspx" || myPageName == "EQ_Order_Entry.aspx" || myPageName == "FinIQ_Trading_Portal.aspx" || myPageName == "FinIQ_Trading_PortalNew.aspx") {
//                    var wsprotocol;
//                    if (location.protocol == "http:")
//                        wsprotocol = "ws:"
//                    else if (location.protocol == "https:")
//                        wsprotocol = "wss:"
//                    else
//                        wsprotocol = "ws:"

//                    try {
//                        // ws = new WebSocket("wss://" + WebSocketIP + "/FinIQservice/WorkflowCallback.svc");  http://192.168.2.204:82/finiqservice_ws/WorkflowCallback.svc
//                        ws = new WebSocket("" + wsprotocol + "//" + WebSocketIP + "/FinIQService/WSCallback.svc");
//                        // alert("" + wsprotocol + "//" + WebSocketIP + "/FinIQService/WSCallback.svc");
//                    }
//                    catch (error) {
//                        //alert(error);
//                    }

//                    ws.onopen = function () {
//                        //alert("After Open");
//                        // alert(ws.readyState);
//                        if (ws.readyState == WebSocket.OPEN) {
//                            // alert('value : ' + $("#<%=hdnUserID.ClientID%>").val());
//                            //$("#<%=hdnUserID.ClientID%>").val()
//                            //   ws.send('MASTERSUBSCRIBE|' + USERID);  mdw
//                            ws.send('MASTERSUBSCRIBE|' + USERID);
//                            console.log('subscribed to Live Quotes'); // added by Hamza.s on 18 jun 2020 for streaming Prices
//                            //ws.Subscribe('MASTERSUBSCRIBE|' + USERID);

//                            // alert(" After Subscription");
//                        }
//                        else {
//                            //alert('Connection is closed', 'success');
//                        }
//                    };
//                    ws.onmessage = function (evt) {
//                        // alert('Received');
//                        //  
//                        var msg = evt.data;
//                        var strRes = JSON.parse(msg);
//                        if (ws.readyState == WebSocket.OPEN && strRes["MesssageType"].toUpperCase() == "SUBSCRIBE") {
//                            // alert('SUBSCRIBED');
//                        }
//                        else if (ws.readyState == WebSocket.OPEN && strRes["MesssageType"].toUpperCase() == "UNSUBSCRIBE") {
//                        }
//                        else if (ws.readyState == WebSocket.OPEN && strRes["MesssageType"].toUpperCase() == "NOTIFICATION") {
//                        }
//                        // added by Hamza.s on 18 jun 2020 for streaming Prices on trading portal
//                        else if (ws.readyState == WebSocket.OPEN && strRes["MesssageType"].toUpperCase() == "PRICEPROVIDERRESPONSE") {
//                            try {
//                                //
//                                // alert(strRes["MessageContent"]);
//                                // added by Hamza.s on 18 jun 2020 for streaming Prices on trading portal
//                                if (myPageName == "FinIQ_EMSX.aspx" || myPageName == "FinIQ_Trading_Portal.aspx" || myPageName == "FinIQ_Trading_PortalNew.aspx") {
//                                    processWSCallbackData(strRes["MessageContent"]);
//                                }
//                                else if (myPageName == "EQ_Order_Entry.aspx") {
//                                    processWSCallbackData2(strRes["MessageContent"]);
//                                }

//                                //processWSCallbackData2(strRes["MessageContent"]);
//                            }
//                            catch (Exception) { }
//                        }
//                    };
//                    ws.onerror = function (evt) {

//                        //  
//                        //  alert('Error with code : ' + evt.code + '', 'error');
//                    };
//                    ws.onclose = function (evt) {
//                        //alert('Onclose' + evt.reason);
//                        //alert('Onclose called - Event : ' + evt + ', code : ' + evt.code + ', reason : ' + evt.reason + ', wasClean : ' + evt.wasClean);
//                        SubScriberr(WebSocketIP, USERID);
//                    };
//                }

//                //<Start= Added by Pranjali K/Joel D on 18th Feb 2020 | Resizeable grid rows| Reported  by Omkar Tapkire>
//                whatifGridAlignment();
//                //<End= Added by Pranjali K/Joel D on 18th Feb 2020 | Resizeable grid rows| Reported  by Omkar Tapkire>

//            });
//        }

//    }
//}
//// ADDED BY sushmita.h for DOR Integration || start || 19_nov_2019
//function SubScriberrDOR(WebSocketIP, USERID) {
//    //
//    var TotalChkBx;
//    var Counter;
//    Counter = 0;
//    preM = 'ctl00_MainContent_';
//    secs = 0;
//    count = 0;
//    var rfqid = Math.random();
//    // alert(path_Name);
//    //alert($("#<%=hdn_WebsocketIP.ClientID%>").val())
//    //WebSocketIP = "192.168.26.106";

//    //Remove hardcoded IP || 23-09-2020 || Sheetalk || as asked by anand sir/PrasadP 
//    // if (WebSocketIP == '' || WebSocketIP == undefined) {
//    //    WebSocketIP = "52.163.241.178";  //$("#<%=hdn_WebsocketIP.ClientID%>").val();
//    //}
//    var myPageName = path_Name.substring(path_Name.lastIndexOf('/') + 1);
//    //alert(1);
//    if (1 == 1) {
//        var prem;
//        if (rfqid == "") { }
//        else {

//            $(document).ready(function () {
//                //Change this for the pagename
//                //Added by Akshika B on 25-Jun-2020 for DOR
//                if (myPageName == "FinIQ_QuoteRequest.aspx" || myPageName == "FinIQ_Bond_Entry.aspx" || myPageName == "RMW.aspx") {

//                    var wsprotocol;
//                    if (location.protocol == "http:")
//                        wsprotocol = "ws:"
//                    else if (location.protocol == "https:")
//                        wsprotocol = "wss:"
//                    else
//                        wsprotocol = "ws:"

//                    try {
//                        // ws = new WebSocket("wss://" + WebSocketIP + "/FinIQservice/WorkflowCallback.svc");  http://192.168.2.204:82/finiqservice_ws/WorkflowCallback.svc
//                        ws = new WebSocket("" + wsprotocol + "//" + WebSocketIP + "/FinIQService/WSCallback.svc");
//                        // alert("" + wsprotocol + "//" + WebSocketIP + "/FinIQService/WSCallback.svc");
//                    }
//                    catch (error) {
//                        //alert(error);
//                    }

//                    ws.onopen = function () {
//                        //alert("After Open");
//                        //   alert("jkkkkk");
//                        if (ws.readyState == WebSocket.OPEN) {
//                            // alert('value : ' + $("#<%=hdnUserID.ClientID%>").val());
//                            //$("#<%=hdnUserID.ClientID%>").val()
//                            //   ws.send('MASTERSUBSCRIBE|' + USERID);  mdw
//                            ws.send('MASTERSUBSCRIBE|' + USERID);
//                            //ws.Subscribe('MASTERSUBSCRIBE|' + USERID);

//                            //alert(" After Subscription");
//                        }
//                        else {
//                            //alert('Connection is closed', 'success');
//                        }
//                    };
//                    ws.onmessage = function (evt) {

//                        // alert('Received');
//                        var msg = evt.data;
//                        var strRes = JSON.parse(msg);
//                        if (ws.readyState == WebSocket.OPEN && strRes["MesssageType"].toUpperCase() == "SUBSCRIBE") {
//                            // alert('SUBSCRIBED');
//                        }
//                        else if (ws.readyState == WebSocket.OPEN && strRes["MesssageType"].toUpperCase() == "UNSUBSCRIBE") {
//                        }
//                        else if (ws.readyState == WebSocket.OPEN && strRes["MesssageType"].toUpperCase() == "NOTIFICATION") {
//                        }
//                        else {
//                            try {
//                                //alert(strRes["MessageContent"]);
//                                //Removed by Akshika B on 25-Jun-2020 for DOR

//                                processWSCallbackData(strRes["MessageContent"]);

//                            }
//                            catch (Exception) { }
//                        }
//                    };
//                    ws.onerror = function (evt) {
//                        //
//                        //  alert('Error with code : ' + evt.code + '', 'error');
//                    };
//                    ws.onclose = function (evt) {
//                        //alert('Onclose' + evt.reason);
//                        //alert('Onclose called - Event : ' + evt + ', code : ' + evt.code + ', reason : ' + evt.reason + ', wasClean : ' + evt.wasClean);
//                        SubScriberrDOR(WebSocketIP, USERID);
//                    };
//                }
//            });
//        }

//    }
//}
//// ADDED BY sushmita.h for DOR Integration || end

//added by shreyasv for signalr notifications 3-sep-2020 start
//commented by shreyasv For signalr notifications replacement 8-jan-2021 -end  PLEASE CONTACT BONDS TEAM INCASE ANY QUERIES

function NewsBroadcast(strRes) {
    var str = "";

    var temp = [];

    temp = strRes.split(",");
    var news = temp[0].split("|")[1];
    var Publisher = temp[2].split("|")[1];
    var PublishedAt = temp[3].split("|")[1];
    var ActiveYN = temp[4].split("|")[1];
    var strFooter = "";




    $("#newsPanel").find(".newsheader").each(function (index, ele) {


        var msgStr = $(this).find(".newsText").text();

        if (msgStr.includes(news.trim())) {

            $(this).next().next().next().next().remove();
            $(this).next().next().next().remove();
            $(this).next().next().remove();
            $(this).next().remove();
            $(this).remove();
        }

    })

    $("#notificationFooter").find(".divWrapper").each(function (index, ele) {
        var msgStrFooter = $(this).find(".newsFooterText").text();
        if (msgStrFooter.includes(news.trim())) {

            $(this).next().remove();
            $(this).remove();

        }

    })


    if (ActiveYN.trim() == "Y") {
        str = str + "<div class='newsheader'> <span class='newsText'>" + news + "</span></div><div class='triangleNewsInfo'></div><div class=''></div><div class='NewsBrodcaster'><span class='news-user'>" + Publisher + "</span></div><div class='NewsUpdatedAt'><span class='newsTime'>" + PublishedAt + "</span></div>";

        strFooter = strFooter + "<div class='divWrapper'><div class='newsFooter'> <span class='newsFooterText'>" + "\"" + news + "\"" + "</span><span class='newsFooternews-user'> - " + Publisher + "</span></div></div><div class='newsSeparator'> </div>";
        getNotificationCountForUser();

    }

    $("#newsPanel").prepend(str);
    $("#notificationFooter").find("marquee").prepend(strFooter);
    //    $("#notificationCount").html(Number($("#notificationCount").val()) + 1);


    $(".NewsCount").html($("#newsPanel").find(".newsheader").length);
}
//added by shreyasv for signalr notifications 3-sep-2020 End


//commented by shreyasv For signalr notifications replacement 8-jan-2021 -start  PLEASE CONTACT BONDS TEAM INCASE ANY QUERIES
//Added by Hamza for Creating a WebSocket for News on 22-01-2020
//function subscribeToNews(WebSocketIP, USERID) {
//
//alert("1");
// return false;
//    var TotalChkBx;
//    var Counter;
//    Counter = 0;
//    preM = 'ctl00_MainContent_';
//    secs = 0;
//    count = 0;
//    var rfqid = Math.random();;

//    //Remove hardcoded IP || 23-09-2020 || Sheetalk || as asked by anand sir/PrasadP 
//    // if (WebSocketIP == '' || WebSocketIP == undefined) {
//    // WebSocketIP = "52.163.241.178";  //Change to cloud IP
//    // }
//    var myPageName = path_Name.substring(path_Name.lastIndexOf('/') + 1);
//    if (1 == 1) {
//        var prem;
//        if (rfqid == "") { }
//        else {
//            $(document).ready(function () {
//                //Added by Hamza | Jira No.: BNPINT-318 | Date: 11-Feb-2020
//                //To disable News Web Socket on pages with own Web Socket connections
//                if (myPageName != "FXDealEntryForDealer.aspx" && myPageName != "FinIQ_QuoteRequest.aspx" && myPageName != "FinIQ_EMSX.aspx" && myPageName != "EQ_Order_Entry.aspx" && myPageName != "FinIQ_Bond_Entry.aspx" && myPageName != "RMW.aspx" && myPageName != "FinIQ_Trading_Portal_Bonds.aspx") {
//                    var wsprotocol;
//                    if (location.protocol == "http:")
//                        wsprotocol = "ws:"
//                    else if (location.protocol == "https:")
//                        wsprotocol = "wss:"
//                    else
//                        wsprotocol = "ws:"

//                    try {
//                        ws = new WebSocket("" + wsprotocol + "//" + WebSocketIP + "/FinIQService/WSCallback.svc");
//                    }
//                    catch (error) {
//                        console.log(error.message);
//                    }

//                    ws.onopen = function () {
//                        if (ws.readyState == WebSocket.OPEN) {
//                            ws.send('MASTERSUBSCRIBE|' + USERID);
//                            console.log('Subscribed to WS News');
//                        }
//                        else {
//                            console.log('Connection is closed');
//                        }
//                    };
//                    ws.onmessage = function (evt) {
//                        var msg = evt.data;
//                        var strRes = JSON.parse(msg);
//                        if (ws.readyState == WebSocket.OPEN && strRes["MesssageType"].toUpperCase() == "SUBSCRIBE") {
//                            // alert('SUBSCRIBED');
//                        }
//                        else if (ws.readyState == WebSocket.OPEN && strRes["MesssageType"].toUpperCase() == "UNSUBSCRIBE") {
//                        }
//                        else if (ws.readyState == WebSocket.OPEN && strRes["MesssageType"].toUpperCase() == "NOTIFICATION") {
//                        }
//                        else if (ws.readyState == WebSocket.OPEN && strRes["MesssageType"].toUpperCase() == "NEWS") {


//                            //Commented by shreyasv  3-sep-2020 start
//                            //var str = "";

//                            ////  $(strRes).each(function (i, ele) {
//                            //var temp = [];

//                            //temp = strRes.MessageContent.split(",");
//                            //var news = temp[0].split("|")[1];
//                            //var Publisher = temp[2].split("|")[1];
//                            //var PublishedAt = temp[3].split("|")[1];
//                            //var ActiveYN = temp[4].split("|")[1];
//                            //var strFooter = "";




//                            //$("#newsPanel").find(".newsheader").each(function (index, ele) {


//                            //    var msgStr = $(this).find(".newsText").text();
//                            //						//alert('hiii');
//                            //    if (msgStr.includes(news.trim())) {

//                            //        $(this).next().next().next().next().remove();
//                            //        $(this).next().next().next().remove();
//                            //        $(this).next().next().remove();
//                            //        $(this).next().remove();
//                            //        $(this).remove();
//                            //    }

//                            //})

//                            //$("#notificationFooter").find(".divWrapper").each(function (index, ele) {
//                            //    var msgStrFooter = $(this).find(".newsFooterText").text();
//                            //	//alert('bye');
//                            //    if (msgStrFooter.includes(news.trim())) {

//                            //        $(this).next().remove();
//                            //        $(this).remove();

//                            //    }

//                            //})


//                            //if (ActiveYN.trim() == "Y") {
//                            //    str = str + "<div class='newsheader'> <span class='newsText'>" + news + "</span></div><div class='triangleNewsInfo'></div><div class=''></div><div class='NewsBrodcaster'><span class='news-user'>" + Publisher + "</span></div><div class='NewsUpdatedAt'><span class='newsTime'>" + PublishedAt + "</span></div>";

//                            //    strFooter = strFooter + "<div class='divWrapper'><div class='newsFooter'> <span class='newsFooterText'>" + "\"" + news + "\"" + "</span><span class='newsFooternews-user'> - " + Publisher + "</span></div></div><div class='newsSeparator'> </div>";
//                            //    getNotificationCountForUser();

//                            //}

//                            //$("#newsPanel").prepend(str);
//                            //$("#notificationFooter").find("marquee").prepend(strFooter);
//                            ////    $("#notificationCount").html(Number($("#notificationCount").val()) + 1);


//                            //$(".NewsCount").html($("#newsPanel").find(".newsheader").length);

//                            //console.log(msg);
//                            //Commented by shreyasv  3-sep-2020 End

//                        }
//                    };
//                    ws.onerror = function (evt) {

//                        //  
//                        //  alert('Error with code : ' + evt.code + '', 'error');
//                    };
//                    ws.onclose = function (evt) {
//                        //alert('Onclose' + evt.reason);
//                        //alert('Onclose called - Event : ' + evt + ', code : ' + evt.code + ', reason : ' + evt.reason + ', wasClean : ' + evt.wasClean);
//                        //console.log("closing socket " + new Date());

//                        ws.close();
//                        subscribeToNews(WebSocketIP, USERID);
//                    };
//                }
//            });
//        }

//    }
//}
////Added by Hamza | 06 Mar 2020 | Web Socket connection for Bonds notitifcation
//function SubScribBonds(WebSocketIP, USERID) {
//    //
//    var TotalChkBx;
//    var Counter;
//    Counter = 0;
//    preM = 'ctl00_MainContent_';
//    secs = 0;
//    count = 0;
//    var rfqid = Math.random();
//    //alert($("#<%=hdn_WebsocketIP.ClientID%>").val())
//    //Remove hardcoded IP || 23-09-2020 || Sheetalk || as asked by anand sir/PrasadP 
//    // if (WebSocketIP == '' || WebSocketIP == undefined) {
//    // WebSocketIP = '52.163.241.178'; // To be changed to cloud IP
//    // }

//    // alert(1);
//    if (1 == 1) {
//        var prem;
//        if (rfqid == "") { }
//        else {
//            //alert(" Inside Subscribe");
//            //alert(WebSocketIP);
//            var wsprotocol;
//            if (location.protocol == "http:")
//                wsprotocol = "ws:"
//            else if (location.protocol == "https:")
//                wsprotocol = "wss:"
//            else
//                wsprotocol = "ws:"


//            try {
//                // ws = new WebSocket("wss://" + WebSocketIP + "/FinIQservice/WorkflowCallback.svc");
//                wsbonds = new WebSocket("" + wsprotocol + "//" + WebSocketIP + "/FinIQService/WorkflowCallback.svc");
//            }
//            catch (error) {
//                //alert(error);
//            }


//            //alert(ws);
//            wsbonds.onopen = function () {
//                // alert("After Open");
//                // alert(ws.readyState);
//                //
//                //Added by Mitali on 24-Jun-2020| websocket based workflow refresh
//                if (window.parent.location.pathname != "/FinIQWebApp/Workflow/Trade_Workflow_Blotter.aspx") {
//                    if (wsbonds.readyState == WebSocket.OPEN) {
//                        // alert('value : ' + $("#<%=hdnUserID.ClientID%>").val());
//                        //$("#<%=hdnUserID.ClientID%>").val()
//                        wsbonds.send('MASTERSUBSCRIBE|' + USERID);
//                        //Commented by Mitali on 22-May-2020
//                        //console.log('MASTERSUBSCRIBE|' + USERID);
//                        //wsbonds.send('SUBSCRIBE|' + USERID);
//                        //console.log('SUBSCRIBE|' + USERID);
//                        //End

//                        // alert(" After Subscription");
//                    }
//                    else {
//                        //alert('Connection is closed', 'success');
//                    }
//                }
//            };
//            wsbonds.onmessage = function (evt) {
//                //
//                //alert('Reached..!!');
//                //alert(evt.data);
//                var msg = evt.data;
//                var msgSplit = msg.toString().toUpperCase().split('|');
//                //alert(msgSplit[0]);
//                if (wsbonds.readyState == WebSocket.OPEN && msgSplit[0].toString().toUpperCase() == "SUBSCRIBED") {
//                    //alert("Routed to Treasury and " + msgSplit[1].toString() + "", 'success');

//                }
//                else if (wsbonds.readyState == WebSocket.OPEN && msgSplit[0].toString().toUpperCase() == "RFQPICKED") {

//                    clearTimeout(timerID);



//                }

//                else if (msgSplit[0].toString() == "RFQRESPONSE") {
//                    console.log('RFQRESPONSE');
//                }

//                else if (msgSplit[0].toString() == "RESPONSEORDER") {

//                    console.log('RESPONSEORDER');
//                }

//                else if (msgSplit[0].toString() == "RESPONSETRADE") {
//                    console.log('RESPONSETRADE');
//                }

//                else if (msgSplit[0].toString() == "RESPONSERFQ") {
//                    console.log('RESPONSERFQ');
//                }

//                else if (msgSplit[0].toString() == "RESPONSEPRIMKT") {
//                    console.log('RESPONSEPRIMKT');
//                }
//                else if (msgSplit[0].toString() == "ONSCREENNOTIFICATION") {
//                    //    
//                    //alert('FinIQ Common onMessage');
//                    //console.log('ONSCREENNOTIFICATION');
//                    getBondsNotifCount(document.getElementById("ctl00_hdnUserNameForNotification").value);
//                }
//            };
//            wsbonds.onerror = function (evt) {
//                //alert('Error occured..');
//                //alert("EventType " + evt.type);
//                //alert("readystate " + ws.readystate);
//                //alert('Error with code : ' + evt.code + '', 'error');
//            };
//            wsbonds.onclose = function (evt) {
//                wsbonds.close();
//                SubScribBonds(WebSocketIP, USERID);

//            };
//        }
//    }
//}
//commented by shreyasv For signalr notifications replacement 8-jan-2021 -end  PLEASE CONTACT BONDS TEAM INCASE ANY QUERIES


function ValidInt(tbControl) {
    var ControlText;
    try {
        ControlText = document.getElementById(tbControl).value
        var C, d;
        if (ControlText.length > 0) {
            for (i = 0; i < ControlText.length; i++) {
                d = ControlText.charAt(i)
                if ((d < '0') || (d > '9') && (d = '-')) {
                    C = ControlText.substring(0, i)
                    document.getElementById(tbControl).value = C
                    document.getElementById(tbControl).focus();
                    return false
                }
            }
        }
        return true
    }
    catch (error) {
        WriteLog_Error(" ValidInt " + error.message);
    }
    finally {
        ControlText = null;
        tbControl = null;
    }
}

function AllowOnlyNumeric() {
    var key;
    try {
        key = window.event.keyCode;

        if (key > 47 && key < 58)
            return;
        else
            window.event.returnValue = null;

    }
    catch (error) {
        WriteLog_Error(" AllowOnlyNumeric " + error.message);
    }
    finally {
        key = "";
    }
}
function allowNominalWithMKBDecimalwithoutMinus(event, ctl, decimalPoint) {
    var charCode;
    var txt;
    var len;
    var dot;
    var minus;
    var m_low, b_low, k_low, m_Cap, b_Cap, k_Cap;
    if (event.shiftKey && event.keyCode == 45) { return false; }
    try {
        charCode = (event.which) ? event.which : event.keyCode;
        if (charCode == 8 || charCode == 9 || charCode == 37 || charCode == 38 || charCode == 39 || charCode == 40 || charCode == 46) {
            return true;
        }
        txt = $(ctl).val();
        len = txt.length;
        dot = txt.indexOf('.');
        minus = txt.indexOf('-');
        m_low = txt.indexOf('m');
        b_low = txt.indexOf('b');
        k_low = txt.indexOf('k');
        m_Cap = txt.indexOf('M');
        b_Cap = txt.indexOf('B');
        k_Cap = txt.indexOf('K');
        mLen = txt.split('m').length;
        kLen = txt.split('k').length;
        bLen = txt.split('b').length;
        dotLen = txt.split('.').length;
        if (((charCode > 47 || charCode < 58) && event.shiftKey) || charCode == 107 || charCode == 109) { return false; }
        if (charCode > 31 && (charCode < 45 || (charCode > 57 && charCode < 96) || charCode > 105) && charCode != 46 && (charCode != 66 && charCode != 77 && charCode != 75) && (charCode != 98) && charCode != 190 && charCode != 110) {
            return false;

        } else {

            if (charCode == 47) {
                return false;
            }
            if (m_low >= 0 && charCode == 109) {

                return false;
            }

            if (b_low >= 0 && charCode == 98) {
                return false;
            }
            if (k_low >= 0 && charCode == 107) {
                return false;
            }
            if (m_Cap >= 0 && charCode == 77) {
                return false;
            }
            if (b_Cap >= 0 && charCode == 66) {
                return false;
            }
            if (k_Cap >= 0 && charCode == 75) {
                return false;
            }
            if (dot >= 0 && charCode == 46) {
                return false;
            }
            if (minus > -2 && charCode == 45) {
                return false;
            }

            if (event.keyCode == 65 || event.keyCode == 191 || event.keyCode == 76 || event.keyCode >= 67 && event.keyCode <= 74 || event.keyCode >= 78 && event.keyCode <= 90
                || event.keyCode >= 106 && event.keyCode <= 109 || event.keyCode == 111 || event.keyCode >= 186 && event.keyCode <= 188) {
                return false
            }

            if (dot > 0 || minus > 0) {
                var CharAfterdot = (len + 1) - dot;
                if (CharAfterdot > (Number(decimalPoint) + 1)) {
                    if (event.keyCode == 8 || event.keyCode == 46 || event.keyCode == 75 || event.keyCode == 77 || event.keyCode == 66 || event.keyCode == 9) {
                        return true;
                    } else if ((event.keyCode > 47 && event.keyCode < 58) || (event.keyCode >= 96 && event.keyCode <= 105)) {
                        return true;
                    }
                    else { return false }
                    return false;
                }
            }
            if (dotLen > 1) {
                var nextChar = event.keyCode;
                var prevChar = txt.charAt(len - 1);
                if (nextChar == 75 || nextChar == 77 || nextChar == 66) {
                    if (prevChar == "." && (nextChar == 75 || nextChar == 77 || nextChar == 66)) {
                        return false
                    }
                    //var CharAfterdot = event.keyCode
                    //  //  if (CharAfterdot >=48 && CharAfterdot <=57 || CharAfterdot >=96 && CharAfterdot <=105 ) { 
                    //              if (CharAfterdot == 77 || CharAfterdot == 76 || CharAfterdot == 75) {
                    //            return false
                    //            }
                    //           return false
                    //      //  }
                }

                if (event.keyCode == 110 || event.keyCode == 190) {
                    return false
                }
                else {
                    return true
                }
            }
            if (mLen > 1 || kLen > 1 || bLen > 1) {
                if (event.keyCode == 8 || event.keyCode == 46 || event.keyCode == 9) {

                    return true;
                }
                return false;
            }
        }
        return true;
    }
    catch (error) {
        WriteLog_Error("allowNominalWithMKBDecimalwithoutMinus :" + er.message);
    }
    finally {
        charCode = null;
        txt = null;
        len = null;
        dot = null;
        minus = null;
        m_low = null;
        b_low = null;
        k_low = null;
        m_Cap = null;
        b_Cap = null;
        k_Cap = null;

    }

}

function allowNominalWithMKBwithoutMinus(event, ctl) {
    var charCode;
    var txt;
    var len;
    var dot;
    var minus;
    var m_low, b_low, k_low, m_Cap, b_Cap, k_Cap;
    if (event.shiftKey && event.keyCode == 45) { return false; }
    try {
        charCode = (event.which) ? event.which : event.keyCode
        if (charCode == 8 || charCode == 9 || charCode == 37 || charCode == 38 || charCode == 39 || charCode == 40 || charCode == 46) {
            return true;
        }
        txt = $(ctl).val();
        len = txt.length;
        dot = txt.indexOf('.');
        minus = txt.indexOf('-');
        m_low = txt.indexOf('m');
        b_low = txt.indexOf('b');
        k_low = txt.indexOf('k');
        m_Cap = txt.indexOf('M');
        b_Cap = txt.indexOf('B');
        k_Cap = txt.indexOf('K');
        if (((charCode > 47 || charCode < 58) && event.shiftKey) || charCode == 107 || charCode == 109) { return false; }
        if (charCode > 31 && (charCode < 45 || (charCode > 57 && charCode < 96) || charCode > 105) && charCode != 46 && (charCode != 66 && charCode != 77 && charCode != 75)
            && (charCode != 98)) {
            return false;

        } else {
            if (charCode == 47) {
                return false;
            }
            if (m_low >= 0 && charCode == 109) {
                return false;
            }
            if (b_low >= 0 && charCode == 98) {
                return false;
            }
            if (k_low >= 0 && charCode == 107) {
                return false;
            }
            if (m_Cap >= 0 && charCode == 77) {
                return false;
            }
            if (b_Cap >= 0 && charCode == 66) {
                return false;
            }
            if (k_Cap >= 0 && charCode == 75) {
                return false;

            }
            if (dot >= 0 && charCode == 46) {
                return false;
            }
            if (minus > -2 && charCode == 45) {
                return false;
            }
            if (dot > 0 || minus > 0) {
                var CharAfterdot = (len + 1) - dot;
                if (CharAfterdot > 10) {
                    return false;
                }
            }
        }
        return true;
    }
    catch (error) {
        WriteLog_Error("allowNominalWithMKBwithoutMinus :" + er.message);
    }
    finally {
        charCode = null;
        txt = null;
        len = null;
        dot = null;
        minus = null;
        m_low = null;
        b_low = null;
        k_low = null;
        m_Cap = null;
        b_Cap = null;
        k_Cap = null;

    }
}


//<input type="text" value="95.00" onKeyPress="return onlyNumberDecimal(event, this);" />
//Added by ArshadM for share searching issue
function disableSomeSpecialChar(evt) {
    try {
        var letters = /^[<>?]*$/;
        var charCode = (evt.which) ? evt.which : event.keyCode;
        var keyPressed = String.fromCharCode(charCode);
        if (letters.test(keyPressed)) {
            return false;
        }
        else {
            return true;
        }
    } catch (er) { WriteLog_Error("disableSomeSpecialChar  :" + er.message); }

}

function onlyNumberDecimal(event, ctl) {
    var charCode;
    var txt;
    var len;
    var dot;
    var minus;
    if (event.shiftKey && event.keyCode == 45) { return false; }
    //var regex1 = RegExp('^(\d*\.)?\d+$');
    //return regex1.test($(ctl).val());
    try {
        charCode = (event.which) ? event.which : event.keyCode
        if (charCode == 8 || charCode == 9 || charCode == 37 || charCode == 38 || charCode == 39 || charCode == 40 || charCode == 46) {
            return true;
        }
        if (((charCode > 47 || charCode < 58) && event.shiftKey) || charCode == 107) { return false; }
        txt = $(ctl).val();
        len = txt.length;
        dot = txt.indexOf('.');
        //minus = txt.indexOf('-');

        if (charCode > 31 && (charCode < 45 || (charCode > 57 && charCode < 96) || charCode > 105) && charCode != 46 && charCode != 190 && charCode != 110) {
            return false;

        } else {
            if (dot >= 0 && charCode == 46) {
                return false;
            }
            if (charCode == 45) {
                return false;
            }
            if (dot > 0) {
                var CharAfterdot = (len + 1) - dot;
                if (CharAfterdot > 10) {
                    return false;
                }
            }
        }
        return true;
    }
    catch (error) {
        WriteLog_Error("onlyNumberDecimal  :" + error.message);
    }
    finally {
        charCode = null;
        txt = null;
        len = null;
        dot = null;
        minus = null;
    }
}


function onlyNumber(event, ctl) {
    console.log(event.type);
    var charCode;
    var txt;
    var len;
    var dot;
    var minus;
    if (event.shiftKey && event.keyCode == 45) { return false; }
    if (event.shiftKey) { return false; }  //Added by MohitM || Approved by shekhar sir || BBVAORINT-246
    try {
        charCode = (event.which) ? event.which : event.keyCode
        txt = $(ctl).val();
        len = txt.length;
        dot = txt.indexOf('.');
        minus = txt.indexOf('-');

        if (charCode == 8 || charCode == 9 || charCode == 37 || charCode == 38 || charCode == 39 || charCode == 40) { //added by devesh for arrow keys working on 7-Feb-2020 
            return true;
        }

        if (charCode > 31 && (charCode < 45 || (charCode > 57 && charCode < 96) || charCode > 105)) {
            return false;
        }
        return true;
    }
    catch (error) {
        WriteLog_Error("onlyNumber  :" + error.message);
    }
    finally {
        charCode = null;
        txt = null;
        len = null;
        dot = null;
        minus = null;
    }
}



function allowNominalWithMKB(event, ctl) {
    var charCode;
    var txt;
    var len;
    var dot;
    var minus;
    var m_low, b_low, k_low, m_Cap, b_Cap, k_Cap;

    try {
        charCode = (event.which) ? event.which : event.keyCode
        txt = $(ctl).val();
        len = txt.length;
        dot = txt.indexOf('.');
        minus = txt.indexOf('-');
        m_low = txt.indexOf('m');
        b_low = txt.indexOf('b');
        k_low = txt.indexOf('k');
        m_Cap = txt.indexOf('M');
        b_Cap = txt.indexOf('B');
        k_Cap = txt.indexOf('K');

        if (charCode > 31 && (charCode < 45 || charCode > 57) && charCode != 46 && (charCode != 66 && charCode != 77 && charCode != 75)
            && (charCode != 98 && charCode != 107 && charCode != 109)) {
            return false;

        } else {
            if (m_low >= 0 && charCode == 109) {
                return false;
            }
            if (b_low >= 0 && charCode == 98) {
                return false;
            }
            if (k_low >= 0 && charCode == 107) {
                return false;
            }
            if (m_Cap >= 0 && charCode == 77) {
                return false;
            }
            if (b_Cap >= 0 && charCode == 66) {
                return false;
            }
            if (k_Cap >= 0 && charCode == 75) {
                return false;

            }
            if (dot >= 0 && charCode == 46) {
                return false;
            }
            if (minus >= 0 && charCode == 45) {
                return false;
            }
            if (dot > 0 || minus > 0) {
                var CharAfterdot = (len + 1) - dot;
                if (CharAfterdot > 10) {
                    return false;
                }
            }
        }
        return true;
    }
    catch (error) {
        WriteLog_Error("allowNominalWithMKB  :" + error.message);
    }
    finally {
        charCode = null;
        txt = null;
        len = null;
        dot = null;
        minus = null;
        m_low = null;
        b_low = null;
        k_low = null;
        m_Cap = null;
        b_Cap = null;
        k_Cap = null;

    }
}



function AllowOnlyNumeric_withoutDecimal(evt) {
    var charCode;
    try {
        //shekhar L. 
        evt = (evt) ? evt : window.event;
        charCode = (evt.which) ? evt.which : evt.keyCode;
        if (charCode > 31 && ((charCode < 48 || charCode > 57) && (charCode < 95 || charCode > 106))) {
            return false;
        }
        return true;
    }
    catch (error) {
        WriteLog_Error("AllowOnlyNumeric_withoutDecimal  :" + error.message);
    }
    finally {
        evt = null;
        charCode = null;
    }

}


function AllowValidPhoneNumber() {
    var key;
    try {
        key = window.event.keyCode;

        if (key > 47 && key < 58)
            return;
        else

            if (key == 40 || key == 41 || key == 43 || key == 45) {
                return;
            }
            else {
                window.event.returnValue = null;
            }
    }
    catch (error) {
        WriteLog_Error("AllowValidPhoneNumber  :" + error.message);
    }
    finally {
        key = null;
    }

}

function DisAllowOnlyNumeric() {

    try {
        key = window.event.keyCode;

        if (key > 47 && key < 58)
            window.event.returnValue = null;
        else
            return;
    }
    catch (error) {
        WriteLog_Error("DisAllowOnlyNumeric  :" + error.message);
    }
    finally {
        key = null;
    }
}

function validDecimalwithPrecision(tbControl) {
    var countMinus = 0;
    var ControlText;
    var C, d, index;
    var precision;
    try {
        ControlText = document.getElementById(tbControl).value
        if (ControlText.length > 0) {
            if (ControlText.charAt(0) == '.') {
                countMinus = 1
            }


            for (i = countMinus; i < ControlText.length; i++) {
                d = ControlText.charAt(i)

                if (((d < '0') || (d > '9'))) {

                    c = ControlText.substring(0, i)
                    document.getElementById(tbControl).value = c
                    return false;
                }

                if (ControlText.indexOf('.') > -1) {
                    index = ControlText.indexOf('.')
                    if (ControlText.indexOf('.', index + 1) > -1) {
                        index = ControlText.indexOf('.', index + 1);
                        document.getElementById(tbControl).value = ControlText.substring(0, index);
                        return false;
                    }
                }


                if (ControlText.indexOf('.') > -1) {

                    index = ControlText.indexOf('.')
                    precision = ControlText.length - index
                    if (ControlText.length >= index + precision) {
                        document.getElementById(tbControl).value = ControlText.substring(0, index + precision + 1)
                    }
                }

            } //end for

        } //end if 
        return true;

    }
    catch (error) {
        WriteLog_Error("validDecimalwithPrecision  :" + error.message);
    }
    finally {
        tbControl = null;
        ControlText = null;
        countMinus = null;
        C = null;
        d = null;
        index = null;
        precision = null;
    }
}

function replaceAll(text, strA, strB) {
    try {
        return text.replace(new RegExp(strA, "g"), strB);
    }
    catch (error) {
        WriteLog_Error("replaceAll  :" + error.message);
    }
    finally {
        text = null;
        strA = null;
        strB = null;
    }
}
function AllowNumericWithdecimal(cntl) {
    try {
        cntrlval = document.getElementById(cntl).value;

        if (cntrlval.indexOf(".") < 0) {
            key = window.event.keyCode;

            if ((key > 47 && key < 58) || key == 46)
                return;
            else
                window.event.returnValue = null;
        }
        else {
            var key = window.event.keyCode;
            //alert(key)
            if (key != 46) {
                if ((key > 47 && key < 58))
                    return;
                else
                    window.event.returnValue = null;
            }
            else {
                window.event.returnValue = null;
            }
        }
    }
    catch (error) {
        WriteLog_Error("AllowNumericWithdecimal  :" + error.message);
    }
    finally {
        cntl = null;
        cntrlval = null;
        key = null;
    }
}

function AllowNumericWithdecimal_OrderEntry(cntl) {
    var cntrlval;
    try {
        cntrlval = document.getElementById(cntl).value;


        if (cntrlval.indexOf(".") < 0) {
            var key = window.event.keyCode;

            if ((key > 47 && key < 58) || key == 46)
                return;
            else
                window.event.returnValue = null;
        }
        else {
            var key = window.event.keyCode;
            //alert(key)
            if ((key != 46) || (key != 188)) {
                if ((key > 47 && key < 58))
                    return;
                else
                    window.event.returnValue = null;
            }
            else {
                window.event.returnValue = null;
            }
        }
    }
    catch (error) {
        WriteLog_Error("AllowNumericWithdecimal_OrderEntry  :" + error.message);
    }
    finally {
        cntl = null;
        cntrlval = null;
        key = null;
    }
}

function AllowNumericWithdecimalandMinus(cntl) {
    var cntrlval;
    try {

        if (isTextSelected(cntl)) {
            document.getElementById(cntl).value = "";
            cntrlval = "";
        }
        else {
            cntrlval = document.getElementById(cntl).value;
        }

        var key = window.event.keyCode;
        if ((cntrlval != "") && (key == 45)) {
            window.event.returnValue = null;
            return;
        }

        if (cntrlval.indexOf(".") < 0) {
            // var key = window.event.keyCode;

            if (cntrlval.length == 0) {
                if (key == 45) {
                    return;
                }
            }
            else {
                if (key == 45 && cntrlval.indexOf("-") < 0) {
                    cntrlval = "-" + cntrlval
                    window.event.returnValue = null;
                    //  return;
                }
            }

            if ((key > 47 && key < 58) || key == 46)
                return;
            else
                window.event.returnValue = null;
        }
        else {
            var key = window.event.keyCode;
            //alert(key)

            if (key != 46) {
                if ((key > 47 && key < 58))
                    return;
                else
                    window.event.returnValue = null;
            }
            else {
                window.event.returnValue = null;
            }
        }
    }
    catch (error) {
        WriteLog_Error("AllowNumericWithdecimalandMinus  :" + error.message);
    }
    finally {
        cntl = null;
        cntrlval = null;
        key = null;
    }
}


/* function added by Sonal on 12-Mar-2013. To check if textbox text is selected  */
function isTextSelected(cntl) {
    try {
        input = document.getElementById(cntl);
        if (typeof input.selectionStart == "number") {
            return input.selectionStart == 0 && input.selectionEnd == input.value.length;
        } else if (typeof document.selection != "undefined") {
            input.focus();
            return document.selection.createRange().text == input.value;
        }
    }
    catch (error) {
        WriteLog_Error("isTextSelected  :" + error.message);
    }
    finally {
        cntl = null;
        cntrlval = null;
        key = null;
        input = null;
    }
}

function validDecimalwithPrecisionwithnegative(tbControl) {
    var countMinus = 0;
    var ControlText;
    var C, d, index;
    var precision;

    try {
        ControlText = document.getElementById(tbControl).value;
        if (ControlText.length > 0) {
            if (ControlText.charAt(0) == '-') {
                countMinus = 1
            }

            for (i = countMinus; i < ControlText.length; i++) {
                d = ControlText.charAt(i)

                if (((d < '0') || (d > '9')) && (d != '.')) {

                    c = ControlText.substring(0, i)
                    document.getElementById(tbControl).value = c
                    return false;
                }

                if (ControlText.indexOf('.') > -1) {
                    index = ControlText.indexOf('.')
                    if (ControlText.indexOf('.', index + 1) > -1) {
                        index = ControlText.indexOf('.', index + 1);
                        document.getElementById(tbControl).value = ControlText.substring(0, index);
                        return false;
                    }
                }


                if (ControlText.indexOf('.') > -1) {

                    index = ControlText.indexOf('.')
                    precision = ControlText.length - index
                    if (ControlText.length >= index + precision) {
                        document.getElementById(tbControl).value = ControlText.substring(0, index + precision + 1)
                    }

                }


            } //end for

        } //end if 
        return true;
    }
    catch (error) {
        WriteLog_Error("validDecimalwithPrecisionwithnegative  :" + error.message);
    }
    finally {
        tbControl = null;
        ControlText = null;
        countMinus = null;
        C = null;
        d = null;
        index = null;
        precision = null;
    }
}



function Sgn(Integer1) {
    Number1 = Integer1.toLowerCase();
    RefString = "0123456789-";
    try {
        if (Number1.length < 1)
            return (false);
        for (var i = 0; i < Number1.length; i++) {
            var ch = Number1.substr(i, 1)
            var a = RefString.indexOf(ch, 0)
            if (a == -1)
                return (false);
        }
        if (Integer1 < 0)
            return (-1);
        else if (Integer1 == 0)
            return (0);
        else
            return (1);
    }
    catch (error) {
        WriteLog_Error("Sgn  :" + error.message);
    }
    finally {
        Number1 = null;
        Integer1 = null;
        RefString = null;
    }
}

/* 11-jan-2020 for billion number format
function AmountFormat_bkp(cntrlID, decimalPts) {
    var amt;
    var index;
    var rel_Amount;
    try {

        amt = document.getElementById(cntrlID).value.replace(',', '');
        index = document.getElementById(cntrlID).value.indexOf(',');
        rel_Amount = /\d+(K$(?![K|M|B])|M$(?![K|M|B])|B$(?![K|M|B]))/i;

        if (amt != null) {

            if (amt.search(rel_Amount) != -1) {
                document.getElementById(cntrlID).value = FormatAmount(Number(FormatNotional(amt)).toFixed(Number(decimalPts)));
            }
            else {
                amt = amt.replace(',', '');
                document.getElementById(cntrlID).value = FormatAmount(Number(amt).toFixed(Number(decimalPts)));
            }


        }
        else {
            document.getElementById(cntrlID).value = Number(amt).toFixed(Number(decimalPts));

        }
    }
    catch (error) {
        WriteLog_Error("AmountFormat  :" + error.message);
    }
    finally {
        cntrlID = null;
        decimalPts = null;
        amt = null;
        index = null;
        rel_Amount = null;
    }

}*/

function AmountFormat(cntrlID, decimalPts) {
    var amt;
    var index;
    var rel_Amount;
    try {

        amt = String(document.getElementById(cntrlID).value).replace(',', '');
        index = String(document.getElementById(cntrlID).value).indexOf(',');
        rel_Amount = /\d+(K$(?![K|M|B])|M$(?![K|M|B])|B$(?![K|M|B]))/i;

        if (amt != null) {

            if (amt.search(rel_Amount) != -1) {
                document.getElementById(cntrlID).value = FormatAmount(Number(FormatNotional(amt)).toFixed(Number(decimalPts)));
            }
            else {
                amt = amt.replaceAll(',', '');
                document.getElementById(cntrlID).value = FormatAmount(Number(amt).toFixed(Number(decimalPts)));
            }


        }
        else {
            document.getElementById(cntrlID).value = Number(amt).toFixed(Number(decimalPts));

        }
    }
    catch (error) {

    }
    finally {
        cntrlID = null;
        decimalPts = null;
        amt = null;
        index = null;
        rel_Amount = null;
    }

}
function FormatNotional(notional) {
    var rel_Amount = /\d+(K$(?![K|M|B])|M$(?![K|M|B])|B$(?![K|M|B]))/i;
    var rel_Char = /(K|M|B)/i;
    var pos;
    var number;
    var rel_invalidChar = /[\#|\@|!|\&|\*|\%|\\|\+|\*|\^]/;
    try {
        //var rel_Amount = /([-+]?([0-9]*\.)?[0-9]+[K|M|B]*$)/i;
        if (notional.search(rel_invalidChar) != -1) {
            return null;
        }
        if (notional.search(rel_Amount) != -1) {
            if ((notional.search('K') != -1) || (notional.search('k') != -1)) {
                pos = notional.search(rel_Char);
                //alert(pos);
                if (pos !== 0) {
                    number = notional.substring(0, pos);
                    number = number * 1000;
                } else {
                    //number = 1000;
                    return null;
                }
                //return number;
                //Modified By Dinesh On 06-May-2020.
                //return number.toLocaleString();
                return number.toLocaleString('en-US', { minimumFractionDigits: 2 });
            }
            if ((notional.search('M') != -1) || (notional.search('m') != -1)) {
                pos = notional.search(rel_Char);
                if (pos !== 0) {
                    number = notional.substring(0, pos);
                    number = number * 1000000;
                } else {
                    //number = 1000000;
                    return null;
                }
                //Modified By Dinesh On 06-May-2020.
                //return number.toLocaleString();
                return number.toLocaleString('en-US', { minimumFractionDigits: 2 });
            }
            if ((notional.search('B') != -1) || (notional.search('b') != -1)) {
                pos = notional.search(rel_Char);
                if (pos !== 0) {
                    number = notional.substring(0, pos);
                    number = number * 1000000000;
                } else {
                    //number = 1000000000;
                    if (notional.search(/[A-Z]/i) != -1)
                        return null;
                    return null;
                }
                //Modified By Dinesh On 06-May-2020.
                //return number.toLocaleString();
                return number.toLocaleString('en-US', { minimumFractionDigits: 2 });
            }
        } else {
            if (notional.search(/[A-Z]/i) != -1) {
                return null;
                //return notional;
            }
            else {
                return notional;
            }
        }
    }
    catch (error) {
        WriteLog_Error("FormatNotional  :" + error.message);
    }
    finally {
        rel_Amount = null;
        rel_Char = null;
        pos = null;
        number = null;
        rel_invalidChar = null;
        notional = null;
    }
}

function FormatAmount(nStr) {
    try {
        nStr += '';
        x = nStr.split('.');
        x1 = x[0];
        x2 = x.length > 1 ? '.' + x[1] : '';
        var rgx = /(\d+)(\d{3})/;
        while (rgx.test(x1)) {
            x1 = x1.replace(rgx, '$1' + ',' + '$2');
        }
        return x1 + x2;
    }
    catch (error) {

    }
    finally {
        nStr = null;
        x = null;
        x1 = null;
        x2 = null;
        rgx = null;
    }
}


function isNumber(amt) {
    try {
        return isNaN(amt.value)
    }
    catch (error) {

    }
    finally {
        amt = null;
    }
}


function IsDecimalExist(cntl) {
    try {
        if (cntl.value.indexOf(".") > 0) {
            return true;
        }
        else {
            return false;
        }
    }
    catch (error) {

    }
    finally {
        return;
    }
}

function IsMinusSignExist(cntl) {
    try {
        if (cntl.value.indexOf("-") > 0) {
            return true;
        }
        else {
            return false;
        }
    }
    catch (error) {

    }
    finally {
        cntl = null;
    }
}

function DaysInMonth(dDate) {
    var dt1, cmn1, cmn2, dtt, lflag, dycnt;
    var temp1;
    var temp2;
    try {
        if (dDate == null)
            return (false);
        dDate = new Date(dDate);
        temp1 = dDate.getMonth() + 1;
        temp2 = dDate.getYear();
        dt1 = new Date(temp2, temp1 - 1, 1)
        cmn1 = dt1.getMonth()
        dtt = dt1.getTime() + 2332800000
        lflag = true
        dycnt = 28
        while (lflag) {
            dtt = dtt + 86400000
            dt1.setTime(dtt)
            cmn2 = dt1.getMonth()
            if (cmn1 != cmn2)
                lflag = false
            else
                dycnt = dycnt + 1;
        }
        if (dycnt > 31)
            dycnt = 31;

        return dycnt;
    }
    catch (error) {

    }
    finally {
        dDate = null;
        dt1 = null;
        cmn1 = null;
        cmn2 = null;
        dtt = null;
        lflag = null;
        dycnt = null;
        temp1 = null;
        temp2 = null;
    }
}

//-------------------- Date validation --------------------------------//
function isvaild_dateddMMMyyyy(dateStr) {
    try {
        // Checks for the following valid date formats:

        // MM/DD/YYYY   MM-DD-YYYY				
        //var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{4})$/;
        var strsplitdate = dateStr.toUpperCase();
        dateStr = strsplitdate;
        var datePat = /^(([0-9])|([0-2][0-9])|([3][0-1]))(\/|-)(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec|JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC|jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)(\/|-)\d{4}$/;

        //dd-MMM-yyyy   dd/MMM/yyyy

        var matchArray = dateStr.match(datePat)
        if (matchArray == null)
            return false

        month = matchArray[6]
        day = matchArray[1]
        year = matchArray[6]


        if (month < 1 || month > 12)
            return false

        if (day < 1 || day > 31)
            return false

        if ((month == 4 || month == 6 || month == 9 || month == 11) && day == 31)
            return false

        if (month == 2) {
            var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0))
            if (day > 29 || (day == 29 && !isleap))
                return false;
        }
        return true;
    }
    catch (error) {

    }
    finally {
        return;
    }
}



//**************************Trim******************************************************************** 
// Removes leading whitespaces
function LTrim(value) {
    try {
        var re = /\s*((\S+\s*)*)/;
        return value.replace(re, "$1");
    }
    catch (error) {

    }
    finally {
        return;
    }
}
// Removes ending whitespaces
function RTrim(value) {
    try {
        var re = /((\s*\S+)*)\s*/;
        return value.replace(re, "$1");
    }
    catch (error) {

    }
    finally {
        return;
    }
}
// Removes leading and ending whitespaces
function Trim(value) {
    try {
        return LTrim(RTrim(value));
    }
    catch (error) {

    }
    finally {

    }
}
//***********

function CreateExcelSheetAutoFit(cntrlGrid) {
    try {
        // alert(cntrlGrid);
        var tbl = cntrlGrid;
        var x = tbl.rows;
        try {
            var xls = new ActiveXObject("Excel.Application");
            var handle = xls.Workbooks.Add;
        }
        catch (e) {
            document.getElementById('ctl00_MainContent_' + 'lblError').innerText = "Please Check Browser setting Tools-->Internet Option-->Security-->Custom Level-->Initialize and script ActiveX controls not marked and safe  Make it enable.";
        }
        for (i = 0; i < x.length; i++) {
            var y = x[i].cells;
            for (j = 0; j < y.length; j++) {
                xls.Cells(i + 1, j + 1).Value = "'" + y[j].innerText;
            }
        }
        xls.visible = true;
        if (y.length <= 26) {
            var rng = xls.Columns(String.fromCharCode(65, 58, 65 + y.length - 1));
            rng.AutoFit;
        }
    }
    catch (e) {
        document.getElementById('ctl00_MainContent_' + 'lblError').innerText = "Please Check Browser setting Tools-->Internet Option-->Security-->Custom Level-->Initialize and script ActiveX controls not marked and safe  Make it enable.";
    }

}

//Change done by PB: 22Dec2010
//New function added for eligibility screen - as customer pan, name and order ref had to be shown.
function CreateExcelSheetAutoFit_EC(cntrlGrid, CustomerName, CustomerPan, OrderRef) {
    try {
        var tbl = cntrlGrid;
        var x = tbl.rows;
        try {
            var xls = new ActiveXObject("Excel.Application");
            var handle = xls.Workbooks.Add;
        }
        catch (e) {
            document.getElementById('ctl00_MainContent_' + 'lblError').innerText = "Please Check Browser setting Tools-->Internet Option-->Security-->Custom Level-->Initialize and script ActiveX controls not marked and safe  Make it enable.";
        }
        //Cell 0: Customerpan
        xls.Cells(1, 1).Value = "'Customer Name ";
        xls.Cells(1, 2).Value = "'" + CustomerPan;
        //Cell 1: Customer name 
        xls.Cells(2, 1).Value = "'Customer Pan ";
        xls.Cells(2, 2).Value = "'" + CustomerName;
        //Cell 2: Scheme
        xls.Cells(3, 1).Value = "'Order Ref No. ";
        xls.Cells(3, 2).Value = "'" + OrderRef;

        for (i = 0; i < x.length; i++) {
            var y = x[i].cells;

            for (j = 0; j < y.length; j++) {
                if (i === 0) {
                    xls.Cells(i + 5, j + 1).Value = "'" + y[j].innerText;
                    xls.Cells(i + 5, j + 1).font.bold = true;
                }
                else {
                    xls.Cells(i + 5, j + 1).Value = "'" + y[j].innerText;
                }
            }
        }
        xls.visible = true;
        if (y.length <= 26) {
            var rng = xls.Columns(String.fromCharCode(65, 58, 65 + y.length - 1));
            rng.AutoFit;
        }
    }
    catch (e) {
        document.getElementById('ctl00_MainContent_' + 'lblError').innerText = "Please Check Browser setting Tools-->Internet Option-->Security-->Custom Level-->Initialize and script ActiveX controls not marked and safe  Make it enable.";
    }
}


function InStr(strSearch, charSearchFor) {
    try {
        //alert("InStr                 "+strSearch);
        var temp = "'" + strSearch + "'";
        //alert(temp.length);
        for (i = 0; i < temp.length; i++) {	//alert(Mid(strSearch, i, 1)); 
            if (charSearchFor == Mid(strSearch, i, 1)) {
                //alert("FOUNd"+i);
                return i;
            }
        }
        return 0;
    }
    catch (error) {

    }
    finally {

    }
}
function PreventEntry() {
    try {
        window.event.returnValue = null;
    }
    catch (error) {

    }
    finally {

    }
}

function Abs(Number) {
    try {
        Number = Number.toLowerCase();
        RefString = "0123456789.-";

        if (Number.length < 1)
            return (false);

        for (var i = 0; i < Number.length; i++) {
            var ch = Number.substr(i, 1)
            var a = RefString.indexOf(ch, 0)
            if (a == -1)
                return (false);
        }

        if (Number < 0)
            return (Number * -1)

        return Number;
    }
    catch (error) {

    }
    finally {

    }
}

function Len(string) {
    try {
        if (string == null)
            return (false);

        return String(string).length;
    }
    catch (error) {

    }
    finally {

    }
}
function Chr(CharCode) {
    try {
        return String.fromCharCode(CharCode);
    }
    catch (error) {

    }
    finally {

    }
}
function Left(String, Length) {
    try {
        if (String == null)
            return (false);

        return String.substr(0, Length);
    }
    catch (error) {

    }
    finally {

    }
}

function Right(String, Length) {
    try {
        if (String == null)
            return (false);

        var dest = '';
        for (var i = (String.length - 1); i >= 0; i--)
            dest = dest + String.charAt(i);

        String = dest;
        String = String.substr(0, Length);
        dest = '';

        for (var i = (String.length - 1); i >= 0; i--)
            dest = dest + String.charAt(i);

        return dest;
    }
    catch (error) {

    }
    finally {

    }
}

function Mid(String, Start, Length) {
    try {
        if (String == null)
            return (false);

        if (Start > String.length)
            return '';

        if (Length == null || Length.length == 0)
            return (false);

        return String.substr((Start - 1), Length);
    }
    catch (error) {

    }
    finally {

    }
}


/////////Format number with decimal rounding
//////// First Parameter ctrl---set as 'this'
/////////Second as  val--- rounding decimal
function FormatRound(ctrl, val1) {
    try {
        if (document.getElementById(ctrl).value != "") {

            if (isNaN(document.getElementById(ctrl).value) == false) {
                var num = parseFloat(document.getElementById(ctrl).value)
                document.getElementById(ctrl).value = num.toFixed(val1)
            }
            else {
                document.getElementById(ctrl).value = ""
            }
        }
    }
    catch (error) {

    }
    finally {

    }
}

function ValidateTenorOnKeyPress(tabcontrol) {
    try {
        var Tenor = document.getElementById(tabcontrol).value;
        var TenorLength = Tenor.length - 1;

        var key = window.event.keyCode;
        if (isNaN(document.getElementById(tabcontrol).value)) {

            window.event.returnValue = null;
        }
        else {

            if ((key > 47 && key < 58) || (key == 100) || (key == 119) || (key == 109) || (key == 121) || (key == 77) || (key == 68) || (key == 87) || (key == 89))
                return;
            else
                window.event.returnValue = null;
        }
    }
    catch (error) {

    }
    finally {

    }
}

function selectAll(invoker) {
    try {
        var inputElements = document.getElementsByTagName('input');
        for (var i = 0; i < inputElements.length; i++) {
            var myElement = inputElements[i];
            if (myElement.type == "checkbox") {
                myElement.checked = invoker.checked;
            }
        }
    }
    catch (error) {

    }
    finally {

    }
}


function TenorValidation2(tabcontrol) {
    try {
        var Tenor = document.getElementById(tabcontrol).value;
        var TenorLength = Tenor.length - 1;
        //alert(Tenor)
        var d, c;
        for (i = 0; i < TenorLength; i++) {
            d = Tenor.charAt(i)
            //alert(d)
            if (((d < '0') || (d > '9'))) {
                c = Tenor.substring(0, i)
                document.getElementById(tabcontrol).value = c
                var tmlen = document.getElementById(tabcontrol).length - 1
                //   alert(tmlen)
                //    alert(document.getElementById(tabcontrol).value)
                switch (c.charAt(tmlen).toUpperCase) {

                    case 'Y':
                        return true;
                        break;
                    case 'M':
                        return true;
                        break;
                    case 'D':
                        return true;
                        break;
                    default:
                        d = Tenor.charAt(Tenor.length)
                        if (((d < '0') || (d > '9'))) {
                            c = Tenor.substring(0, Tenor.length)
                            document.getElementById(tabcontrol).value = c
                            return false;
                        }
                }
                return false;
            }

        }
        switch (Tenor.charAt(Tenor.length).toUpperCase) {

            case 'Y':
                return true;
                break;
            case 'M':
                return true;
                break;
            case 'D':
                return true;
                break;
            default:
                d = Tenor.charAt(Tenor.length)
                if (((d < '0') || (d > '9'))) {
                    c = Tenor.substring(0, Tenor.length)
                    document.getElementById(tabcontrol).value = c
                    return false;
                }
        }
    }
    catch (error) {

    }
    finally {

    }
}
//Change done by Amit Alone on 09-Nov-2011 for setting business date to user control 
//updated by Shekhar L/Akshay D. @07-Apr-2022  UWI-308  added validations on invalid date enter BBVA 
function checkdate(txtDate, serverdate, Format) {
    var dateText = document.getElementById(txtDate).value;
    //AshwiniP on 29-11-2018 - BNPP Date control editable in the format of dd/MM/yyyy START
    if (dateText.indexOf("/") > -1) {
        var dateParts = dateText.split("/");
        if (event.type == "blur") {
            if (dateParts.length < 3) {
                alert("Date format Must be e.g.12-Mar-2012 and >=1900");
                document.getElementById(txtDate).value = serverdate;
                return false;
            } else {
                if (isNaN(parseInt(dateParts[2]))) {
                    alert("Date format Must be e.g.12-Mar-2012 and >=1900");
                    document.getElementById(txtDate).value = serverdate;
                    return false;
                }
            }
        }
        if (dateParts[2].length < 4 && parseInt(dateParts[2]) < 2000) {
            dateParts[2] = Number(2000 + parseInt(dateParts[2]));
        }
        var dobj = new Date(dateParts[2], dateParts[1] - 1, dateParts[0]);
        var day = dobj.getDate();
        var month = dobj.getMonth();
        var year = dobj.getFullYear();
        if (day < 10) {
            day = "0" + day;
        }
        dateText = day + "-" + MONTH_NAMES1[month] + "-" + year;
        //AshwiniP on 29-11-2018 - BNPP END

        //JIRA SCBP_433 Arshad M
        var res = dateText.split('-');
        if (res.length > 2 && parseInt(res[2]) < 1900) {
            if (dateText != "") {
                if (dateText != "NaN-undefined-NaN") {
                    alert("Date format Must be e.g.12-Mar-2012 and >=1900");
                    document.getElementById(txtDate).value = serverdate;
                    return false;
                }
            }
        }
        if (isDate(dateText, Format) == true) {
            document.getElementById(txtDate).value = dateText;

            return true;
        }
        else {
            if (dateText != "") {
                if (dateText != "NaN-undefined-NaN") {
                    alert("Date format Must be e.g.12-Mar-2012");
                    document.getElementById(txtDate).value = serverdate;
                    return false;
                }
            }
        }
    }
    //AKshayD for allow blank date 08-Aug-2019
    else {

        if (((dateText.indexOf("/") > -1) || (dateText.indexOf("-") > -1)) && dateText != '-') { //  dateText != '-' condition added by OnkarE on 21-Apr-2022 JIRA:BBVAORINT-167
            return true;
        }
        else {
            var AllowBlank = document.getElementById(txtDate.replace("txtDate", "hdnAllowBlank")).value;
            if (AllowBlank.toUpperCase() == "TRUE") {
                if (dateText != "") {
                    alert("Date format Must be e.g.12-Mar-2012");
                    document.getElementById(txtDate).value = serverdate;
                    return false;
                }
                else {
                    return true;
                }
            }
            else {
                alert("Date format Must be e.g.12-Mar-2012");
                document.getElementById(txtDate).value = serverdate;
                return false;
            }
        }
    }
}


// Added By Ganesh 27Jan11
function OnTextChange(tabcontrol, tabcontrol1) {
    try {
        var TextBox1 = document.getElementById(tabcontrol).value
        document.getElementById(tabcontrol1).value = document.getElementById(tabcontrol).value
    }
    catch (error) {

    }
    finally {

    }

}


function OnStrikePriceYieldChange(tabcontrol, tabcontrol1, tabradioBtn1, tabradioBtn2, tabradioBtn3) {
    try {
        var TextBox1 = document.getElementById(tabcontrol).value
        document.getElementById(tabcontrol1).value = document.getElementById(tabcontrol).value
        ////        document.getElementById(tabradioBtn1).checked=true
        ////        document.getElementById(tabradioBtn2).checked = false
        ////        document.getElementById(tabradioBtn3).checked = false
    }
    catch (error) {

    }
    finally {

    }
}
function isNumeric(sText, decimals, negatives) {
    try {
        var isNumber = true;

        var numDecimals = 0;

        var validChars = "0123456789";

        if (decimals) validChars += ".";

        if (negatives) validChars += "-";

        var thisChar;

        for (i = 0; i < sText.length && isNumber == true; i++) {

            thisChar = sText.charAt(i);

            if (negatives && thisChar == "-" && i > 0) isNumber = false;

            if (decimals && thisChar == ".") {

                numDecimals = numDecimals + 1;

                if (i == 0 || i == sText.length - 1) isNumber = false;

                if (numDecimals > 1) isNumber = false;

            }

            if (validChars.indexOf(thisChar) == -1) isNumber = false;

        }

        return isNumber;
    }
    catch (error) {

    }
    finally {

    }
}

function KeysAllowedForNotional() {
    var e = window.event;
    var key = window.event.keyCode;
    var obj;
    if (e.target) { obj = e.target; }
    else if (e.srcElement) { obj = e.srcElement; }
    if (key != 8) {
        //if ((Len(obj.value) > 0) && (!(isNumeric(Right(obj.value, 1)))))
        if ((Len(obj.value) > 0) && (Right(obj.value, 1) != "." && (!(isNumeric(Right(obj.value, 1)))))) {
            //<start Added by Arun Gautam BOSEQD-51 | Notional field allwoing other characters (other than K,M,N,B,T)
            //window.event.returnValue = false;
            window.event.preventDefault ? window.event.preventDefault() : window.event.returnValue = false; //handling for IE
        }
        else {
            var character = String.fromCharCode(key);
            var s = obj.value;
            if ((s.indexOf(".") != -1) && (character == ".")) window.event.returnValue = false;
            else
                if (key > 47 && key < 58) return;
                else {
                    // var character = String.fromCharCode(key);
                    if (character == "K" || character == "M" || character == "B" || character == "T" || character == "L" || character == "P" || character == "k" || character == "m" || character == "b" || character == "t" || character == "l" || character == "p" || character == ".")
                        return;
                    else
                        //<start Added by Arun Gautam BOSEQD-51 | Notional field allwoing other characters (other than K,M,N,B,T)
                        //window.event.returnValue = false;
                        window.event.preventDefault ? window.event.preventDefault() : window.event.returnValue = false; //handling for IE
                }
        }
    }
}

//this functon added by rajesh on 21-Nov-2011
//Purpose: stop page nevigation on readonly textbox when pressing backspace key
function checkReadOnlyTextboxBackspace(TextboxID) {
    if (event.keyCode == 8) {
        var isreadonly = document.getElementById(TextboxID).readOnly;
        // alert("is readonly = " + isreadonly);
        if (isreadonly === true) {
            event.cancelBubble = true;
            event.returnValue = false;
            return false;
        }
        else {
            return true;
        }
    }
    else {
        return true;
    }
}

//Start: Added by Kshitija on 16-Feb-2013 To handle postback on Backspace for a button
function checkButtonBackspace(btnID) {
    if (event.keyCode == 8) {
        event.cancelBubble = true;
        event.returnValue = false;
        return false;
    }
    else {
        return true;
    }
}
//End : Added by Kshitija on 16-Feb-2013

//Added by Sonal on 10-Sep-2012
function AllowValidTenorChar(cntl) {
    var cntrlval;
    cntrlval = document.getElementById(cntl).value;
    cntrlval = cntrlval.toUpperCase();
    var key = window.event.keyCode;
    if ((cntrlval === "") && ((key == 109) || (key == 121) || (key == 100) || (key == 119))) {
        window.event.returnValue = null;
        return false;
    }
    if (cntrlval.indexOf('M') > -1 || cntrlval.indexOf('Y') > -1 || cntrlval.indexOf('D') > -1 || cntrlval.indexOf('W') > -1) { window.event.returnValue = null; return false; }

    //if ((key > 47 && key < 58) || (key == 109) || (key == 121) || (key == 100) || (key == 119))
    if ((key > 47 && key < 58) || (key == 109 || key == 77) || (key == 121 || key == 89) || (key == 100 || key == 68) || (key == 119 || key == 87))
        return true;
    else { window.event.returnValue = null; return false; }
}

function DisAllowSpecialChar_RSP() {
    var key = window.event.keyCode;
    if (key > 32 && key < 48 || key > 57 && key < 65 || key > 90 && key < 97 || key > 122 && key < 127)
        if (key != 45) // modified by Anand K on 22-Apr-2014 2.59 PM
            //window.event.returnValue = null;
            if (key != 95) // modified by Anand K on 22-Apr-2014 2.59 PM
                window.event.returnValue = null;
            else
                return;
        else
            return;
    //else
    //window.event.returnValue = null;
    else
        return;
}

function DisAllowSpecialChar_UDF() {
    var key = window.event.keyCode;
    if (key == 32) // modified by Dinesh 13-May-2014
    {
        window.event.returnValue = null;
    }
    if (key > 31 && key < 48 || key > 57 && key < 65 || key > 90 && key < 97 || key > 122 && key < 127)
        //if (key == 45) // modified by Anand K on 22-Apr-2014 2.59 PM
        //window.event.returnValue = null;
        //key = window.event.keyCode;
        if (key != 95) // modified by Anand K on 22-Apr-2014 2.59 PM
            window.event.returnValue = null;
        else
            return;
    //  else
    //  window.event.returnValue = null;
    else
        return;
}

//Function Added by Dhanashri 01-Apr-2013 : allow only numbers and alphabets
function DisAllowSpecialChar() {
    var key = window.event.keyCode;
    if (key > 32 && key < 48 || key > 57 && key < 65 || key > 90 && key < 97 || key > 122 && key < 127)
        window.event.returnValue = null;
    else
        return;
}
//End

//Sonal:for OCBC:17-Dec-2013<avinashg. on 30-aug-2013: for fast find customer>
function findcust(e, id) {
    if (e.keyCode == 13 || e.keyCode == 8 || BtnImageSelect.click) {
        document.getElementById(id).click();
    }
}

//<Sandip G. on 10-Oct-2013: to allow ctrl + v in attach account
function AllowOnlyNumericAndPaste() {
    var key = window.event.keyCode;
    if (key > 47 && key < 58)
        return;
    else if (key == 86 || key == 118 && (window.event.ctrlKey))
        return;
    else
        window.event.returnValue = false;
}

//<Shekhar: confirmation box>------------------------------------------------------
var msg;
function Click_Ok() {
    $("#draggable").css('visibility', 'hidden');
    return true;
    __doPostBack('btnSolve_Click', 'Click');
}

function Click_Cancel() {
    $("#draggable").css('visibility', 'hidden');
    return false;
}

function confirm1(msg) {
    str = '<div id="draggable" class="MsgBox ui-widget-content" style="visibility:hidden;">';
    str = str + '<h1>Confirmation</h1>';
    str = str + '<div class="icon-confirmed"><img src="../App_Resources/confirmed.png" ></div>';
    str = str + '<div id="msgbody">Test Message.</div>';
    str = str + '<div class="clsButton"> ';
    str = str + '<input type="button" id="btnOk" value="Ok" width="80px" height="20px" onClick="javascript: return Click_Ok();" /> ';
    str = str + '<input type="button" id="btnCancel" value="Cancel" width="60px"  height="20px" onClick="javascript: return Click_Cancel();" /></div>';
    str = str + '</div>';
    $("body").append(str);
    $("#draggable").css('visibility', 'visible');
    $("#msgbody").html(msg);
    $("#draggable").draggable();
}

var ProductAutoCompletectrl, Loginctrl, Directionctrl, TransactionTypectrl, Product_Acronymctrl, productctrl, sub_productctrl, purpose_codectrl, btnProdselectctrl, tableControl;
function autocomplete_prodchanged(event, productAutoComplete, LoginGrp, Login, Direction, Transaction_type, check, Product_Acronym, product, sub_product, purpose_code, btnproductselect, table) {
    ProductAutoCompletectrl = productAutoComplete;
    Directionctrl = Direction;
    TransactionTypectrl = Transaction_type;
    Product_Acronymctrl = Product_Acronym;
    productctrl = product;
    sub_productctrl = sub_product;
    purpose_codectrl = purpose_code;
    btnProdselectctrl = btnproductselect;
    tableControl = table;
    var keyCode = event.which;
    var txt = $("#" + productAutoComplete.id).val().trim();
    var term = "";
    term = txt;
    if (term === "") {
        $(tableControl).html("");
        $(tableControl).hide("");
        //$("#tbl_prod").html("");
        //$("#tbl_prod").hide();
        autocomplete_prodclicked('', '', '', '', '', '');
        return;
    }
    var LoginID = "";
    var LoginGroup = "";
    var Side = "";
    var TranType = "";
    var CheckValue = "";
    Side = $("#" + Direction.id).val().trim();
    TranType = $("#" + Transaction_type.id).val().trim();
    CheckValue = $("#" + check.id).val().trim();
    LoginID = $("#" + Login.id).val().trim();
    LoginGroup = $("#" + LoginGrp.id).val().trim();
    if (CheckValue === '') {
        CheckValue = "NO";
    }
    $.support.cors = true;
    $.ajax({
        type: "GET",
        url: "http://" + location.hostname + "/finiqservice/SearchEngineService.svc/GetProductSearch?LoginID=" + LoginID + "&LoginGroup=" + LoginGroup + "&QueryString=" + term + "&Dir=" + Side + "&TransType=" + TranType + "&check=" + CheckValue + "",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        //async: true,
        cache: false,
        success: function (data) {
            var tbl = "<table class='TableSearchResult'>";
            tbl += "<tr>";
            tbl += "<th>Product Acronym</th>";
            tbl += "<th>Product</th>";
            tbl += "<th>Sub Product</th></tr>";
            var objData;
            $.each(data, function (key, value) {
                var jsonData = JSON.stringify(value);
                objData = $.parseJSON(jsonData);
            });
            for (var i = 0; i < objData.length; i++) {
                tbl += "<tr class='SearchResultRow' onClick=\"autocomplete_prodclicked('" + objData[i].Product_Acrynm + "','" + objData[i].Product + "','" + objData[i].Sub_Product + "','" + objData[i].Purpose_Code + "','" + objData[i].Rate_Type + "','" + objData[i].Side + "')\">";
                tbl += "<td>" + objData[i].Product_Acrynm + "</td>";
                tbl += "<td>" + objData[i].Product + "</td>";
                tbl += "<td>" + objData[i].Sub_Product + "</td>";
                tbl += "</tr>";
            }
            tbl += "</table>";
            $(tableControl).html(tbl);
            $(tableControl).show();
        }
    });
}

function autocomplete_prodclicked(Product_Acrynm, Product, Sub_Product, Purpose_Code, Rate_Type, Side, Priority) {
    $("#" + ProductAutoCompletectrl.id).val(Product_Acrynm);
    $('#' + Product_Acronymctrl.id).val(Product_Acrynm);
    $('#' + productctrl.id).val(Product);
    $('#' + sub_productctrl.id).val(Sub_Product);
    $('#' + purpose_codectrl.id).val(Purpose_Code);
    $('#' + TransactionTypectrl.id).val(Rate_Type);
    $('#' + Directionctrl.id).val(Side);
    // $("#tbl_prod").hide();
    $(tableControl).hide();
    //document.getElementById('<%=btnProdSelect.ClientID()%>').click();
    $('#' + btnProdselectctrl.id).click();
}

function autocomplete_prodchanged(event, Login, EntityID, Applyissuedatefilter, strShowProductsMarkedForRestructure) {
    var keyCode = event.which;
    var txt = $("#ctl00_MainContent_Finiq_Product_SmartSearch_Tranche_autompleteprod1").val().trim();
    var term = "";
    if (keyCode >= 32)
        term = txt + String.fromCharCode(event.which);
    else
        if (keyCode == 8)
            alert(keyCode);
    term = txt.substring(0, txt.length - 1);

    if (term === "") {
        $("#tbl_prod").html("");
        $("#tbl_prod").hide();
        return;
    }
    var LoginID = "";
    //var preM;
    //preM = 'ctl00_MainContent_';
    //LoginID = document.getElementById(preM + 'hdnLoginID').value;
    var LoginID = Login;
    var entityID = EntityID;
    if (Applyissuedatefilter.trim().toUpperCase() == "Y") {
        //Do nothing.
    }
    else {
        Applyissuedatefilter = "N";
    }
    if (strShowProductsMarkedForRestructure.trim().toUpperCase() == "Y") {
        //Do nothing.
    }
    else {
        strShowProductsMarkedForRestructure = "N";
    }
    //Aditya B. on 20-Jul-2016 <Start> for CIMB
    var SearchEngineUrl = "";
    SearchEngineUrl = "http://" + location.hostname + "/finiqservice/SearchEngine.svc/Get_Product_Details?strEntityID=" + entityID + "&strLogin=" + LoginID + "&strProductName=" + term + "&strPagingValue=0&strCurrentPage=0&QueryString=&strCustomerID=&strDealerID=&strApplyIssueDateFilter=" + Applyissuedatefilter + "&strShowProductsMarkedForRestructure=" + strShowProductsMarkedForRestructure + "";
    $.support.cors = true;
    $.ajax({
        type: "GET",
        url: SearchEngineUrl,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
            var tbl = "<table border=1 cellpadding=1 cellspacing=1 style='border-collapse:collapse;background-color:#FFFFFF'><tr><th>Product Name</th><th>Product Id</th></tr>";
            var objData;
            $.each(data, function (key, value) {
                var jsonData = JSON.stringify(value);
                objData = $.parseJSON(jsonData);
            });
            for (var i = 0; i < objData.length; i++) {
                tbl += "<tr onClick=\"autocomplete_prodclicked('" + objData[i].Product_Name + "','" + objData[i].Note_Master_ID + "')\">";
                tbl += "<td>" + objData[i].Product_Name + "</td>";
                tbl += "<td>" + objData[i].Note_Master_ID + "</td>";
                tbl += "</tr>";
            }
            tbl += "</table></div>";
            $("#tbl_prod").html(tbl);
            $("#tbl_prod").show();
        }
    });
}

function autocomplete_prodclicked(Product_Name, Note_Master_ID) {
    $('#ProductName').val(Product_Name);
    $('#NoteMasterID').val(Note_Master_ID);
    $('#ctl00_MainContent_Finiq_Product_SmartSearch_Tranche_autompleteprod1').val(Product_Name);
    $("#tbl_prod").hide();
    __doPostBack('prod_name_ValueChanged', 'ValueChanged');
}

//</Shekhar: confirmation box>------------------------------------------------------
//var CustAutoCompletectrl, CustSearchctrl, Cust_namectr, Cust_bcfx_idctrl, Cust_tlt_idctrl, Cust_rm_idctrl, Cust_allocation_codectrl, Cust_typectrl, Cust_Doc_IDctrl, BtnCustselectctrl;
//var CustAutoCompletectrl, CustSearchctrl, Cust_namectr, Cust_bcfx_idctrl, BtnCustselectctrl;
var CustAutoCompletectrl, Cust_namectr, Cust_bcfx_idctrl, tableControl, Cust_tlt_idctrl, Cust_rm_idctrl, Cust_allocation_codectrl, Cust_typectrl, Cust_Doc_IDctrl, Cust_Settlement_Acc_ctrl, BtnCustselectctrl, BtnImageSelect, urlToRest;

function autocomplete_custchanged(event, custAutoCompletectrl, table, cust_namectr, cust_bcfx_idctrl, cust_rm_idctrl, cust_typectrl, cust_Doc_IDctrl, Cust_Settlement_Acc_ctrl, btnCustselectctrl, btnImageSelect) {
    var id = event.currentTarget.id;
    var checkBtnClickEvent = "btnImage";

    if (id == checkBtnClickEvent) {

    }
    else {
        if (event.keyCode != 13) {
            //autocomplete_Customer('', '0', '', '', '', '', '', '');
            return false;
        }
    }

    CustAutoCompletectrl = custAutoCompletectrl;
    tableControl = table;
    //CustSearchctrl = custSearchctrl;
    Cust_namectr = cust_namectr;
    Cust_bcfx_idctrl = cust_bcfx_idctrl;
    //Cust_tlt_idctrl = cust_tlt_idctrl;
    Cust_rm_idctrl = cust_rm_idctrl;
    Cust_typectrl = cust_typectrl;
    Cust_Doc_IDctrl = cust_Doc_IDctrl;
    Cust_Settlement_Acc_ctrl = Cust_Settlement_Acc_ctrl;
    BtnCustselectctrl = btnCustselectctrl;
    BtnImageSelect = btnImageSelect;
    try {
        if (CustAutoCompletectrl.value === "") {
            urlToRest = "";
        }
        else {
            urlToRest = "CUSTNAMEORCUSTID";
        }
        //alert(urlToRest);
        var keyCode = event.which;
        var txt = $("#" + CustAutoCompletectrl.id).val().trim();
        var term = "";
        var CheckValue = "";
        var ParentID = "";
        var LoginIDCustomer = "";
        var EntityIDCustomer = "";
        term = txt;
        if (event.keyCode == 13 || id == checkBtnClickEvent) {
            ShowPopup2();
            var keyCode = event.which;
            var txt = $("#" + CustAutoCompletectrl.id).val().trim();
            var term = "";
            term = txt;
            var path_Name = window.location.pathname;
            var myPageName = path_Name.substring(path_Name.lastIndexOf('/') + 1);
            var strConfigEQC_PTCC, strMethod;
            //strConfigEQC_PTCC = parent.document.getElementById("ctl00_MainContent_hdnConfigEQC_PTCC").value;
            strConfigEQC_PTCC = "NO";
            if (strConfigEQC_PTCC.toUpperCase() == 'YES' | strConfigEQC_PTCC.toUpperCase() == 'Y') {
                strMethod = 'FindCustomerCDE';
            }
            else {
                strMethod = 'FindCustomer';
            }

            $.support.cors = true;
            if (term.length >= 3) {
                $.ajax({
                    type: "POST",
                    url: "" + myPageName + "/" + strMethod,
                    //url: "" + myPageName + "/FindCustomer",
                    contentType: "application/json; charset=utf-8",
                    dataType: "text",
                    cache: false,

                    data: "{'term':'" + term + "', 'Mode':'" + urlToRest + "'}",
                    //data:"{}",
                    crossDomain: true, //Modified Code
                    success: function (data) {
                        $(tableControl.id).css("right", "100px");
                        $(tableControl).html("");
                        $(tableControl.id).html("");
                        $(tableControl.id).css("right", "100px");
                        //var obj = jQuery.parseJSON(data.d);
                        var obj = jQuery.parseJSON(data);
                        var tbl = "<div style='overflow-y:auto;height:350px;width:auto;background-color:#FFFFFF;'   class='Filter UCCustomerFind UCCustomerPos UCOverflow setPadding'>";
                        // tbl += "<div style='overflow-y:auto;height:auto;max-height:390px; background-color:#FFFFFF;'  class='Grid'>"
                        tbl += " <table id='1' cellpadding='0' cellspacing='0' border='0' style='width: 270px;'>";
                        tbl += "<tr>";
                        tbl += "<td colspan='2' class='lblHeader background_gray'  style='background-color: #5D7B9D;' align='left'>";
                        tbl += "<label  ID='lbltbl_cust" + tableControl.id + "' style='display: inline;' align='left'></label>";
                        tbl += "</td>";
                        tbl += "<td class='background_gray' style='background-color: #5D7B9D;' align='right'>";
                        tbl += "<img  ID='imgtbl_cust_close' style='display:inline;' onclick='closetbl_cust_table(" + tableControl.id + ")'  src='../App_Themes/images/close.png'/>";
                        tbl += "</td>";
                        tbl += "</tr>";
                        tbl += "</table>";
                        tbl += "<br/>";
                        tbl += "<table id='idTableSearchResult' class='Grid TableSearchResult' cellpadding='0' cellspacing='0' border='0' style='width: 270px;border-collapse:collapse;' >";
                        tbl += "<tr><th>Customer Name</th>";
                        tbl += "<th>ID</th>";
                        tbl += "<th>Customer CIF</th>";
                        tbl += "</tr>";
                        var objData;
                        $.each(obj, function (key, value) {
                            tojson: var jsonData = JSON.stringify(value);
                            objData = $.parseJSON(jsonData);
                        });
                        if (objData.length === 0) {
                            // var tbl1 = "<div style='overflow-y:auto;height:auto;max-height:300px;background-color:#FFFFFF;'  class='Grid'>"
                            // tbl1 += "<label  ID='lbltbl_cust1' style='float:left;display: inline;'   class='lblerror'></label>"
                            // tbl1 += "<img  ID='imgtbl_cust_close1' style='float:right;display:inline;Height:24px; Width:22px' onclick='closetbl_cust_table()'  src='../App_Themes/images/close.png'/>"
                            // tbl1 += "<br/>"
                            // tbl1 += "</div>";
                            // $(tableControl).html(tbl1);
                            // $(tableControl).show();
                            //// $("#tbl_cust").html("");                                                                                      
                            // document.getElementById("lbltbl_cust1").innerHTML = 'No Such customer(s) found.';
                            //// autocomplete_Customer('', '0', '', '', '', '')
                            // $("#" + CustAutoCompletectrl.id).blur();
                            //alert("No details found for selected customer");
                            //$("#" + x).attr('title', 'Customer Name :  BCFX Customer ID :  RM ID :  ');                                     
                            // return;
                        }

                        for (var i = 0; i < objData.length; i++) {
                            if (strConfigEQC_PTCC.toUpperCase() == 'YES' | strConfigEQC_PTCC.toUpperCase() == 'Y') {
                                //  tbl += "<tr class='SearchResultRow' onclick=\"autocomplete_Customer('" + objData[i].CustomerName + "','" + objData[i].ID + "','" + objData[i].CIFNo + "','" + objData[i].Type + "','" + objData[i].AccountNo + "','" + objData[i].DocId + "')\">"
                                tbl += "<tr class='SearchResultRow' onclick=\"autocomplete_Customer('" + objData[i].CustomerName + "','" + objData[i].ID + "','" + objData[i].CIFNo + "','" + objData[i].Type + "','" + objData[i].AccountNo + "','" + objData[i].DocId + "','" + objData[i].DealerName + "')\">";  //ArshadM
                                tbl += "<td>" + objData[i].CustomerName + "</td>";
                            }
                            else {
                                tbl += "<tr class='SearchResultRow' onclick=\"autocomplete_Customer('" + objData[i].Name + "','" + objData[i].ID + "','" + objData[i].CIFNo + "','" + objData[i].Type + "','" + objData[i].AccountNo + "','" + objData[i].DocId + "')\">";
                                //tbl += "<td>hhhhhh</td>";
                                tbl += "<td>" + objData[i].Name + "</td>";
                            }
                            tbl += "<td>" + objData[i].ID + "</td>";   // --<Javed>--Added <DOC ID> column told by Milind N.--<on 23-Dec-2016>
                            tbl += "<td>" + objData[i].CIFNo + "</td>";
                            tbl += "</tr>";
                        }
                        tbl += "</table> </div>";
                        $(tableControl).html(tbl);
                        $(tableControl).show();
                        document.getElementById("lbltbl_cust" + tableControl.id).innerHTML = 'Total record(s): ' + objData.length;
                        if (objData.length === 0) {
                            $('#idTableSearchResult').hide();
                            document.getElementById("lbltbl_cust" + tableControl.id).innerHTML = 'No such customer(s) found.';
                        }
                        else {
                            $('#idTableSearchResult').show();
                        }
                        $('#para1').addClass('demo');
                        $(tableControl.id).css("right", "100px");
                        $(tableControl.id).addClass("demo");
                        $("#dialog2").hide();
                    },
                    error: function (xhr, textStatus, error) {
                    }
                });
            }

        }
    } catch (error) {
    }
}

function closetbl_cust_table(tableControl) {
    try {
        $(tableControl).hide();
        autocomplete_Customer('', '0', '', '', '', '', '');
        return;
    } catch (e) {
    }
}

function ShowPopup2(message) {
    $(function () {
        $("#dialog2").show();
    });
}


function ClearCustomerControl(event) {
    var txt = $("#" + CustAutoCompletectrl.id).val().trim();
    if (term === "") {
        autocomplete_clicked('', '0', '', '', '', '', '', '');
        // alert($('#sel_cust_bcfx_id').value);
        return;
    }
}

//  function autocomplete_clicked(CustomerName, CustomerID, CDM_TLT_ID, AH_CIF_No, AH_ALLOCATION_CODE, AH_Type_1, AccountNo, AH_Doc_ID) {
function autocomplete_Customer(CustomerName, CustomerID, AH_CIF_No, AH_Type_1, AccountNo, AH_Doc_ID, DealerName) {
    try {
        $("#" + Cust_namectr.id).val(CustomerName);
        $("#" + CustAutoCompletectrl.id).val(CustomerName);
        //cust_name_ValueChanged alert(CustomerName);
        $("#" + Cust_bcfx_idctrl.id).val(CustomerID);//DK
        // $('#sel_cust_tlt_id').val(CDM_TLT_ID);
        $("#" + Cust_rm_idctrl.id).val(DealerName);
        //  $('#sel_cust_allocation_code').val(AH_ALLOCATION_CODE);
        $("#" + Cust_typectrl.id).val(AH_Type_1);
        $("#" + Cust_Doc_IDctrl.id).val(AH_Doc_ID);
        $(tableControl).hide();
        // __doPostBack('cust_name_ValueChanged', 'ValueChanged');
        $('#' + BtnCustselectctrl.id).click();

    } catch (error) {
        //alert(error);
    }
}

function SearchByChanged(Cust, Dropdown) {
    $('#' + Cust.id).val("");
    //var textbox1 = document.getElementById(Cust);
    //textboxt1.text = "";
    var dropdown1 = $('#' + Dropdown.id);
    //alert(dropdown1);
    var selected = dropdown1.prop('selectedIndex');
    if (selected === 0) {
        urlToRest = "CustomerName";
    }
    else if (selected == 1) {
        urlToRest = "CustomerID";
    }
    else if (selected == 2) {
        urlToRest = "CIFNUMBER";
    }
    else if (selected == 3) {
        urlToRest = "ACCOUNTNUMBER";
    }
    $("#" + CustAutoCompletectrl).val("");
    $(tableControl).hide();
}

//<Added by Neha M :DB:for LSS Reports:28-12_17>
function AllowUnderScoreWithAlphanumeric(tbControl) {
    var ControlText = document.getElementById(tbControl).value;
    var C, d;
    CheckStartSpace(tbControl);
    if (ControlText.length > 0) {
        for (i = 0; i < ControlText.length; i++) {
            d = ControlText.charAt(i);
            if (((d >= 'a') && (d <= 'z')) || ((d >= 'A') && (d <= 'Z')) || ((d <= '') && (d >= ' ')) || ((d >= '0') && (d <= '9')) || (d == '_') || (d == ' ')) {
            }
            else {
                C = ControlText.substring(0, i);
                document.getElementById(tbControl).value = C;
                document.getElementById(tbControl).focus();
                return false;
            }
        }
    }
}

function CheckStartSpace(tbControl) {
    var ControlText = document.getElementById(tbControl).value;
    var C = ControlText.substring(0, ControlText.length);
    if (ControlText.charAt(0) == ' ') {
        var pos = 0;
        for (var i = 0; i < ControlText.length; i++) {
            if (ControlText.charAt(i) == ' ')
                pos = pos + 1;
            if (ControlText.charAt(i) !== '')
                break;
        }
        document.getElementById(tbControl).value = ControlText.substring(pos, ControlText.length);
    }
}

//added by monika /suhas 5-4-17 for EQC customer  search

var CustAutoCompletectrl_EQC, Cust_namectr_EQC, Cust_countryctr, Cust_bcfx_idctrl_EQC, tableControl_EQC, Cust_tlt_idctrl_EQC, Cust_rm_idctrl_EQC, Cust_allocation_codectrl_EQC, Cust_typectrl_EQC, Cust_Doc_IDctrl_EQC, Cust_Settlement_Acc_ctrl_EQC, BtnCustselectctrl_EQC, BtnImageSelect_EQC, urlToRest_EQC;

function autocomplete_custchanged_EQC(event, custAutoCompletectrl, table, cust_namectr, cust_bcfx_idctrl, cust_rm_idctrl, cust_typectrl, cust_Doc_IDctrl, Cust_Settlement_Acc_ctrl, btnCustselectctrl, btnImageSelect, Cust_country) {
    try {

        $("#dialog2").show();

        var id = event.currentTarget.id;
        var checkBtnClickEvent = "btnImage";

        if (id == checkBtnClickEvent) {

        }
        else {
            if (event.keyCode != 13) {
                $("#dialog2").hide();
                return false;
            }
        }

        CustAutoCompletectrl = $("#" + custAutoCompletectrl)[0];
        tableControl = $("#" + table)[0];
        //CustSearchctrl = custSearchctrl;
        Cust_namectr = $("#" + cust_namectr)[0];
        Cust_countryctr = $("#" + Cust_country)[0];
        Cust_bcfx_idctrl = $("#" + cust_bcfx_idctrl)[0];
        //Cust_tlt_idctrl = cust_tlt_idctrl;
        Cust_rm_idctrl = $("#" + cust_rm_idctrl)[0];
        Cust_typectrl = $("#" + cust_typectrl)[0];
        Cust_Doc_IDctrl = $("#" + cust_Doc_IDctrl)[0];
        Cust_Settlement_Acc_ctrl = $("#" + Cust_Settlement_Acc_ctrl)[0];
        BtnCustselectctrl = $("#" + btnCustselectctrl)[0];
        BtnImageSelect = $("#" + btnImageSelect)[0];


        if (CustAutoCompletectrl.value == "") {
            urlToRest = ""
        }
        else {
            urlToRest = "CUSTNAMEORCUSTID"
        }
        var keyCode = event.which;
        var txt = $("#" + CustAutoCompletectrl.id).val();
        if (txt != undefined) {
            txt = txt.trim();
        }
        var term = "";
        var CheckValue = "";
        var ParentID = "";
        var LoginIDCustomer = "";
        var EntityIDCustomer = "";
        //DK
        var strRMID;
        strRMID = $("#" + cust_rm_idctrl.id).val();
        if (strRMID != undefined) {
            strRMID = strRMID.trim();
        }
        //DK
        term = txt;

        if (event.keyCode == 13 || id == checkBtnClickEvent) {
            var keyCode = event.which;
            var txt = $("#" + CustAutoCompletectrl.id).val();
            if (txt != undefined) {
                txt = txt.trim();
            }
            var term = "";
            var minLengthToSearchCust = 3;//parent.document.getElementById("ctl00_hdncustSearchLength").value;
            if (isNaN(minLengthToSearchCust)) { minLengthToSearchCust = 0; }
            term = txt;

            var path_Name = window.location.pathname;
            var myPageName = path_Name.substring(path_Name.lastIndexOf('/') + 1);

            var strConfigEQC_PTCC, strMethod;
            //strConfigEQC_PTCC = parent.document.getElementById("ctl00_MainContent_hdnConfigEQC_PTCC").value;
            strConfigEQC_PTCC = "NO"
            if (strConfigEQC_PTCC.toUpperCase() == 'YES' | strConfigEQC_PTCC.toUpperCase() == 'Y') {
                strMethod = 'FindCustomerCDE';
            }
            else {
                strMethod = 'FindCustomer'
            }

            $.support.cors = true;
            if (term.length >= minLengthToSearchCust) {
                $("#ctl00_MainContent_lblerrorPopUp").text('');
                $.ajax({
                    type: "POST",
                    url: "" + myPageName + "/" + strMethod,
                    contentType: "application/json; charset=utf-8",
                    dataType: "text",
                    cache: false,
                    data: "{'term':'" + term + "', 'Mode':'" + urlToRest + "' , 'strRMID':'" + $("#" + table)[0].parentElement.parentElement.rowIndex + "'}",
                    crossDomain: true, //Modified Code

                    success: function (data) {
                        $(tableControl.id).css("right", "100px");
                        $(tableControl).html("");
                        $(tableControl.id).html("");
                        $(tableControl.id).css("right", "100px");
                        //
                        //var obj = jQuery.parseJSON(data.d);
                        var obj = jQuery.parseJSON(data);
                        //<Shekhar Sir/Sudarshan Sep 12 2017 : Added one extra div for disable background when customer popup open > 
                        var tbl = "<div class='overlay'></div><div style='overflow-y:auto;height:350px;width:auto;background-color:#FFFFFF;z-index:9999;'   class='Filter UCCustomerFind UCCustomerPos UCOverflow setPadding'>"
                        // tbl += "<div style='overflow-y:auto;height:auto;max-height:390px; background-color:#FFFFFF;'  class='Grid'>"
                        tbl += " <table id='1' cellpadding='0' cellspacing='0' border='0' style='width: 270px;'>"
                        tbl += "<tr>"
                        tbl += "<td colspan='2' class='lblHeader background_gray' align='left'>"
                        tbl += "<label  ID='lbltbl_cust" + tableControl.id + "' style='display: inline;' align='left'></label>"
                        tbl += "</td>"
                        tbl += "<td class='background_gray' align='right'>"
                        tbl += "<img  ID='imgtbl_cust_close' style='display:inline;' onclick='closetbl_cust_table_EQC(" + tableControl.id + ")'  src='../App_Themes/images/close.png'/>"
                        tbl += "</td>"
                        tbl += "</tr>"
                        tbl += "</table>"
                        tbl += "<br/>"
                        tbl += "<table id='idTableSearchResult' class='Grid TableSearchResult' cellpadding='0' cellspacing='0' border='0' style='width: 270px;border-collapse:collapse;' >"
                        tbl += "<tr><th>Customer Name</th>"
                        //tbl += "<th>PAN No</th>"
                        //tbl += "<th>DOC ID</th>"  // --<Javed>--Added <DOC ID> column told by Milind N.--<on 23-Dec-2016>
                        //tbl += "<th>RM ID</th>"
                        // tbl += "<th>Allocation Code</th>"
                        //tbl += "<th>Settlement Account</th>
                        tbl += "<th>ID</th>"
                        tbl += "<th>Customer CIF</th>"

                        tbl += "</tr>";

                        var objData;
                        $.each(obj, function (key, value) {

                            //var mydata = obj;

                            tojson: var jsonData = JSON.stringify(value);
                            objData = $.parseJSON(jsonData);
                        })
                        //alert(objData);

                        for (var i = 0; i < objData.length; i++) {

                            //tbl += "<tr>";
                            // alert(objData[i].CustomerName);

                            if (strConfigEQC_PTCC.toUpperCase() == 'YES' | strConfigEQC_PTCC.toUpperCase() == 'Y') {
                                tbl += "<tr class='SearchResultRow' onclick=\"autocomplete_Customer_EQC('" + objData[i].CustomerName + "','" + objData[i].ID + "','" + objData[i].CIFNo + "','" + objData[i].Type + "','" + objData[i].AccountNo + "','" + objData[i].DocId + "','" + objData[i].DealerName + "','')\">"
                                tbl += "<td>" + objData[i].CustomerName + "</td>";
                            }
                            else {
                                tbl += "<tr class='SearchResultRow' onclick=\"autocomplete_Customer_EQC('" + objData[i].Name + "','" + objData[i].ID + "','" + objData[i].CIFNo + "','" + objData[i].Type + "','" + objData[i].AccountNo + "','" + objData[i].DocId + "',''," + "'" + objData[i].Country + "')\">"
                                //tbl += "<td>hhhhhh</td>";
                                tbl += "<td>" + objData[i].Name + "</td>";
                            }

                            tbl += "<td>" + objData[i].ID + "</td>";   // --<Javed>--Added <DOC ID> column told by Milind N.--<on 23-Dec-2016>
                            tbl += "<td>" + objData[i].CIFNo + "</td>";

                            //tbl += "<td>" + objData[i].AH_CIF_No + "</td>";
                            // tbl += "<td>" + objData[i].AH_ALLOCATION_CODE + "</td>";
                            //tbl += "<td>" + objData[i].AccountNo + "</td>";
                            tbl += "</tr>";
                        }
                        tbl += "</table> </div>";

                        if (objData.length === 0) {

                        }
                        else {
                            $(tableControl).html(tbl);
                            $(tableControl).show();
                            //<Shekhar Sir/Sudarshan Sep 12 2017: show div>
                            $(tableControl).find('.overlay').show();
                        }
                        //$('#ctl00_MainContent_grdRMData').find('#btnImage').css('display', 'none');
                        /* $('#ctl00_MainContent_grdRMData').find('#btnImage').attr('disabled', 'disabled');
                         $('#ctl00_MainContent_grdRMData').find('#btnImage').attr('disabled', true);*/
                        //$('#ctl00_MainContent_grdRMData').each(function () {

                        //    $(this).find('#btnImage').attr('disabled', 'disabled');

                        //});
                        //$('#ctl00_MainContent_grdRMData').find('#btnImage').prop('disabled', true);   

                        //$('#ctl00_MainContent_grdRMData :input').attr('disabled', true);
                        //
                        //if (document.getElementById("lbltbl_cust" + tableControl.id) != null) {                        
                        if (objData.length === 0) {
                            $('#idTableSearchResult').hide();
                            parent.document.getElementById("ctl00_MainContent_hdnCustomerSearch").value = term;
                            //document.getElementById("lbltbl_cust" + tableControl.id).innerHTML = 'No such customer(s) found.';
                            closetbl_cust_table_EQC(tableControl.id);
                        }
                        else {

                            if (document.getElementById("lbltbl_cust" + tableControl.id) !== null) {
                                document.getElementById("lbltbl_cust" + tableControl.id).innerHTML = 'Total record(s): ' + objData.length;
                            }
                            $('#idTableSearchResult').show();
                            parent.document.getElementById("ctl00_MainContent_hdnCustomerSearch").value = "";
                        }
                        //}

                        $('#para1').addClass('demo');
                        $(tableControl.id).css("right", "100px");
                        $(tableControl.id).addClass("demo");
                        $("#dialog2").hide();
                    },

                    error: function (xhr, textStatus, error) {

                        //called on ajax call error
                        // alert();
                        //  alert("Error: " + error);
                    }
                });
            }
            else { $("#ctl00_MainContent_lblerrorPopUp").text('Please enter minimum ' + minLengthToSearchCust + ' digits to search customer.'); }
            $("#dialog2").hide();
        }
    } catch (error) {

        console.log(error.message);
        //alert(error);
    }
}

function closetbl_cust_table_EQC(tableControl) {
    try {
        $(tableControl).hide();
        var strConfigEQC_PTCC, strMethod;
        strConfigEQC_PTCC = parent.document.getElementById("ctl00_MainContent_hdnConfigEQC_PTCC").value;

        if (strConfigEQC_PTCC.toUpperCase() == 'YES' | strConfigEQC_PTCC.toUpperCase() == 'Y') {
            if (BtnCustselectctrl.length > 0) {
                $('#' + BtnCustselectctrl[0].id).click();
            }
            else {
                $('#' + BtnCustselectctrl.id).click();
            }
            return;
        }
        else {
            autocomplete_Customer_EQC('', '0', '', '', '', '', '', '');
            return;
        }
    } catch (e) {
    }
}

function ShowPopup2_EQC(message) {
    $(function () {
        $("#dialog2").show();
    });
};

function ClearCustomerControl_EQC(event) {
    try {
        var txt = $("#" + CustAutoCompletectrl.id).val().trim();
        if (term === "") {
            //  alert('clear');
            autocomplete_Customer_EQC('', '0', '', '', '', '', '', '');
            // alert($('#sel_cust_bcfx_id').value);
            return;
        }
    } catch (error) {
        //alert(error);
    }
}

//  function autocomplete_clicked(CustomerName, CustomerID, CDM_TLT_ID, AH_CIF_No, AH_ALLOCATION_CODE, AH_Type_1, AccountNo, AH_Doc_ID) {
function autocomplete_Customer_EQC(CustomerName, CustomerID, AH_CIF_No, AH_Type_1, AccountNo, AH_Doc_ID, DealerName, CustomerCountry) {
    try {
        $("#" + Cust_namectr.id).val(CustomerName);
        $("#" + Cust_countryctr.id).val(CustomerCountry)
        $("#" + CustAutoCompletectrl.id).val(CustomerName);
        //cust_name_ValueChanged alert(CustomerName);
        $("#" + Cust_bcfx_idctrl.id).val(CustomerID); //DK
        // $('#sel_cust_tlt_id').val(CDM_TLT_ID);
        $("#" + Cust_rm_idctrl.id).val(DealerName);
        //  $('#sel_cust_allocation_code').val(AH_ALLOCATION_CODE);
        $("#" + Cust_typectrl.id).val(AH_Type_1);
        $("#" + Cust_Doc_IDctrl.id).val(AH_Doc_ID);
        $(tableControl).hide();
        // __doPostBack('cust_name_ValueChanged', 'ValueChanged');
        //Added If Condition Dilkhush/Sudarshan 26Dec2017: array is getting generated of BtnCustselectctrl  Due to this id is getting undefined
        //if (BtnCustselectctrl != undefined) {
        //    BtnCustselectctrl.length = 1;
        if (BtnCustselectctrl.length > 0) {
            $('#' + BtnCustselectctrl[0].id).click();
        }
        else {
            $('#' + BtnCustselectctrl.id).click();
        }
        //}

    } catch (error) {
    }
}

var Mode;
var RMID;


//Updated by Neeral+Shekhar on 22Jan200
function arrowKey(event, txtSearch) {
 //Code changes updated by Onkar E.+ Shekhar on 30-Apr-2022 JIRA:UWI-341 : Bug Fix for Arrow Key Up and Down issues in Share and Customer autocomplete serach
    var keyCode;
    var event = event || window.event;
    //if (event.keyCode == 13 || event.keyCode == 38 || event.keyCode == 40 || event.keyCode == 27 || event.keyCode == 9 || event.keyCode == 16 && event.keyCode == 9) {
    //    return;
    //} 
    //else {
    //    CustomerSearch(txtSearch, event)
    //}
     
    if (event.keyCode == 13 || event.keyCode == 38 || event.keyCode == 40 || event.keyCode == 27 || event.keyCode == 9 || event.keyCode == 16 && event.keyCode == 9) {
        var tbody = $(".TableCustomerSearchResult_new").find("tbody");
        selected = tbody.find(".selected"); 
        if (event.keyCode == 38) {
            $(".TableCustomerSearchResult_new").find(".selected").removeClass("selected");
            if (selected.prev().length == 0) {
                tbody.find("tr:last").addClass("selected");
            } else {
                selected.prev().addClass("selected"); 
            }
        }
        else if (event.keyCode == 40) {
            tbody.find(".selected").removeClass("selected");
            if (selected.next().length == 0) {
                tbody.find("tr:nth-child(2)").addClass("selected");
            } else {
                $(".TableCustomerSearchResult_new").find(".selected").removeClass("selected");
                selected.next().addClass("selected"); 
            }
        }
        else if (event.keyCode == 13 && $(".TableCustomerSearchResult_new").find(".selected").length !== 0) { 
            $(".TableCustomerSearchResult_new").find(".selected").click();
            $(".sharePopup").hide();
        }
        else if (event.keyCode == 27) {
            $(".sharePopup").hide();
        }
        else if (event.keyCode == 16 && event.keyCode == 9) {
            $(".sharePopup").hide();
        }
        else if (event.keyCode == 9) {
            $(".sharePopup").hide();
        } 
        //Updated by ShekharL @20-May-2022 JIRA: BBVAORINT-407- Solar Product Entry - Scroll bar not working when keyboard down arrow key is used for selection.
        var keyCode = window.event ? event.keyCode : event.which;
        $(".sharePopup").scrollTop(0);//set to top
        $(".sharePopup").scrollTop($('.selected:first').offset().top - $(".sharePopup").height());//then set equal to the position of the selected element minus the height of scrolling div
        return;
    }
    else {
        CustomerSearch(txtSearch, event);
    }
}

function arrowKeyShareCollection(txtSearch, event) {
    // //
    var keyCode;
    event = event || window.event;
    if (event.keyCode == 13 || event.keyCode == 38 || event.keyCode == 40 || event.keyCode == 27 || event.keyCode == 9 || event.keyCode == 16 && event.keyCode == 9) {
        return;
    }
    else {
        ShareCollectionSearch(txtSearch, event)
    }
}



//Updated by Neeral+Shekhar on 22Jan200
function arrowKeyShareSearch(event, txtSearch) {
     //Code changes updated by Onkar E.+ Shekhar on 30-Apr-2022 JIRA:UWI-341 : Bug Fix for Arrow Key Up and Down issues in Share and Customer autocomplete serach
    var keyCode; 
    var event = event || window.event;
    //if (event.keyCode == 13 || event.keyCode == 38 || event.keyCode == 40 || event.keyCode == 27 || event.keyCode == 9 || event.keyCode == 16 && event.keyCode == 9) {
    if (event.keyCode == 13 || event.keyCode == 38 || event.keyCode == 40 || event.keyCode == 27 || event.keyCode == 9 || event.keyCode == 16 && event.keyCode == 9) {
        var tbody = $(".TableShareSearchResult").find("tbody");
        selected = tbody.find(".selected");
        if (event.keyCode == 38) {
            $(".TableShareSearchResult").find(".selected").removeClass("selected");
            if (selected.prev().length == 0) {
                tbody.find("tr:last").addClass("selected");
            } else {
                selected.prev().addClass("selected");
            }
        }
        else if (event.keyCode == 40) {
            tbody.find(".selected").removeClass("selected");
            if (selected.next().length == 0) {
                tbody.find("tr:nth-child(2)").addClass("selected");
            } else {
                $(".TableShareSearchResult").find(".selected").removeClass("selected");
                selected.next().addClass("selected");
            }
        }
        else if (event.keyCode == 13 && $(".TableShareSearchResult").find(".selected").length !== 0) {
            $(".TableShareSearchResult").find(".selected").click();
            $(".sharePopup").hide();
        }
        else if (event.keyCode == 27) {
            $(".sharePopup").hide();
        }
        else if (event.keyCode == 16 && event.keyCode == 9) {
            $(".sharePopup").hide();
        }
        else if (event.keyCode == 9) {
            $(".sharePopup").hide();
        }
        //Updated by ShekharL @20-May-2022 JIRA: BBVAORINT-407- Solar Product Entry - Scroll bar not working when keyboard down arrow key is used for selection.
        var keyCode = window.event ? event.keyCode : event.which;
        $(".sharePopup").scrollTop(0);//set to top
        $(".sharePopup").scrollTop($('.selected:first').offset().top - $(".sharePopup").height());//then set equal to the position of the selected element minus the height of scrolling div
        return;
    }
    else {
        Share_Search(txtSearch, event)
    }
}




function CustomerSearch(txtCustomerSearch, event) {
    //updated by Chandrashekhar 15-Feb-2019 for bnp bond demo


    //var keyCode;
    //var event = event || window.event;

    //if (event.keyCode == 13 || event.keyCode == 38 || event.keyCode == 40 || event.keyCode == 27 || event.keyCode == 9 || event.keyCode == 16 && event.keyCode == 9) {
    //    return;
    //}

    // //
    txtID = "#" + $(txtCustomerSearch).attr('id');
    autocompleteInput = txtID;

    $(txtID).parent().find(".tbl_cust1").hide();
    Mode = $(txtID).parent().find('.txtCustomerMode').val();
    RMID = $(txtID).parent().find('.txtCustomerRMId').val();
    //SessionID = $(txtID).parent('.hdnSessionID').attr('id');
    SessionID = document.getElementById('hdnSessionID').value;


    //alert(RMID);
    //alert(Mode);
    $(autocompleteInput).on("focus", function () { });


    //var e = event || window.event;
    //var keyCode = e.keyCode || e.which;

    var keyCode;
    var event = event || window.event;
    if (event != undefined) {
        keyCode = event.keyCode || event.which;
    }



    if (keyCode != 9) {
        $(txtID).closest('.ui-widget').find('#hdnCounterPartyCode').val("");
    }

    if ($(txtID).val().length < 3) {
        $('.tbl_cust1').hide();
    }


    $(autocompleteInput).autocomplete({
        search: function (event, ui) {
            if (event.keyCode == 13 || event.keyCode == 38 || event.keyCode == 40 || event.keyCode == 27 || event.keyCode == 9 || event.keyCode == 16 && event.keyCode == 9) { event.preventDefault(); }
        },
        minLength: 3,
        autoFocus: false,
        focus: function (event, ui) {
            $(autocompleteInput).val(ui.item.label);
            return false;
        },
        source: function (request, response) {

            $.support.cors = true;
            $.ajax({
                type: "POST",
                url: "../FinIQ_User_Controls/ShareSearch/WebMethod.aspx/GetCustomerNames",
                cache: false,
                data: "{'strSearch':'" + request.term + "', 'Mode':'" + Mode + "','sRMID':'" + RMID + "','SessionID':'" + SessionID + "', maxResults: 3 }",
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                crossDomain: true,
                async: true,
                complete: function (XMLHttpRequest, textStatus, errorThrown) {
                },
                success: function (data) {
                    //alert(data);
                    objData = jQuery.parseJSON(data.d);
                    $('.tbl_cust1').hide();
                    //  response($.map(objData, function (item) {
                    var objData = jQuery.parseJSON(data.d);
                    var tbl = "<div style='overflow-y:auto;height:auto;max-height:300px;background-color:#FFFFFF;' class='Grid sharePopup'>"
                    tbl += "<table id='mstrTable' class='TableCustomerSearchResult_new' cellpadding=1 cellspacing=1 style='border-collapse:collapse;' >"
                    tbl += '<tr><th><div style="width:90%; float:left; padding:3px;">Code</div></th>'
                    //updated by Chandrashekhar 15-Feb-2019 for bnp bond demo
                    tbl += '<th><div style="width:80%; float:left; padding:3px;">Party Name</div><div style="width:10%; float:right; padding:3px;" onClick=\"' + "SelectCustomerDetails_CC(this,'" + 'Close' + "','" + '' + "','" + '' + "')" + '\">X</div></th>';
                    tbl += "</tr>";
                    //HemlataA on 31-03-2020 added null condition.
                    if (objData === null) {
                        $(txtID).closest('.ui-widget').find('#hdnCounterPartyCode').val("");
                        $(txtID).val(''); //Added by SwatiP on 6-6-2022 <BBVAORINT-486>
                        //Updated by ShekharL @20-May-2022 JIRA: BBVAORINT-407 
                        //$('#<%=tbl_cust1.ClientID%>').html("");
                        //$('#<%=tbl_cust1.ClientID%>').hide();
                        $(txtID).parent().find(".tbl_cust1").html('');
                        $(txtID).parent().find(".tbl_cust1").hide();
                        $('.tbl_cust1').hide();
                        tbl += "<tr class='SearchResultRow1'>";
                        tbl += '<td contentEditable="false">No details found for selected Customer.</td>';
                        tbl += '</tr>';
                        tbl += '</table></div>';
                        tblCust1 = $(autocompleteInput).parent().find(".tbl_cust1").attr('id');
                        $("#" + tblCust1).html(tbl);
                        $("#" + tblCust1).css("display", "block");
                        return true; //Updated by ShekharL @20-May-2022 JIRA: BBVAORINT-407-
                    }

                    else if (objData.length === 0) {
                        $(txtID).closest('.ui-widget').find('#hdnCounterPartyCode').val("");
                        $(txtID).val(''); //Added by SwatiP on 6-6-2022 <BBVAORINT-486>
                        //Updated by ShekharL @20-May-2022 JIRA: BBVAORINT-407-
                        $(txtID).parent().find(".tbl_cust1").html('');
                        $(txtID).parent().find(".tbl_cust1").hide();
                        $('.tbl_cust1').hide();
                        tbl += "<tr class='SearchResultRow1'>";
                        tbl += '<td contentEditable="false">No details found for selected Customer.</td>';
                        tbl += '</tr>';
                        tbl += '</table></div>';
                        tblCust1 = $(autocompleteInput).parent().find(".tbl_cust1").attr('id');
                        $("#" + tblCust1).html(tbl);
                        $("#" + tblCust1).css("display", "block");
                        return;
                    }
                    else {

                        console.log("start " + $.now());
                        for (var i = 0; i < objData.length; i++) {
                            if (objData[i].Type == undefined) { //Rohit P on 23-Apr-2020
                                CustType = "";
                            }
                            else {
                                CustType = objData[i].Type;//Rohit P on 23-Apr-2020
                            }
                            tbl += "<tr class='SearchResultRow1' onClick=\"SelectCustomerDetails_CC(this,'" + objData[i].ID + "','" + objData[i].Code + "','" + CustType + "')\">"; //Updated by ShekharL @20-May-2022 JIRA: BBVAORINT-407-
                            tbl += '<td contentEditable="false">' + objData[i].ID + '</td>';
                            tbl += '<td>' + objData[i].Code + '</td>';
                            tbl += '</tr>';
                            console.log(i + " || " + $.now());
                        }
                        tbl += '</table></div>';
                     
                        tblCust1 = $(autocompleteInput).parent().find(".tbl_cust1").attr('id');
                 
                        $("#" + tblCust1).html(tbl);
                        $("#" + tblCust1).css("display", "block");
                        var tbody = $(".TableCustomerSearchResult_new").find("tbody");
                        var selected = tbody.find("tr:nth-child(2)").addClass("selected");
                        //arrowKeySelection();
                    }
                    // }))
                },

                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    try {
                        tbl += "<tr  class='SearchResultRow1_new SearchResultRow1_new'>";
                        tbl += '<td contentEditable="false">No details found for selected Customer.</td>';
                        tbl += '</tr>';
                        tbl += '</table></div>';
                        $(txtID).closest('.ui-widget').find('#hdnCounterPartyCode').val("");
                        tblCust1 = $(autocompleteInput).parent().find(".tbl_cust1").attr('id');

                        $("#" + tblCust1).html(tbl);
                        $("#" + tblCust1).css("display", "block");

                    } catch (e) {

                    }
                }
            });
        }
    });




}
//Added by Shekhar L @14-Mar-2022 Mandiri unwanted calling on every page load
if ($(".TableCustomerSearchResult_new").is(':visible')) {
arrowKeySelection();
} 
 
function arrowKeySelection(that) {
    //$(document).on('keydown',
    //Added by Shekhar L @14-Mar-2022 Mandiri unwanted calling on every page load
    $(that).on('keydown', function (event) {
        //
        var tbody = $(".TableCustomerSearchResult_new").find("tbody");
        selected = tbody.find(".selected");

        if (event.keyCode == 38) {
            $(".TableCustomerSearchResult_new").find(".selected").removeClass("selected");
            if (selected.prev().length == 0) {
                tbody.find("tr:last").addClass("selected");
                $(".Grid").scrollTop(0);
            } else {
                selected.prev().addClass("selected");
                var scrollTP = $(".Grid").scrollTop();
                $(".Grid").scrollTop(scrollTP - 13);
            }
        }
        else if (event.keyCode == 40) {
            tbody.find(".selected").removeClass("selected");
            if (selected.next().length == 0) {
                tbody.find("tr:nth-child(2)").addClass("selected");
                $(".Grid").scrollTop(0);
            } else {
                $(".TableCustomerSearchResult_new").find(".selected").removeClass("selected");
                selected.next().addClass("selected");
                var scrollTP = $(".Grid").scrollTop();
                $(".Grid").scrollTop(scrollTP + 13);
            }
        }
        else if (event.keyCode == 13) {
            //$(".selected").click();
            // Updated by OnkarE on 09-June-2022 JIRA:BBVAORINT-694
            var tbody = $(".TableCustomerSearchResult_new").find("tbody");
            selected = tbody.find(".selected");
            if (event.keyCode == 13) {
                $(".selected").click();
                $(".tbl_cust1").hide();
                return true;
            } else {
                return;
            }
            $(".tbl_cust1").hide();
        }
        else if (event.keyCode == 27) {
            $(".tbl_cust1").hide();
        }
        else if (event.keyCode == 16 && event.keyCode == 9) {
            $(".tbl_cust1").hide();
        }
        else if (event.keyCode == 9) {
            $(".tbl_cust1").hide();
        }
    });
}


//Added by Shekhar L @14-Mar-2022 Mandiri unwanted calling on every page load
if ($(".TableShareSearchResult").is(':visible')) {
arrowKeySelectionShareSearch();
}


function arrowKeySelectionShareSearch() {
    //$(document).on('keydown',
    $(document).on('keydown', function (event) {
        //
        var tbody = $(".TableShareSearchResult").find("tbody");
        selected = tbody.find(".selected");

        if (event.keyCode == 38) {
            $(".TableShareSearchResult").find(".selected").removeClass("selected");
            if (selected.prev().length == 0) {
                tbody.find("tr:last").addClass("selected");
            } else {
                selected.prev().addClass("selected");
                //var scrollTP = $(".Grid").scrollTop();
                //$(".Grid").scrollTop(scrollTP - 15);
            }
        }
        else if (event.keyCode == 40) {
            tbody.find(".selected").removeClass("selected");
            if (selected.next().length == 0) {
                tbody.find("tr:nth-child(2)").addClass("selected");
            } else {
                $(".TableShareSearchResult").find(".selected").removeClass("selected");
                selected.next().addClass("selected");
                //var scrollTP = $(".Grid").scrollTop();
                //$(".Grid").scrollTop(scrollTP + 15);
            }
        }
        else if (event.keyCode == 13 && $(".TableShareSearchResult").find(".selected").length !== 0) {
            //alert("arrowKeySelectionShareSearch");
            $(".TableShareSearchResult").find(".selected").click();
            $(".tbl_cust").hide();
        }
        else if (event.keyCode == 27) {
            $(".tbl_cust").hide();
        }
        else if (event.keyCode == 16 && event.keyCode == 9) {
            $(".tbl_cust").hide();
        }
        else if (event.keyCode == 9) {
            $(".tbl_cust").hide();
        }
    });
}
//Added by Shekhar L @14-Mar-2022 Mandiri unwanted calling on every page load
if ($(".TableCustomerSearchResult_shareCollection").is(':visible')) {
arrowKeySelectionShareCollectionSearch();
}  
function arrowKeySelectionShareCollectionSearch() {
    //$(document).on('keydown',
    $(document).on('keydown', function (event) {
        //
        var tbody = $(".TableCustomerSearchResult_shareCollection").find("tbody");
        selected = tbody.find(".selected");
        //

        if (event.keyCode == 38) {
            $(".TableCustomerSearchResult_shareCollection").find(".selected").removeClass("selected");
            if (selected.prev().length == 0) {
                tbody.find("tr:last").addClass("selected");
            } else {
                selected.prev().addClass("selected");
                //var scrollTP = $(".Grid").scrollTop();
                //$(".Grid").scrollTop(scrollTP - 15);
            }
        }
        else if (event.keyCode == 40) {
            tbody.find(".selected").removeClass("selected");
            if (selected.next().length == 0) {
                tbody.find("tr:nth-child(2)").addClass("selected");
            } else {
                $(".TableCustomerSearchResult_shareCollection").find(".selected").removeClass("selected");
                selected.next().addClass("selected");
                //var scrollTP = $(".Grid").scrollTop();
                //$(".Grid").scrollTop(scrollTP + 15);
            }
        }

        else if (event.keyCode == 13 && $(".TableCustomerSearchResult_shareCollection").find(".selected").length !== 0) {
            //alert("arrowKeySelectionShareCollectionSearch");
            $(".TableCustomerSearchResult_shareCollection").find(".selected").click();
            $(".tbl_cust").hide();
        }
        else if (event.keyCode == 27) {
            $(".tbl_cust").hide();
        }
        else if (event.keyCode == 16 && event.keyCode == 9) {
            $(".tbl_cust").hide();
        }
        else if (event.keyCode == 9) {
            $(".tbl_cust").hide();
        }
    });
}


//added by shreyas v 5-Nov-2020 Mashreq/1finiq changes to support customer CIF Search(Copy of CustomerSearch) start
//updated by Shekhar L @14-Mar-2022 below function BOND Entry for Mandiri Anand K.
function arrowKeyCIFSearch(txtSearch, event) {
 
    var keyCode;
    var event = event || window.event;
    event.preventDefault()

    var tbody = $(".TableCustomerSearchResult_new").find("tbody");
    var selected;
 
    var event = event || window.event;
    if (event != undefined) {
        keyCode = event.keyCode || event.which;
    }  
    if ( event.keyCode == 27 || event.keyCode == 9 || event.keyCode == 16 && event.keyCode == 9) {
        return;
    }
    else if (event.keyCode == 38 || event.keyCode == 40 || event.keyCode == 13) {
        // updated by Shekhar @01-Sep2020 and changed as per Aanad K. & Shreys V.
        arrowKey_txtCIFSearch(txtSearch, event); 
    } 
    else {
        CIFSearch(txtSearch, event);
    }
 
}
//Added by Shekhar L @14-Mar-2022 Mandiri on keydown travel focus on autocomple items
// Start cust search ------------------------------
function CIFSearch(txtCIFSearch, event) {
    //updated by Chandrashekhar 15-Feb-2019 for bnp bond demo


    var keyCode;
    var event = event || window.event;

    //if (event.keyCode == 13 || event.keyCode == 38 || event.keyCode == 40 || event.keyCode == 27 || event.keyCode == 9 || event.keyCode == 16 && event.keyCode == 9) {
    //    return;
    //}

    // //
    txtID = "#" + $(txtCIFSearch).attr('id');
    autocompleteInput = txtID;

    $(txtID).parent().find(".tbl_cust1").hide();
    Mode = $(txtID).parent().find('.txtCustomerMode').val();
    RMID = $(txtID).parent().find('.txtCustomerRMId').val();
    //SessionID = $(txtID).parent('.hdnSessionID').attr('id');
    SessionID = document.getElementById('hdnSessionID').value;


    //alert(RMID);
    //alert(Mode);
    $(autocompleteInput).on("focus", function () { });


    //var e = event || window.event;
    //var keyCode = e.keyCode || e.which;

    var keyCode;
    var event = event || window.event;
    if (event != undefined) {
        keyCode = event.keyCode || event.which;
    }



    if (keyCode != 9) {
        $(txtID).closest('.ui-widget').find('#hdnCounterPartyCode').val("");
    }

    if ($(txtID).val().length < 3) {
        $('.tbl_cust1').hide();
    }


    $(autocompleteInput).autocomplete({
        search: function (event, ui) {
            //if (event.keyCode == 13 || event.keyCode == 38 || event.keyCode == 40 || event.keyCode == 27 || event.keyCode == 9 || event.keyCode == 16 && event.keyCode == 9) { event.preventDefault(); }
        },
        minLength: 3,
        autoFocus: false,
        focus: function (event, ui) {
            $(autocompleteInput).val(ui.item.label);
            return false;
        },
        source: function (request, response) {
            $.support.cors = true;
            $.ajax({
                type: "POST",
                url: "../FinIQ_User_Controls/ShareSearch/WebMethod.aspx/GetCustomersWithCif",  //added by shreyas v 5-Nov-2020 Mashreq/1finiq changes to support customer CIF Search

                cache: false,
                data: "{'strSearch':'" + request.term + "', 'Mode':'" + Mode + "','sRMID':'" + RMID + "','SessionID':'" + SessionID + "','LRCMode':'', maxResults: 3 }",
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                crossDomain: true,
                async: true,
                complete: function (XMLHttpRequest, textStatus, errorThrown) {
                },
                success: function (data) {
                    //alert(data);


                    objData = jQuery.parseJSON(data.d);
                    $('.tbl_cust1').hide();
                    //  response($.map(objData, function (item) {
                    var objData = jQuery.parseJSON(data.d);
                    var tbl = "<div style='overflow-y:auto;height:auto;max-height:300px;background-color:#FFFFFF;' class='Grid sharePopup'>"
                    tbl += "<table id='mstrTable' class='TableCustomerSearchResult_new' cellpadding=1 cellspacing=1 style='border-collapse:collapse;' >"
                    tbl += '<tr><th><div style="width:90%; float:left; padding:3px;">Code</div></th>'
                    //updated by Chandrashekhar 15-Feb-2019 for bnp bond demo
                    tbl += '<th><div style="width:80%; float:left; padding:3px;">Party Name</div><div style="width:10%; float:right; padding:3px;" onClick=\"' + "SelectCustomerDetails_CC(this,'" + 'Close' + "','" + '' + "','" + '' + "')" + '\">X</div></th>';
                    tbl += "</tr>";
                    //HemlataA on 31-03-2020 added null condition.
                    if (objData === null) {
                        $(txtID).closest('.ui-widget').find('#hdnCounterPartyCode').val("");
                        $('#<%=tbl_cust1.ClientID%>').html("");
                        $('#<%=tbl_cust1.ClientID%>').hide();
                        $('.tbl_cust1').hide();
                        tbl += "<tr class='SearchResultRow1'>";
                        tbl += '<td contentEditable="false">No details found for selected Customer.</td>';
                        tbl += '</tr>';
                        tbl += '</table></div>';
                        tblCust1 = $(autocompleteInput).parent().find(".tbl_cust1").attr('id');
                        $("#" + tblCust1).html(tbl);
                        $("#" + tblCust1).css("display", "block");
                        return;
                    }

                    else if (objData.length === 0) {
                        $(txtID).closest('.ui-widget').find('#hdnCounterPartyCode').val("");
                        $('#<%=tbl_cust1.ClientID%>').html("");
                        $('#<%=tbl_cust1.ClientID%>').hide();
                        $('.tbl_cust1').hide();
                        tbl += "<tr class='SearchResultRow1'>";
                        tbl += '<td contentEditable="false">No details found for selected Customer.</td>';
                        tbl += '</tr>';
                        tbl += '</table></div>';
                        tblCust1 = $(autocompleteInput).parent().find(".tbl_cust1").attr('id');
                        $("#" + tblCust1).html(tbl);
                        $("#" + tblCust1).css("display", "block");
                        return;
                    }
                    else {

                        console.log("start " + $.now());
                        for (var i = 0; i < objData.length; i++) {
                            if (objData[i].Type == undefined) { //Rohit P on 23-Apr-2020
                                CustType = "";
                            }
                            else {
                                CustType = objData[i].Type;//Rohit P on 23-Apr-2020
                            }
                            tbl += "<tr class='SearchResultRow1' onClick=\"SelectCustomerDetails_CC(this,'" + objData[i].ID + "','" + objData[i].Code + "','" + CustType + "')\">"; //Updated by ShekharL @20-May-2022 JIRA: BBVAORINT-407-
                            tbl += '<td contentEditable="false">' + objData[i].ID + '</td>';
                            tbl += '<td>' + objData[i].Code + '</td>';
                            tbl += '</tr>';
                            console.log(i + " || " + $.now());
                        }
                        tbl += '</table></div>';
                        console.log("append complete " + $.now());
                        tblCust1 = $(autocompleteInput).parent().find(".tbl_cust1").attr('id');
                        console.log($.now());
                        $("#" + tblCust1).html(tbl);
                        $("#" + tblCust1).css("display", "block");
                        var tbody = $(".TableCustomerSearchResult_new").find("tbody");
                        var selected = tbody.find("tr:nth-child(2)").addClass("selected");
                        //arrowKeySelection();
                    }
                    // }))
                },

                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    try {
                        tbl += "<tr  class='SearchResultRow1_new SearchResultRow1_new'>";
                        tbl += '<td contentEditable="false">No details found for selected Customer.</td>';
                        tbl += '</tr>';
                        tbl += '</table></div>';
                        $(txtID).closest('.ui-widget').find('#hdnCounterPartyCode').val("");
                        tblCust1 = $(autocompleteInput).parent().find(".tbl_cust1").attr('id');

                        $("#" + tblCust1).html(tbl);
                        $("#" + tblCust1).css("display", "block");

                    } catch (e) {

                    }
                }
            });
        }
    });

}

//end cust search---------------------------



//added by shreyas v 5-Nov-2020 Mashreq/1finiq changes to support customer CIF Search(Copy of CustomerSearch) END

//jQuery AutoComplete Select Event
//updated by Chandrashekhar 15-Feb-2019 for bnp bond demo
function SelectCustomerDetails_CC(selRow, strCode, strLongName, strExchangeCode) {//, strExchangeName, strCcy) {
    try {

        if (strCode == 'Close') {
            $(selRow).closest('.tbl_cust1').hide();
        } else {
            $(selRow).closest('.ui-widget').find('.textboxAuto').val(strLongName);
            $(selRow).closest('.ui-widget').find('#hdnCounterPartyCode').val(strCode);
            $(selRow).closest('.ui-widget').find('#hdnCounterPartyName').val(strLongName);
            $(selRow).closest('.ui-widget').find('#hdnClientCode').val(strExchangeCode);
            //    $(selRow).closest('.ui-widget').find('#hdnClientName').val(strExchangeName);
            // $(selRow).closest('.ui-widget').find('#hdnCcy').val(strCcy);
            $(selRow).closest('.tbl_cust1').hide();
            //alert(strCode);
            //Updated by ShekharL @20-May-2022 JIRA: BBVAORINT-407
          //  $(selRow).focus();
            //$(autocompleteInput).focus();
            $(selRow).closest('.ui-widget').find('#btnSelect').click();
            //document.getElementById('btnSelect').click();
            //$(this).parent().find(".btntxtCustomerSearch").click();
            // var tempclick = $("input[id$='btntxtCustomerSearch']")[0].id
            // $("#"+tempclick).click()
        }
    } catch (er) { console.log(er.message); }
}


function Share_Search(txtShareSearch) {
    $.support.cors = true;
    //   autocompleteInput = $(autocompleteInput).prop('id');
    txtID = "#" + $(txtShareSearch).attr('id');
    autocompleteInput = txtID;
    var strMarketype;
    strMarketype = $(txtID).closest('.ui-widget').find('#hdnMarketype').val();
    $(txtID).parent().find(".tbl_cust").hide();

    //var e = event || window.event;
    //var keyCode = e.keyCode || e.which;

    var keyCode;
    var event = event || window.event;
    if (event != undefined) {
        keyCode = event.keyCode || event.which;
    }


    if (keyCode != 9) {
        $(txtID).closest('.ui-widget').find('#hdnShareCode').val("");
    }
    if ($(txtID).val().length < 1) {        
        $(txtID).closest('.ui-widget').find('#hdnShareCode').val("");
        $(txtID).parent().find(".tbl_cust").hide();
        window.SelectShareDetails(this, 'Clear', '', '', '', '');
    }
    $(autocompleteInput).autocomplete({
        search: function (event, ui) {
            if (event.keyCode == 13 || event.keyCode == 38 || event.keyCode == 40 || event.keyCode == 27 || event.keyCode == 9 || event.keyCode == 16 && event.keyCode == 9) { event.preventDefault(); }
        },
        minLength: 1,
        autoFocus: true,
        focus: function (event, ui) {
            $(autocompleteInput).val(ui.item.label);
            return false;
        },
        source: function (request, response) {
            $.ajax({
                type: "POST",
                url: "../FinIQ_User_Controls/ShareSearch/WebMethod.aspx/GetSharesNames",
                cache: false,
                data: "{'strSearch':'" + request.term + "', 'strMarketype':'" + strMarketype + "', maxResults: 3 }",
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                crossDomain: true,
                complete: function (XMLHttpRequest, textStatus, errorThrown) {
                    //alert(textStatus);
                },
                success: function (data) {
                    objData = jQuery.parseJSON(data.d);
                    $('.tbl_cust').hide();
                    //response($.map(objData, function (item) {
                    var objData = jQuery.parseJSON(data.d);
                    var tbl = "<div style='overflow-y:auto;height:auto;max-height:300px;background-color:#FFFFFF;' class='Grid sharePopup'>";
                    tbl += "<table id='mstrTable' class='TableShareSearchResult' cellpadding=1 cellspacing=1 style='border-collapse:collapse;' >";
                    tbl += '<tr><th><div style="width:90%; float:left; padding:3px;">Code</div></th>';
                    tbl += '<th><div style="width:80%; float:left; padding:3px;">Share Name</div><div style="width:10%; float:right; padding:3px;" onClick=\"' + "SelectShareDetails(this,'" + 'Close' + "','" + '' + "','" + '' + "','" + '' + "','" + '' + "')" + '\">X</div></th>';
                    tbl += "</tr>";
                    if (objData.length === 0) {
                        $(txtID).parent().find(".tbl_cust").html('');
                        $(txtID).parent().find(".tbl_cust").hide();
                        // alert("No details found.");
                        $(txtID).parent().find("#hdnShareCode").val('');
                        $(txtID).blur(function () {
                            if ($(txtID).closest('.ui-widget').find('#hdnShareCode').val() === "") {
                                $(this).val('');
                                // $(txtID).parent().find(".btnSelect").click();
                            }
                        });
                        return;
                    }
                    else {
                        for (var i = 0; i < objData.length; i++) {
                            tbl += "<tr class='SearchResultRow' onClick=\"SelectShareDetails(this,'" + objData[i].Code + "','" + objData[i].LongName.replace(/'/g, "\\'") + "','" + objData[i].ExchangeCode + "','" + objData[i].ExchangeName + "','" + objData[i].Ccy + "')\">"; //replace(/'/g, "\\'") added escapehtml by akshayd 13-July-2020 for share selection issue
                            tbl += '<td contentEditable="false">' + objData[i].Code + '</td>';
                            tbl += '<td>' + objData[i].LongName + '</td>';
                            tbl += '</tr>';
                        }
                        tbl += '</table></div>';
                        tblCust1 = $(autocompleteInput).parent().find(".tbl_cust").attr('id');
                        $("#" + tblCust1).html(tbl);
                        $("#" + tblCust1).css("display", "block");
                        var tbody = $(".TableShareSearchResult").find("tbody");
                        var selected = tbody.find("tr:nth-child(2)").addClass("selected");
                        $(txtID).blur(function () {
                            if ($(txtID).closest('.ui-widget').find('#hdnShareCode').val() === "") {
                                if ($(this).val() == objData[0].Code) {
                                    $(txtID).closest('.ui-widget').find('#hdnShareCode').val(objData[0].Code);
                                    $(txtID).parent().find(".btnSelect").click();
                                }
                            }
                        });
                    }
                    // }))
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    $(txtID).parent().find(".tbl_cust").hide();
                    $(txtID).blur(function () {
                        if ($(txtID).closest('.ui-widget').find('#hdnShareCode').val() === "") {
                            $(this).val('');
                        }
                    });
                },
                select: function (event, ui) {
                    if (ui.item) {
                        $('#hdnShareCode').val(ui.item.Code);
                        $('#hdnShareLongName').val(ui.item.LongName);
                    }
                }
            });
        }
    });
}

$.support.cors = true;
//jQuery AutoComplete Select Event
function SelectShareDetails(selRow, strCode, strLongName, strExchangeCode, strExchangeName, strCcy) {
    if (strCode == 'Close') {
        $(selRow).closest('.tbl_cust').hide();
    } else if (strCode == 'Clear') {
        $(selRow).closest('.ui-widget').find('.textboxAuto').val('');
        $(selRow).closest('.ui-widget').find('#hdnShareCode').val('');
        $(selRow).closest('.ui-widget').find('#hdnShareLongName').val('');
        $(selRow).closest('.ui-widget').find('#hdnExchangeCode').val('');
        $(selRow).closest('.ui-widget').find('#hdnExchangeName').val('');
        $(selRow).closest('.ui-widget').find('#hdnCcy').val('');
        $(selRow).closest('.tbl_cust').hide();
        $(autocompleteInput).focus();
        $(txtID).parent().find(".btnSelect").click();
    }
    else {
        if ($(selRow).closest('.tbl_cust')[0].style.display === "block") {
            $(selRow).closest('.ui-widget').find('.textboxAuto').val(strCode);
            $(selRow).closest('.ui-widget').find('#hdnShareCode').val(strCode);
            $(selRow).closest('.ui-widget').find('#hdnShareLongName').val(strLongName);
            $(selRow).closest('.ui-widget').find('#hdnExchangeCode').val(strExchangeCode);
            $(selRow).closest('.ui-widget').find('#hdnExchangeName').val(strExchangeName);
            $(selRow).closest('.ui-widget').find('#hdnCcy').val(strCcy);
            $(selRow).closest('.tbl_cust').hide();
            $(autocompleteInput).focus();
            $(txtID).parent().find(".btnSelect").click();
        }
    }
}



var MONTH_NAMES1 = new Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');
setDateTime();
function setDateTime() {
    //   $(document).ready(function () {
  //  $(document).on('keydown', '.UCPDate, .UCPDateTime, .UCPTime, .txtDateTime:not(.hasDatepicker)', function (e) {   //06-Apr-2022 UWI-308 Shekhar L/Akshay D
    $(document).on('keydown', '.UCPDate, .UCPDateTime, .UCPTime', function (e) {
        var e = e || event || window.event;
        var dateTime = new Date();
        var day = dateTime.getDate();
        var month = dateTime.getMonth();
        var year = dateTime.getFullYear();
        var h = dateTime.getHours();
        t = h < 12 ? "AM" : "PM";
        h = (h > 12) ? (h - 12) : h;
        h = (h < 10) ? ("0" + h) : h;
        var m = dateTime.getMinutes();
        m = (m < 10) ? ("0" + m) : m;
        var s = dateTime.getSeconds();
        s = (s < 10) ? ("0" + s) : s;
        // console.log(e.which + " : " + e.keyCode + " : " + day + "-" + MONTH_NAMES1[month] + "-" + year + " " + h + ":" + m + ":" + s + ":" + t)
        if (((e.which === 186) && e.ctrlKey && e.shiftKey) || ((e.which === 69) && e.ctrlKey && e.shiftKey)) {
            $(this).val(day + "-" + MONTH_NAMES1[month] + "-" + year + " " + h + ":" + m + ":" + s + ":" + t);
        }
        else if ((e.which === 186) && e.ctrlKey) {
            $(this).val(day + "-" + MONTH_NAMES1[month] + "-" + year);
        }
        else if ((e.which === 222) && e.ctrlKey) {
            $(this).val(h + ":" + m + ":" + s + ":" + t);
        }
    });
    // }); 
}
//</ DB share/Counterparty/client search user control By Shekhar vIMP dn't change without permission>
function Get_FocusedControl1() {

    $(":focus").each(function () {
        if ($(this).get(0).tagName != 'A' || $(this).get(0).tagName != 'IMG' || $(this).get(0).tagName != 'DIV') {
            $("#lastcontrol").val($(this).attr("id"));
            lastcontrol = $("#lastcontrol").val();
        }
    });
}

function Set_FocusedControl1() {

    lastcontrol = $("#lastcontrol").val();
    $("#" + lastcontrol).focus();
    if (lastcontrol !== undefined || lastcontrol !== null) {
        $("#" + lastcontrol).focus(function () {
            if ($(this).get(0).type != 'submit') {
                $(this).select();
            }
        });
        return $("#" + lastcontrol).each(function () {
            $(this).focus();
            if ($(this).get(0).type != 'submit' || $(this).get(0).type != 'reset' || $(this).get(0).type != 'button') {
                if (this.setSelectionRange) {
                    var len = $(this).val().length * 2;
                    //this.setSelectionRange(0, len);  //-----on this line get error
                } else {
                    $(this).val($(this).val());
                }
                this.scrollTop = 999999;
            }
        });
    }
}

function DisabledRow_DropDownColor() {
    $(document).ready(function () {
        $('.DisabledRow').each(function () {
            $('select[disabled="disabled"]').each(function (i) {
                alert(i);
                $(this).css('color', '#FF000000');
            });
        });
    });
}

function SendResponseToHub(loggedUser, index) {
    $('document').ready(function () {
        //$(window.parent.document).find("#ctl00_MainContent_btnRef").text = index;
        $(window.parent.document).find("#ctl00_MainContent_btnDef").click();
    });
}

function ChangeFrameHeight() {
    $('document').ready(function () {
        $(window.parent.document).find("#ctl00_MainContent_btniframe").click();
    });
}

//Pallavi
function onlyAlphaNumberDecimal(event, ctl) {
    var charCode;
    var txt;
    var len;
    var dot;
    var minus;
    try {
        charCode = (event.which) ? event.which : event.keyCode;
        txt = $(ctl).val();
        len = txt.length;
        dot = txt.indexOf('.');
        //minus = txt.indexOf('-');
        if (charCode > 31 && (charCode < 48 || charCode > 57) && (charCode < 65 || charCode > 90) && (charCode < 97 || charCode > 122) && charCode != 95) {
            return false;
        } else {
            if (dot >= 0 && charCode == 46) {
                return false;
            }
            if (charCode == 45) {
                return false;
            }
            if (dot > 0) {
                var CharAfterdot = (len + 1) - dot;
                if (CharAfterdot > 10) {
                    return false;
                }
            }
        }
        return true;
    }
    catch (error) {

    }
    finally {
        charCode = null;
        txt = null;
        len = null;
        dot = null;
        minus = null;
    }
}

//Updated by Neeral+Shekhar on 22Jan200
function FunctionSearch(event, txtCustomerSearch) {
    txtID = "#" + $(txtCustomerSearch).attr('id');
    autocompleteInput = txtID;
    $(txtID).parent().find(".tbl_cust1").hide();
    var strFunction_Type;
    strFunction_Type = $(txtID).closest('.ui-widget').find('#hdnFunction_Type').val();
    SessionID = $(txtID).closest('.ui-widget').find('#hdnSessionID').val();
    //SessionID = document.getElementById('hdnSessionID').value;

    var strDB_Name;
    strDB_Name = $(txtID).closest('.ui-widget').find('#hdnDB_name').val();
    $(autocompleteInput).on("focus", function () { });
    var e = event || window.event;
    var keyCode = e.keyCode || e.which;
    if (keyCode != 9) {
        // $(txtID).closest('.ui-widget').find('#hdnCounterPartyCode').val("");
    }
    if ($(txtID).val().length < 3) {
        $('.tbl_cust1').hide();
    }
    $(autocompleteInput).autocomplete({
        minLength: 3,
        autoFocus: false,
        focus: function (event, ui) {
            $(autocompleteInput).val(ui.item.label);
            return false;
        },
        source: function (request, response) {
            $.support.cors = true;

            $.ajax({
                type: "POST",
                url: "../FinIQ_User_Controls/ShareSearch/WebMethod.aspx/GetFunctionNames",
                cache: false,
                data: "{'strSearch':'" + request.term + "', 'Function_Type':'" + strFunction_Type + "', 'DB_name':'" + strDB_Name + "','SessionID':'" + SessionID + "', maxResults: 3 }",
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                crossDomain: true,
                async: true,
                complete: function (XMLHttpRequest, textStatus, errorThrown) {
                },
                success: function (data) {
                    objData = jQuery.parseJSON(data.d);
                    $('.tbl_cust1').hide();
                    //  response($.map(objData, function (item) { 
                    var tbl = "<div style='overflow-y:auto;height:auto;max-height:300px;background-color:#FFFFFF;' class='Grid sharePopup'>";
                    tbl += "<table id='mstrTable' class='TableCustomerSearchResult_new' cellpadding=1 cellspacing=1 style='border-collapse:collapse;' >";
                    tbl += '<tr>';
                    tbl += '<th><div style=" float:left; padding-top:3px; padding-left:3px">Name</div><div style="width:10%; float:right; padding:3px;" onClick=\"' + "SelectFunctionName(this,'" + 'Close' + "','" + '' + "','" + '' + "','" + '' + "','" + '' + "')" + '\">X</div></th>';
                    tbl += "</tr>";
                    if (objData !== null) {
                        if (objData.length === 0) {
                            $(txtID).closest('.ui-widget').find('#hdnCounterPartyCode').val("");
                            $('#<%=tbl_cust1.ClientID%>').html("");
                            $('#<%=tbl_cust1.ClientID%>').hide();
                            $('.tbl_cust1').hide();
                            tbl += "<tr class='SearchResultRow1'>";
                            tbl += '<td contentEditable="false">No details found for selected function.</td>';
                            tbl += '</tr>';
                            tbl += '</table></div>';
                            tblCust1 = $(autocompleteInput).parent().find(".tbl_cust1").attr('id');
                            $("#" + tblCust1).html(tbl);
                            $("#" + tblCust1).show();
                            $("#" + tblCust1).css("display", "block");
                            return;
                        }
                        else {
                            for (var i = 0; i < objData.length; i++) {
                                tbl += "<tr class='SearchResultRow1' onClick=\"SelectFunctionName(this,'" + objData[i].type_desc + "','" + objData[i].name + "')\">";
                                tbl += '<td>' + objData[i].name + '</td>';
                                tbl += '</tr>';
                            }
                            tbl += '</table></div>';
                            tblCust1 = $(autocompleteInput).parent().find(".tbl_cust1").attr('id');
                            $("#" + tblCust1).html(tbl);
                            $("#" + tblCust1).css("display", "block");
                        }
                        // }))
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    try {
                        tbl += "<tr  class='SearchResultRow1_new SearchResultRow1_new'>";
                        tbl += '<td contentEditable="false">No details found for selected Customer.</td>';
                        tbl += '</tr>';
                        tbl += '</table></div>';
                        $(txtID).closest('.ui-widget').find('#hdnCounterPartyCode').val("");
                        tblCust1 = $(autocompleteInput).parent().find(".tbl_cust1").attr('id');
                        $("#" + tblCust1).html(tbl);
                        $("#" + tblCust1).css("display", "block");
                    } catch (e) {
                    }
                }
            });
        }
    });
}

function SelectFunctionName(selRow, strCode, strLongName) {
    if (strCode == 'Close') {
        $(selRow).closest('.tbl_cust1').hide();
    } else {
        $(selRow).closest('.ui-widget').find('.textboxAuto').val(strLongName);
        $(selRow).closest('.ui-widget').find('#hdnExchangeCode').val(strCode);
        $(selRow).closest('.ui-widget').find('#hdnExchangeName').val(strLongName);
        //$(selRow).closest('.ui-widget').find('#hdnClientCode').val(strExchangeCode);
        //$(selRow).closest('.ui-widget').find('#hdnClientName').val(strExchangeName);
        // $(selRow).closest('.ui-widget').find('#hdnCcy').val(strCcy);
        $(selRow).closest('.tbl_cust1').hide();
        //alert(strCode);
        $(selRow).focus();
        $(autocompleteInput).focus();
        // document.getElementById('<%=btnSelect.ClientID()%>').click();
        __doPostBack('#ctl00$MainContent$oUCPFunctionDefination$dgvFunctionDefination$ctl05$FinIQ_Function_Search$txtShare', strLongName);
    }
}

function SearchTable(sTableID, iColumnIndex, strFilter) {
    try {
        //  RemovePagination();
        console.log("SearchTable");

        var sfilter;
        var arrData = $('#' + sTableID).find('.GridItem, .GridItemSelect').get();
        arrColIndex = [];
        $("#" + sTableID).find(".Grid th, .GridHeader th, .GridHeader td, .gridCol th").each(function (colIndex, cell) {
            GridTH = $(this);
            if ($(GridTH).find('input[type="checkbox"]').length == 0) {

                $(GridTH).find('input[type="text"]').each(function (txtIndex, thTextBox) {
                    sfilter = $(thTextBox).val();
                });

                if (sfilter == " ") {
                    sfilter = '';
                    $(GridTH).find('input[type="text"]').val(sfilter);
                    return false;
                }

                if (sfilter != "") {
                    $(GridTH).removeClass("filter_1").addClass("filter_0");
                    // strFilter = $(this).find('input[type="text"]').val();

                    if (sfilter != undefined && sfilter != "Search..." && sfilter != "") {
                        arrColIndex.push({ "colIndex": colIndex, "searchString": JSON.stringify(sfilter) });
                    }
                }
                else {
                    $(GridTH).removeClass("filter_0").addClass("filter_1");
                }
            }
        });

        if (typeof arrColIndex != "string" && arrColIndex.length > 0) {
            localStorage.removeItem('arrColIndex');
            localStorage.setItem('arrColIndex', JSON.stringify(arrColIndex));
        }
        else {

            SetFilterIcon(GridTH);
        }
        $.each(arrData, function (index, row) {

            var iTDIndex = $(row).children('td:not("table")').eq(iColumnIndex).text().toUpperCase();
            if (arrColIndex.length > 0) {
                var displayFlag = 1;
                $(arrColIndex).each(function (icol) {

                    ColumnIndex = JSON.parse(arrColIndex[icol].colIndex);
                    sFilter = JSON.parse(arrColIndex[icol].searchString).toUpperCase();
                    iTDIndex = $(row).children('td:not("table")').eq(ColumnIndex).text().toUpperCase();

                    if (iTDIndex.indexOf(sFilter) > -1) {
                        if (displayFlag == 1) {
                            $(row).css("display", "");
                        }
                    } else {

                        $(row).css("display", "none");
                        displayFlag = 0;
                    }

                    $('#' + sTableID).find('tbody:first').append(row);
                    if ((arrData.length - 1) == index) {
                        $('#' + sTableID).find('tbody:first').append($('#' + sTableID).find('.GridPager').get());
                    }

                });

            }
            else {
                $(row).css("display", "");
                $('#' + sTableID).find('tbody:first').append(row);
                if ((arrData.length - 1) == index) {
                    $('#' + sTableID).find('tbody:first').append($('#' + sTableID).find('.GridPager').get());
                }
            }
        });

        if (SortColIndex.length > 0) {
            sortTable("ctl00_MainContent_workflowControl_queue_data_grid", SortColIndex[0].colIndex, SortColIndex[0].sortString);
        }
    }
    catch (er) { console.log(er.message); }
}


function autocomplete_clicked(AH_Id, Name, Doc_Type, Doc_Id, Type, CIF_No, Either_To_Sign, CIN) {
    try {
        $('#cust_name').val(Name);
        $("#automplete_2").val(Name);
        $('#sel_cust_type').val(Doc_Type);
        //$('#sel_cust_tlt_id').val(CDM_TLT_ID);
        //$('#sel_cust_rm_id').val(AH_CIF_No);
        //$('#sel_cust_allocation_code').val(AH_ALLOCATION_CODE);
        $('#sel_AH_ID').val(AH_Id);
        $('#sel_cust_Doc_ID').val(Doc_Id);
        $('#sel_CIF_No').val(CIF_No);
        $('#sel_CIN').val(CIN);
        $("#tbl_cust").hide();
        __doPostBack('cust_name_ValueChanged', 'ValueChanged');
    }
    catch (error) {

    }
    finally {

    }
}

function autocomplete_clicked2(AH_Id, Name, Doc_Type, Doc_Id, Type, CIF_No, Either_To_Sign, CIN) {
    try {
        $('#cust_name1').val(Name);
        $("#automplete_2").val(Name);
        $('#sel_cust_type1').val(Doc_Type);
        //$('#sel_cust_tlt_id').val(CDM_TLT_ID);
        //$('#sel_cust_rm_id').val(AH_CIF_No);
        //$('#sel_cust_allocation_code').val(AH_ALLOCATION_CODE);
        $('#sel_AH_ID1').val(AH_Id);
        $('#sel_cust_Doc_ID1').val(Doc_Id);
        $('#sel_CIF_No1').val(CIF_No);
        $('#sel_CIN1').val(CIN);
        $("#tbl_cust1").hide();
        //<Change done by Nitin N/Mayuri C on 16-Feb-2021 : MASINT-1394 Changes in Customer Profile, Customer Account and RM Setup>>
        // __doPostBack('cust_name1_ValueChanged', 'ValueChanged');
        //   $("#" + x).parent().find("#btnSelect").click()


        $("#btnSelect1").click()

        //  $("#" + ProAutoCompletectrl.id).parent().find("#btnSelect1").click()

    }
    catch (error) {

    }
    finally {

    }
}

var Cust, Dropdown;

function SearchCustomerByChanged(Cust, Dropdown) {
    try {
        //
        //var y = CustSearchctrl.id;
        //$(CustAutoCompletectrl).text = "";
        //$("#" + CustAutoCompletectrl.id).val("");
        //alert(Cust);
        //alert(Dropdown);
        //var y = DdlCustSearchctrl.id;
        $('#' + Cust.id).val("");
        //var textbox1 = document.getElementById(Cust);

        //textboxt1.text = "";
        var dropdown1 = $('#' + Dropdown.id);
        //alert(dropdown1);
        var selected = dropdown1.prop('selectedIndex');
        //alert(selected);
        //var dropdown1 = document.getElementById(Dropdown);
        //var selected = dropdown1.selectedIndex;
        if (selected == 0) {
            urlToRest = "CustomerName";
        }
        else if (selected == 1) {
            urlToRest = "CustomerID";
        }
        else if (selected == 2) {
            urlToRest = "TLTID";
        }
        else if (selected == 3) {
            urlToRest = "CIFNUMBER";
        }
        else if (selected == 4) {
            urlToRest = "ALLOCATIONCODE";
        }
        else if (selected == 5) {
            urlToRest = "ACCOUNTNUMBER";
        }
        //$("#" + x).val("");
        //alert(urlToRest);
        $(tableControl).hide();

    }
    catch (error) {

    }
    finally {
        cust = null;
        Dropdown = null;

    }
}

function ClearCustomerControl(event) {
    try {
        var txt = $("#" + x).val().trim();

        if (term == "") {
            autocomplete_customerclicked('', '0', '', '', '', '', '', '')
            //alert($('#sel_cust_bcfx_id').value);
            return;
        }
    }
    catch (error) {

    }
    finally {

    }
}



// <Start || Arshin S || For Market Data pages || 6th April 2017>

function AllowNumericOnly(e) {
    var keycode;
    if (window.event)
        keycode = window.event.keyCode;
    else if (event)
        keycode = event.keyCode;
    else if (e)
        keycode = e.which;
    else return true;
    if ((keycode > 47 && keycode <= 57)) { return true; }
    else { return false; } return true;
}

function AllowAlphaNumeric(e) {
    var keycode;
    if (window.event)
        keycode = window.event.keyCode;
    else if (event)
        keycode = event.keyCode;
    else if (e)
        keycode = e.which;
    else return true;

    if ((keycode > 47 && keycode < 58) || (keycode > 64 && keycode < 91) || (keycode > 96 && keycode < 123)) {
        return true;
    }
    else {
        return false;
    }
    return true;
}


function AllowAlphaNumericfortxtIDCode(e) {
    var keycode;
    if (window.event)
        keycode = window.event.keyCode;
    else if (event)
        keycode = event.keyCode;
    else if (e)
        keycode = e.which;
    else return true;

    if ((keycode > 47 && keycode < 58) || (keycode > 64 && keycode < 91) || (keycode > 96 && keycode < 123) || keycode == 46) {
        return true;
    }
    else {
        return false;
    }
    return true;
}


function AllowNumericWithdecimal_MarketData(e) {
    var keycode;
    if (window.event)
        keycode = window.event.keyCode;
    else if (event)
        keycode = event.keyCode;
    else if (e)
        keycode = e.which;
    else return true;

    if (keycode > 31 && (keycode < 48 || keycode > 57) && keycode != 46) { return false; }
    else { return true; } return false;
}

function AllowStringOnly(e) {
    var keycode;
    if (window.event)
        keycode = window.event.keyCode;
    else if (event)
        keycode = event.keyCode;
    else if (e)
        keycode = e.which;
    else return true;
    if ((keycode > 47 && keycode <= 57)) { return false; }
    else { return true; } return false;
}


//------------ nishant - pair crosses Javascript start------------------------//

function numericwithdecimal(el, evt) {

    var charCode = (evt.which) ? evt.which : event.keyCode;
    var number = el.value.split('.');
    if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    }
    //just one dot & minus
    if (number.length > 1 && charCode == 46) {
        return false;
    }
    return true;
}

//--------------pair crosses Javascript end-------------//


//<Pooja S || Market Data || 7-Apr-2017>
function setRowColorOnCheckClick(chkBox) {
    var rowspan = $(chkBox).parent().parent().attr("rowspan");
    var a;
    if (typeof (rowspan) == "undefined") {
        a = 1;
    }
    else {
        a = parseInt(rowspan);
    }

    var trpointer = chkBox.parentNode.parentNode.parentNode;

    if (chkBox.checked) {
        for (var i = 0; i < a; i++) {
            $(trpointer).css("background-color", "#f6f6f6");
            trpointer = $(trpointer).next();
        }
    }
    else {
        for (var i = 0; i < a; i++) {
            $(trpointer).css("background-color", "");
            trpointer = $(trpointer).next();
        }
    }
}


function allowNegativeDecimalNumber(element, e) {
    var charCode = (e.which) ? e.which : event.keyCode
    var number = element.value.split('.');
    if (charCode > 31 && (charCode < 45 || charCode > 57)) {
        return false;
    }
    if (number.length > 1 && charCode == 46) {

        return false;
    }
    number = element.value.split('-');
    if (number.length > 1 && charCode == 45) {

        return false;
    }
    return true;

}
//</End Pooja S || Market Data || 7-Apr-2017>

//< DB share/Counterparty/client search user control By Shekhar vIMP dn't change without permission>

//Start-------------------------------------------
//Updated by Neeral+Shekhar on 22Jan200
function FieldUcpSearch(event, txtFieldSearch) {

    txtID = "#" + $(txtFieldSearch).attr('id');
    autocompleteInput = txtID;

    $(txtID).parent().find(".tbl_cust1").hide();
    Mode = $(txtID).parent().find('.txtCustomerMode').val();
    TargetField = $(txtID).parent().find('.txtTargetField').val();

    SessionID = document.getElementById('hdnSessionID').value;
    $(autocompleteInput).on("focus", function () { });


    var e = event || window.event;
    var keyCode = e.keyCode || e.which;


    if (keyCode != 9) {
        $(txtID).closest('.ui-widget').find('#hdnCounterPartyCode').val("");
    }

    if ($(txtID).val().length < 3) {
        $('.tbl_cust1').hide();
    }

    $(autocompleteInput).autocomplete({
        minLength: 1,
        autoFocus: false,
        focus: function (event, ui) {
            $(autocompleteInput).val(ui.item.label);
            return false;
        },
        source: function (request, response) {
            var blnkStr = "";
            $.support.cors = true;
            SessionID = document.getElementById('hdnSessionID').value;
            $.ajax({
                type: "POST",
                url: "../FinIQ_User_Controls/ShareSearch/WebMethod.aspx/GetFieldNameSearch",
                cache: false,
                data: "{'strSearch':'" + request.term + "', 'Mode':'" + Mode + "', 'TargetField':'" + TargetField + "','SessionID':'" + SessionID + "', maxResults: 3 }",
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                crossDomain: true,
                async: true,
                complete: function (XMLHttpRequest, textStatus, errorThrown) {
                },
                success: function (data) {
                    //alert(data);
                    objData = jQuery.parseJSON(data.d);
                    $('.tbl_cust1').hide();
                    //  response($.map(objData, function (item) {
                    var objData = jQuery.parseJSON(data.d);
                    var tbl = "<div style='overflow-y:auto;overflow-x: hidden; height:auto;max-height:300px;background-color:#FFFFFF;' class='Grid sharePopup'>"
                    tbl += "<table id='mstrTable' class='TableCustomerSearchResult_new' cellpadding=1 cellspacing=1 style='border-collapse:collapse;' >"
                    //tbl += '<th><div style="width:90%; float:left; padding:3px;">Code</div></th>'
                    tbl += '<tr><th><div style="width:80%; min-width:135px; float:left; padding:3px;">Code</div><div style="width:5%;  float:right; padding:3px;" onClick=\"' + "SelectFieldDetails_Ucp_CC(this,'" + 'Close' + "','" + '' + "','" + '' + "','" + '' + "','" + '' + "')" + '\">X</div></th>'
                    tbl += "</tr>";
                    if (objData != null) {
                        if (objData.length === 0) {
                            $(txtID).closest('.ui-widget').find('#hdnCounterPartyCode').val("");
                            $('#<%=tbl_cust1.ClientID%>').html("");
                            $('#<%=tbl_cust1.ClientID%>').hide();
                            $('.tbl_cust1').hide();
                            tbl += "<tr class='SearchResultRow1'>";
                            tbl += '<td contentEditable="false">No details found for selected Field.</td>';
                            tbl += '</tr>';
                            tbl += '</table></div>';
                            tblCust1 = $(autocompleteInput).parent().find(".tbl_cust1").attr('Code');
                            $("#" + tblCust1).html(tbl);
                            $("#" + tblCust1).show();
                            $("#" + tblCust1).css("display", "block");
                            return;
                        }

                        else {

                            console.log("start " + $.now());
                            for (var i = 0; i < objData.length; i++) {
                                tbl += "<tr class='SearchResultRow1' onClick=\"SelectFieldDetails_Ucp_CC(this,'" + objData[i].Code.replace(/&/g, "&amp;").replace(/>/g, "&gt;").replace(/</g, "&lt;").replace(/"/g, "&quot;") + "')\">"; //AkshayD , PSM to handle special characters 12-Apr-2021
                                //tbl += '<td contentEditable="true">' + objData[i].ID + '</td>';
                                tbl += '<td>' + objData[i].Code + '</td>';
                                tbl += '</tr>';
                                console.log(i + " || " + $.now());
                            }
                            tbl += '</table></div>';
                            console.log("append complete " + $.now());
                            tblCust1 = $(autocompleteInput).parent().find(".tbl_cust1").attr('id');
                            console.log($.now());
                            $("#" + tblCust1).html(tbl);
                            $("#" + tblCust1).show();
                            $("#" + tblCust1).css("display", "block");
                        }
                        // }))
                    }
                },

                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    try {
                        tbl += "<tr  class='SearchResultRow1_new SearchResultRow1_new'>";
                        tbl += '<td contentEditable="false">No details found for selected Field.</td>';
                        tbl += '</tr>';
                        tbl += '</table></div>';
                        $(txtID).closest('.ui-widget').find('#hdnCounterPartyCode').val("");
                        tblCust1 = $(autocompleteInput).parent().find(".tbl_cust1").attr('id');

                        $("#" + tblCust1).html(tbl);
                        $("#" + tblCust1).show();
                        $("#" + tblCust1).css("display", "block");

                    } catch (e) {

                    }
                }
            });
        }
    });
}

function SelectFieldDetails_Ucp_CC(selRow, strCode) {

    if (strCode == 'Close') {
        $(selRow).closest('.tbl_cust1').hide();
    } else {
        $(selRow).closest('.ui-widget').find('.textboxAuto').val(strCode);
        $(selRow).closest('.ui-widget').find('#hdnCounterPartyCode').val(strCode);
        //$(selRow).closest('.ui-widget').find('#hdnCounterPartyName').val(strLongName);
        //$(selRow).closest('.ui-widget').find('#hdnClientCode').val(strExchangeCode);
        //$(selRow).closest('.ui-widget').find('#hdnClientName').val(strExchangeName);
        // $(selRow).closest('.ui-widget').find('#hdnCcy').val(strCcy);
        $(selRow).closest('.tbl_cust1').hide();
        //alert(strCode);
        $(selRow).focus();
        $(autocompleteInput).focus();
        //document.getElementById('<%=btnSelect.ClientID()%>').click(); 
        document.getElementById('btnSelect').click();
    }
}


//End------------------------------------------------------------------------------------------------------------------------
function onlyNumberDecimalIncludingNegative(evt, cntrl) {
    var charCode;
    if (event.shiftKey && event.keyCode == 45) { return false; }

    try {
        var cntrlval;
        cntrlval = document.getElementById(cntrl.id).value;
        charCode = (evt.which) ? evt.which : evt.keyCode;
        if (charCode == 8 || charCode == 9 || charCode == 37 || charCode == 38 || charCode == 39 || charCode == 40 || charCode == 46) {
            return true;
        }
        if (((charCode > 47 || charCode < 58) && event.shiftKey) || charCode == 107) { return false; }
        if (charCode == 46) {
            if (cntrlval.indexOf(".") == -1)
                return isNumricWithDecMinus(charCode);
            return false
        }
        else if (charCode == 45) {
            if (cntrlval.indexOf("-") == -1)
                return isNumricWithDecMinus(charCode);
            return false
        }
        else {
            if (charCode == 190 || charCode == 110 || charCode == 109 || charCode == 189 || charCode == 46 || charCode == 45) {
                return true;
            }
            return isNumricWithDecMinus(charCode);
        }

    }
    catch (error) {

    }
    finally {
        charCode = null;
    }
}

/*************************************************************************************************************************************************/
// added by namita on 17-May-2018 as told by Nitin N and ARshad K.


//<Change done by Nitin N/Mayuri C on 16-Feb-2021 : MASINT-1394 Changes in Customer Profile, Customer Account and RM Setup>>
var ProAutoCompletectrl, ProSearchctrl, Pro_namectr, Pro_bcfx_idctrl, Pro_tlt_idctrl, Pro_rm_idctrl, Pro_allocation_codectrl, Pro_typectrl, Pro_Doc_IDctrl, BtnProselectctrl, DdlProSearchctrl, urlToRest1;
function autocomplete_custprofilechanged(event, custAutoCompletectrl, table, LoginIDCust, EntityIDCust, check, ParentCompany, custSearchctrl, cust_namectr, cust_bcfx_idctrl, cust_tlt_idctrl, cust_rm_idctrl, cust_allocation_codectrl, cust_typectrl, cust_Doc_IDctrl, btnCustselectctrl, ddlCustSearchctrl, Cust_AHId, Cust_EitherToSign) {
    try {

        //if (IsKeyUpOrDownPressed == true) {
        //    return;

        //}

        e = event || window.event;
        event = event || window.event;

        ProAutoCompletectrl = custAutoCompletectrl;
        tableControl = table;
        ProSearchctrl = custSearchctrl;
        Pro_namectr = cust_namectr;
        Pro_bcfx_idctrl = cust_bcfx_idctrl;
        Pro_tlt_idctrl = cust_tlt_idctrl;
        Pro_rm_idctrl = cust_rm_idctrl;
        Pro_allocation_codectrl = cust_allocation_codectrl;
        Pro_typectrl = cust_typectrl;
        Pro_Doc_IDctrl = cust_Doc_IDctrl;
        BtnProselectctrl = btnCustselectctrl;
        DdlProSearchctrl = ddlCustSearchctrl.id;

        urlToRest = $("#" + DdlProSearchctrl + " option:selected").text();// $("#" + DdlCustSearchctrl.id).val().trim();
        // alert(urlToRest);
        if (urlToRest == null) {
            urlToRest = "Name";
        }
        var keyCode = event.which;
        var txt = $("#" + ProAutoCompletectrl.id).val().trim();
        var term = "";
        var CheckValue = "";
        var ParentID = "";
        var LoginIDCustomer = "";
        var AHId = false;
        var EitherToSign = false;
        var EntityIDCustomer = "";

        term = txt
        e = e || window.event;

        if (e.keyCode == 13) {
            $('form input, body').on("keypress", function (e) {
                if (e.keyCode == 13) {
                    e.stopPropagation ? e.stopPropagation() : (e.cancelBubble = true);
                    e.returnvalue = null;
                    return false;
                }
            });
            return false;
        }



        if (term == "") {
            $(tableControl).html("");
            $(tableControl).hide();

            // autocomplete_customerclicked('', '0', '', '', '', '', '', '')

            autocomplete_clicked2('', '', '', '', '', '', '', '')

            return;
        }

        if (e.keyCode == 38 || e.keyCode == 40 || e.keyCode == 27 || e.keyCode == 9 || e.keyCode == 16 && e.keyCode == 9) {
            return;
        }
        else if (term.length >= 3) {

            var path_Name = window.location.pathname;
            var myPageName = path_Name.substring(path_Name.lastIndexOf('/') + 1);
            CheckValue = $("#" + check.id).val().trim();
            ParentID = $("#" + ParentCompany.id).val().trim();
            LoginIDCustomer = $("#" + LoginIDCust.id).val().trim();
            EntityIDCustomer = $("#" + EntityIDCust.id).val().trim();

            AHId = $("#" + Cust_AHId.id).val();

            EitherToSign = $("#" + Cust_EitherToSign.id).val();
            //alert(EntityIDCust.id.val());
            if (CheckValue == '') {
                CheckValue = "NO";
            }
            //EntityIDCustomer = "1002";
            //alert(EntityIDCustomer);
            //alert(term);
            //alert(urlToRest);
            // //
            $.support.cors = true;
            $.ajax({
                type: "POST",
                //url: "" + location.protocol + "//finiq218/finiqservice/SearchEngine.svc/CustomerProfileSearch?QueryString=" + term + "&Mode=" + urlToRest + "&EntityID=" + EntityIDCustomer,
                url: "" + myPageName + "/FindCustomerProfile",
                contentType: "application/json; charset=utf-8",
                dataType: "text",
                cache: false,
                data: "{'term':'" + term + "', 'Mode':'" + urlToRest + "'}",
                crossDomain: true,

                success: function (data) {

                    var obj = jQuery.parseJSON(data);
                    //var tbl = "<div style='overflow-y:scroll; border:1px;background-color:#0AC2FF'>";

                    var tbl = "<div style='overflow-y:auto;height:auto;max-height:300px;background-color:#FFFFFF;' class='Grid'>"

                    tbl += "<table id='searchedcusttable' style='cursor:default; background-color:white; border:1px solid #DDDDDD !important;' class='TableSearchResult' >";
                    tbl += "<tr >"

                    if (AHId.toUpperCase() == "TRUE") {
                        tbl += "<th style='border:1px solid #DDDDDD !important;'>AH Id</th>";
                    }

                    tbl += "<th style='border:1px solid #DDDDDD !important;'>Name</th><th style='border:1px solid #DDDDDD !important;'>Doc Type</th>";
                    tbl += "<th style='border:1px solid #DDDDDD !important;'>Doc Id</th>";
                    tbl += "<th style='border:1px solid #DDDDDD !important;'>Type</th>";
                    tbl += "<th style='border:1px solid #DDDDDD !important;'>CIF Number</th>";

                    if (EitherToSign.toUpperCase() == "TRUE") {
                        tbl += "<th style='border:1px solid #DDDDDD !important;'>Either To Sign</th>";
                    }

                    tbl += "<th style='border:1px solid #DDDDDD !important;'>CIN</th></tr>";

                    var objData;
                    $.each(obj, function (key, value) {
                        var jsonData = JSON.stringify(value);
                        objData = $.parseJSON(jsonData);
                    })
                    // alert(objData.AH_Id);
                    for (var i = 0; i < objData.length; i++) {
                        tbl += "<tr id='" + i + "' class='SearchResultRow' onClick=\"autocomplete_clicked2('" + objData[i].AH_Id + "','" + objData[i].Name + "','" + objData[i].Doc_Type + "','" + objData[i].Doc_Id + "','" + objData[i].Type + "','" + objData[i].CIF_No + "','" + objData[i].Either_To_Sign + "','" + objData[i].CIN + "')\">"
                        if (AHId.toUpperCase() == "TRUE") {

                            tbl += "<td style='border:1px solid #DDDDDD !important;'>" + objData[i].AH_Id + "</td>";
                        }
                        tbl += "<td style='border:1px solid #DDDDDD !important;'>" + objData[i].Name + "</td>";
                        tbl += "<td style='border:1px solid #DDDDDD !important;'>" + objData[i].Doc_Type + "</td>";
                        tbl += "<td style='border:1px solid #DDDDDD !important;'>" + objData[i].Doc_Id + "</td>";
                        tbl += "<td style='border:1px solid #DDDDDD !important;'>" + objData[i].Type + "</td>";
                        tbl += "<td style='border:1px solid #DDDDDD !important;'>" + objData[i].CIF_No + "</td>";

                        if (EitherToSign.toUpperCase() == "TRUE") {

                            tbl += "<td style='border:1px solid #DDDDDD !important;'>" + objData[i].Either_To_Sign + "</td>";
                        }

                        tbl += "<td style='border:1px solid #DDDDDD !important;'>" + objData[i].CIN + "</td>";
                        tbl += "</tr>";

                    }
                    tbl += "</table></div>";


                    $(tableControl).html(tbl);
                    $(tableControl).show();

                    var tbody = $(".TableSearchResult").find("tbody");
                    var selected = tbody.find("tr:nth-child(2)").addClass("selected");


                }


            });
        }
    }
    catch (error) {

    }
    finally {
        return;
    }
}

//</Change done by Nitin N/Mayuri C on 16-Feb-2021 : MASINT-1394 Changes in Customer Profile, Customer Account and RM Setup>>

function isNumricWithDecMinus(charCode) {
    try {
        if ((charCode != 46 && charCode != 45) && charCode > 31
            && (charCode < 48 || charCode > 57) && (charCode < 96 || charCode > 105)) { //Changed by PranavT on 6/12/18 for handling numpad numeric inputs
            return false;
        } else {
            return true;
        }
    }
    catch (error) {
    }
    finally {
        charCode = null;
    }
}

var arrColIndex = [];
var SortColIndex = [];
function ClearFilters(cFilters, clrFor) {
    try {
        thatTH = $(cFilters).parent().parent('td, th');
        var sTableID = $(thatTH).closest('Table').attr('id');
        var iTHindex = $(".Grid th, .GridHeader td,.GridHeader th, .gridCol th").index(thatTH);



        if (clrFor == '1') {
            $(thatTH).find('input[type="text"]').val('');

            localStorage.removeItem('SortColIndex');
            localStorage.removeItem('arrColIndex');
            if (arrColIndex.length > 0) {
                arrColIndex = jQuery.grep(arrColIndex, function (n, i) {
                    return (n.colIndex !== iTHindex);
                });
            }

            if (SortColIndex.length > 0) {
                SortColIndex = jQuery.grep(SortColIndex, function (n, i) {
                    return (n.colIndex !== iTHindex);
                });
            }

            localStorage.setItem('SortColIndex', JSON.stringify(SortColIndex));
            localStorage.setItem('arrColIndex', JSON.stringify(arrColIndex));

            SetFilterIcon(thatTH);
        }
        else {
            arrColIndex = [];
            SortColIndex = [];
            localStorage.removeItem('arrColIndex');
            localStorage.removeItem('SortColIndex');
            $(".Grid th, .GridHeader td,.GridHeader th, .gridCol th").find('input[type="text"]').val('');
        }

        if (arrColIndex.length > 0) {
            localStorage.setItem('arrColIndex', JSON.stringify(arrColIndex));
            SearchTable(sTableID, arrColIndex[0].colIndex, arrColIndex[0].searchString);
        }
        else {
            arrColIndex = [];
            SearchTable(sTableID, "", "");
        }

    } catch (er) { console.log(er.message); }
}



function clickOnSort(sortIcon, sortOrder) {
    try {
        that = $(sortIcon).parent().parent('td, th');
        var sTableID = $(that).closest('Table').attr('id');
        var iTHindex = $(".Grid th, .GridHeader td,.GridHeader th, .gridCol th").index(that);
        SortColIndex = [];
        SortColIndex.push({ "colIndex": iTHindex, "sortString": JSON.stringify(sortOrder) });
        sortTable(sTableID, iTHindex, sortOrder);
        SetFilterIcon(that);
    } catch (er) { console.log(er.message); }
}


function getToken() {
    try {
        var queryToken = window.location.search.split("&");;// '<%=Request.QueryString("csrfToken")%>';
        $(queryToken).each(function (i, j) {
            if (j.split("=")[0] == "csrfToken") {
                qtok = j.split("=")[1];

                if (localStorage.getItem("queryToken") != null) {
                    if (localStorage.getItem("queryToken") != qtok) {
                        window.localStorage.removeItem('queryToken');
                        window.localStorage.removeItem('SortColIndex');
                        window.localStorage.removeItem('arrColIndex');
                    }
                }
                localStorage.setItem("queryToken", qtok);
            }
        });
    } catch (er) { console.log(er.message); }
}

// sample sorting code
function SetSorting_Filter() {
    try {

        getToken();
        arrColIndex = [];
        $('.filter_1, .filter_0').click(function (event) {
            $(".dropdown-filter-content").each(function () { $(this).hide(); });

        });


        $(document).ready(function () {
            console.log("ready");

            HideDialogBox();

            arrColIndex = [];


            $("#ctl00_MainContent_workflowControl_queue_data_grid").find(".Grid th, .GridHeader td, .GridHeader th, .gridCol th").click(function () {

                //$("#ctl00_MainContent_workflowControl_queue_data_grid t").find(".filter_1").click(function () {

                SortFilter_DialogBox(this);
                SetFilterIcon(this)
            });

            if (localStorage.getItem("arrColIndex") != null && localStorage.getItem("arrColIndex") != "") {
                arrColIndex = JSON.parse(localStorage.getItem("arrColIndex"));
            }

            if (localStorage.getItem("SortColIndex") != null && localStorage.getItem("SortColIndex") != "") {
                SortColIndex = JSON.parse(localStorage.getItem("SortColIndex"));
            }


            $("#ctl00_MainContent_workflowControl_queue_data_grid").find(".Grid th, .GridHeader td, .GridHeader th, .gridCol th").each(function (THindex, thisTH) {
                var sTableID;
                var iTHindex;
                var SortColIndex;
                if ($(this).find('input[type="checkbox"]').length == 0) {
                    $(this).removeClass("filter_0").addClass("filter_1");
                    $(this).parent().parent().parent().removeAttr("style"); //removed grid width
                    $(this).append('<div class="dropdown-filter-content" style="display: none;"><div class="dropdown-filter-sort" onclick="clickOnSort(this,\'1\');"><span class="a-to-z asc" data-column="1"> Ascending Order</span></div> <div class="dropdown-filter-sort" onclick="clickOnSort(this,\'-1\');"><span class="z-to-a desc" data-column="1"> Descending Order</span></div><div class="dropdown-filter-search"><input type="text" class="txtTHFilter"  value="" /></div><div class="ClearFilters lblError"  onclick="ClearFilters(this,\'1\');">Clear this filter</div><div class="ClearFilters lblError"  onclick="ClearFilters(this,\'All\');">Clear all filter</div></div>')

                    if (SortColIndex != null) {
                        if (SortColIndex.split(":")[0] == THindex) {
                            $(this).removeClass("filter_1").addClass("filter_0");
                            sortTable("ctl00_MainContent_workflowControl_queue_data_grid", THindex, SortColIndex.split(":")[1]);
                        }
                    }

                    if (arrColIndex.length > 0) {
                        searchString = "";
                        $(arrColIndex).each(function (iTemp, Obj) {
                            if (Obj.colIndex == THindex) {
                                searchString = JSON.parse(Obj.searchString);
                                $(thisTH).removeClass("filter_1").addClass("filter_0");
                                $(thisTH).find('input[type="text"]').val(searchString);
                            }
                        });
                    }
                }
                else {
                    $(this).removeClass("filter_1 filter_0");
                }
            });


            if (arrColIndex.length > 0) {
                SearchTable("ctl00_MainContent_workflowControl_queue_data_grid", arrColIndex[0].colIndex, arrColIndex[0].searchString);
            }

            $('th input[type="text"]').each(function () {
                $(this).on('keyup', function (event) {
                    event = event || window.event;
                    var code = (event.keyCode ? event.keyCode : event.which);
                    if ($('th input[type="text"]').is(event.target) && (code == 13 || code == 9)) {
                        event.preventDefault();
                        sTableID = $(this).parent().parent().parent().parent().parent().parent().attr('id');
                        iTHindex = $(this).parent().parent().parent().parent().find('td, th').index($(this).parent().parent().parent());

                        strFilter = $(this).val().toUpperCase();
                        SearchTable(sTableID, iTHindex, strFilter);
                        return false;
                    }
                });
            });

            $("#ctl00_MainContent_workflowControl_ddlWorkFlow").click(function () {
                ClearFilters();
            })

        });

        // RemovePagination();


    } catch (er) { console.log(er.message); }
}


function SetFilterIcon(GridTH) {

    iColumnIndex = $(".Grid th, .GridHeader td,.GridHeader th, .gridCol th").index($(GridTH));
    // $('.Grid th, .GridHeader td, .GridHeader th, .gridCol th').eq(iColumnIndex).removeClass("filter_1").addClass("filter_0");

    arrColIndex = [];
    SortColIndex = [];
    if (localStorage.getItem("arrColIndex") != null && localStorage.getItem("arrColIndex") != "") {
        arrColIndex = JSON.parse(localStorage.getItem("arrColIndex"));
    }

    if (localStorage.getItem("SortColIndex") != null && localStorage.getItem("SortColIndex") != "") {
        SortColIndex = JSON.parse(localStorage.getItem("SortColIndex"));
    }

    var returnFilterData = $.grep(arrColIndex, function (element, index) {
        return element.colIndex == iColumnIndex;
    });

    var returnSortData = $.grep(SortColIndex, function (element, index) {
        return element.colIndex == iColumnIndex;
    });

    if (returnFilterData.length > 0 || returnSortData.length > 0) {
        $(GridTH).removeClass("filter_1").addClass("filter_0");
    }
    else {
        $(GridTH).removeClass("filter_0").addClass("filter_1");
    }
}


function sortTable(sTableID, iColumnIndex, sortOrder) {
    try {
        console.log("sortTable");
        // RemovePagination();
        // $('.Grid th, .GridHeader td, .GridHeader th, .gridCol th').eq(iColumnIndex).removeClass("filter_1").addClass("filter_0");
        //  iColumnIndex = JSON.parse(iColumnIndex);
        sortOrder = JSON.parse(sortOrder);
        // $(this).removeClass("filter_1").addClass("filter_0");

        var arrData = $('#' + sTableID).find('.GridItem, .GridItemSelect').get();
        arrData.sort(function (a, b) {
            var val1 = $(a).children('td:not("table")').eq(iColumnIndex).text().toUpperCase();
            var val2 = $(b).children('td:not("table")').eq(iColumnIndex).text().toUpperCase();

            str1 = val1;
            str2 = val2;


            if (str1.indexOf(',') > -1) {
                str1 = str1.replace(/,/g, "");
            }
            if (str2.indexOf(',') > -1) {
                str2 = str2.replace(/,/g, "");
            }



            if ($.isNumeric(str1) == true && $.isNumeric(str2) == true) {

                str1 = parseFloat(str1);
                str2 = parseFloat(str2);

            }
            else if (str1.indexOf('-') > -1 && str2.indexOf('-') > -1) {
                str1 = isDateForSort(str1);
                str2 = isDateForSort(str2);
            }
            else {
                str1 = val1;
                str2 = val2;
            }
            val1 = str1;
            val2 = str2;
            if (sortOrder == "-1") {
                sortOrder = -1;
            }
            else {
                sortOrder = 1;
            }
            if ($.isNumeric(val1) && $.isNumeric(val2)) {
                return sortOrder == 1 ? val1 - val2 : val2 - val1;
            }

            else {
                return (val1 < val2) ? -sortOrder : (val1 > val2) ? sortOrder : 0;
            }
        });
        $.each(arrData, function (index, row) {
            $('#' + sTableID).find('tbody:first').append(row);
            if ((arrData.length - 1) == index) {
                $('#' + sTableID).find('tbody:first').append($('#' + sTableID).find('.GridPager').get());
            }

            if (iColumnIndex == index) {
                localStorage.removeItem('SortColIndex');
                localStorage.setItem('SortColIndex', JSON.stringify(SortColIndex));
            }
        });


        $('#' + sTableID).find(".Grid th, .GridHeader th, .GridHeader td, .gridCol th").each(function (iHRow, hRow) {
            if (iHRow == iColumnIndex) {
                $(hRow).removeClass("filter_1").addClass("filter_0");
                return false;
            }
        });
    }
    catch (er) { console.log(er.message); }
}


function SortFilter_DialogBox(GridTH) {
    try {

        e = event || window.event;
        if ($(GridTH).find('input[type="checkbox"]').length == 0) {
            $(GridTH).toggleClass("filter_1");




            if ($(GridTH).find(".dropdown-filter-content").css("display") == "none") {
                $(GridTH).find(".dropdown-filter-content").toggle();
            }

            if ($(GridTH).find(".dropdown-filter-content").find('input[type="text"]').val() != "" || ($(GridTH).find(".dropdown-filter-content").find('span').is(e.target))) {
                $(GridTH).removeClass("filter_1").addClass("filter_0");
            }
            if ($(GridTH).find(".dropdown-filter-content").css("display") == "block") {
                $(GridTH).removeClass("filter_1").addClass("filter_0");
            }
        }
    } catch (er) { console.log(er.message); }
}


function HideDialogBox() {
    try {
        $(document).on("click keyup", function (event) {
            var event = event || window.event;
            var popup = $(".dropdown-filter-content");
            if (!$('.Grid th, .GridHeader td, .gridCol th, .filter_1, .filter_0').is(event.target) && !popup.is(event.target) && popup.has(event.target).length == 0) {
                popup.hide(150);
                return true;
            }
            if (event.keyCode == 27) {
                popup.hide(150);
                return true;
            }
            else {

                $(event.target).find('input[type="text"]').focus();
            }
        });
    } catch (er) { console.log(er.message); }
}


function isDateForSort(sDate) {

    matches = sDate.match(/^((([0-9])|([0-2][0-9])|([3][0-1]))\-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\-\d{4})$/i) || str1.match(/^((([0-9])|([0-2][0-9])|([3][0-1]))\-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\-\d{4}) ([0]?[1-9]|1[0-2]):([0-5]\d):([0-5]\d)\s?(AM|PM)$/i);
    if (matches != null) {
        sDate = Date.parse(new Date(sDate.replace(/-/g, " ")));
    }
    return sDate;
}



function RemovePagination() {
    try {
        var j = 0;
        if (localStorage.getItem("rowIndex") != null && localStorage.getItem("rowIndex") != "") {
            j = localStorage.getItem("rowIndex");
        }

        if (localStorage.getItem("arrColIndex") != null && localStorage.getItem("arrColIndex") != "") {
            arrColIndex = JSON.parse(localStorage.getItem("arrColIndex"));
        }
        var i = $("#ctl00_MainContent_workflowControl_queue_data_grid").find(".GridPager").length;
        if (Number(j) < Number($("#ctl00_MainContent_workflowControl_TxRowsPerPage").val()) || j == undefined) {
            j = $("#ctl00_MainContent_workflowControl_TxRowsPerPage").val();
        }
        if (i > 0) {
            var GridPagerTD = $("#ctl00_MainContent_workflowControl_queue_data_grid").find(".GridPager table td").length;

            do {
                j = (j * GridPagerTD);
                $("#ctl00_MainContent_workflowControl_TxRowsPerPage").val(Number(j));
                localStorage.setItem("rowIndex", j);
                __doPostBack('<%# TxRowsPerPage.ClientID %>', 'OnTextChanged')
            }
            while (i == 0);
        }
        else {
            localStorage.removeItem("rowIndex");
        }
        SearchTable("ctl00_MainContent_workflowControl_queue_data_grid", "", "");

    } catch (er) { console.log(er.message); }
}

window.onload = function () {

    btnID = localStorage.getItem("lastBtn");
    if (btnID != null && btnID != undefined) {
        $("#" + btnID).prop("disabled", false);
        $("#" + btnID).removeAttr("disabled");
        localStorage.removeItem("lastBtn");
    }

}

// Modified by Anand K. 31-Aug-2021
function MsgDialog(obj, title, x, dialogText) {

    try {
        $('html').find('#dialog').remove(); //Added by ShekharL || 22-Nov-2021 || MASCLI-1923 
        var dialogText1 = '';
        var activeElement = sessionStorage.getItem('focusItem');
        if (dialogText1 != dialogText) {
            dialogText1 = dialogText;
            dialogConfirmed = false;
        }
        if (!dialogConfirmed) {
            if (x === 1) {
                if ($("#pageName").html() != null) {
                    title = "Information - " + $("#pageName").html();
                }

                $('html').append(String.Format("<div id='dialog' title='{0}'><table cellpadding='2' cellspacing='0'><tr><td style='padding:10px;'><img src='../App_Themes/images/imgSuccess.png' style='width:18px;height:18px;'></td><td><p style='float:left;color:#008000;'><span style='float:left;margin:0 0 20px 0;'></span>{1}</p></td> </tr></table></div>",
                    title, dialogText));

                var x = $('html');


            }
            else if (x === 0) {
                if ($("#pageName").html() != null) {
                    title = "Warning - " + $("#pageName").html();
                }

                $('html').append(String.Format("<div id='dialog' title='{0}'><table cellpadding='2' cellspacing='0'><tr><td style='padding:10px;'><img src='../App_Themes/images/Warning_Msg.png' style='width:18px;height:18px;'></td><td><p style='float:left;color:#0368b6;'><span style='float:left;margin:0 0 20px 0;'></span>{1}</p></td> </tr></table></div>",
                    title, dialogText));

            }
            $('#dialog').dialog
                ({
                    position: { my: 'top+150%', at: 'top', of: window }, //Added by Jassim AR/Shreyas V | 18-Jan-2020 | To align dialogue box in the center
                    height: 180,
                    width: 350,
                    modal: true,
                    resizable: false,
                    draggable: true,

                    close: function (event, ui) {
                        // $(document).find("#" + activeElement).focus();   ''MSACLI-894 Modify by Anand K / Prachi P. on 31-Aug-2021
                        $('html').find('#dialog').remove();
                    },
                    buttons:
                    {

                        'OK': function () {
                            $(this).dialog('close');
                        }
                    }
                });
        }

        // $('button:last').focus();  ''Modify by Anand K / Prachi P. on 31-Aug-2021


        return dialogConfirmed;

        $(".ui-widget-overlay").height($("body").height());

    }
    catch (error) {
        console.log("Error: " + error);
    }
}


//<Start ||  Added by Arshin S || on 22-Jan-2019 || asked by Deepa K>
function validateFloatDecimalPlaces(el, event, decimalPoint, Allownegative) {

    if (Allownegative == false) {
        if ((event.which != 46 || el.value.indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
            if ((event.which != 46 || el.value.indexOf('.') != -1)) {
                return false;
            }
        }

    }
    else {
        if ((event.which != 46 || el.value.indexOf('.') != -1) && (event.which < 48 || event.which > 57) && (event.which != 45 || el.value.indexOf('-') != -1)) {
            if ((event.which != 46 || el.value.indexOf('.') != -1)) {
                return false;
            }
            if ((event.which != 45 || el.value.indexOf('-') != -1)) {
                return false;
            }
        }

    }

    var t = el.value.substr(el.selectionStart, el.selectionEnd - el.selectionStart);
    if (t.length > 0) {
        return true;
    }

    if (el.selectionStart <= el.value.indexOf(".")) {
        return true;
    }
    if (el.value.indexOf(".") > -1 && (el.value.split('.')[1].length > decimalPoint - 1)) {
        return false;
    }
    return true;
}

//<End ||  Added by Arshin S || on 22-Jan-2019 || asked by Deepa K>

//[START]Dashrath K and Abhinav T on 04-Feb-2019
function DisallowSpecialCharacters(e) {
    var keycode;
    var event = e || event.window;
    var keyCode = event.which;

    if ((keycode > 34 && keycode < 38) || keycode == 33 || (keycode > 41 && keycode < 45) || keycode == 47 || keycode == 38
        || (keycode > 58 && keycode < 65) || (keycode > 90 && keycode < 95) || (keycode > 122 && keycode < 126)) {
        return false;
    }
    else {
        return true;
    }

}


function EnterEventIssuer(event, txtIssuer) {
    //
    event = event || event.window;
    var keyCode = event.which;
    Issuer = "#" + $(txtIssuer).attr('id');

    var txt = document.getElementById(txtIssuer.id).value;

    //  alert(txt);
    var term = "";
    term = txt
    //Sheetal K || to handle no postback on backspace || 15-May20
    if (term == "" && (keyCode == 8)) {
        $("#tbl_Issuer").html("");
        $("#tbl_Issuer").hide();
        autocomplete_Issuerclicked("", 0)
        //  $("#" + x).blur();
        return;
    }

    //Sheetal k || to handle up and down arrow key || 15May20
    if (keyCode == 38 || keyCode == 40 || keyCode == 27 || keyCode == 9 || keyCode == 16 && keyCode == 9) {
        return;
    }

    //Aditya B || 06-May-2020 || Start 
    //if (keyCode == 13) {
    //$("#dialog1").show();

    //if (keyCode >= 32)
    //    term = txt + String.fromCharCode(event.which);
    //else
    //    if (keyCode == 8)
    //        term = txt.substring(0, txt.length - 1);

    if (term == "") {
        $("#tbl_Issuer").html("");
        $("#tbl_Issuer").hide();
        //autocomplete_prodclicked("", 0)
        return;
    }


    $.support.cors = true;
    $.ajax({
        type: "POST",
        url: "../FinIQ_User_Controls/Smart_Search_Issuer_Control/web_IssuerSearch.aspx/FindIssuer",
        contentType: "application/json; charset=utf-8",
        dataType: "text",
        cache: false,
        crossDomain: true, //Modified Code            
        data: "{'strSearch':'" + term + "'}",
        //async: true,
        //cache: false,
        success: function (data) {
            //alert(data);
            var obj = jQuery.parseJSON(data);
            var tbl = "<div style='overflow-y:auto;height:auto;max-height:300px;background-color:#FFFFFF;Cursor:pointer' class='Grid'><table class='TableSearchResult' border=1 cellpadding=1 cellspacing=1 style='border-collapse:collapse;background-color:#FFFFFF'><tr><th>Issuer Name</th><th>Issuer Id</th></tr>";

            var objData;
            $.each(obj, function (key, value) {
                var jsonData = JSON.stringify(value);
                objData = $.parseJSON(jsonData);
            })

            if (objData.length === 0) {
                $("#tbl_Issuer").html("");
                $("#tbl_Issuer").hide();
                //alert("No details found for selected product");
                //autocomplete_Issuerclicked('', '', 0);
                return false;
            }
            else {
                for (var i = 0; i < objData.length; i++) {

                    // tbl += "<tr class='trHover' onClick=\"autocomplete_prodclicked(this,'" + objData[i].Issuer_Name + "','" + objData[i].Issuer_Id + "')\">"
                    tbl += "<tr class='trHover' onClick=\"autocomplete_Issuerclicked(this,'" + objData[i].Issuer_Name + "', '" + objData[i].Issuer_Id + "')\">"
                    tbl += "<td>" + objData[i].Issuer_Name + "</td>";
                    tbl += "<td>" + objData[i].Issuer_Id + "</td>";
                    tbl += "</tr>";
                }

                tbl += "</table></div>";
                $("#tbl_Issuer").html(tbl);
                $("#tbl_Issuer").show();
            }
            $("#dialog1").hide();

        },
        error: function (xhr, textStatus, error) {
            //called on ajax call error
            // alert();
            console.log("Error: " + error);
        }

    });
    //}
    //Aditya B || 06-May-2020 || End
}

function autocomplete_Issuerclicked(selRow, selIssuerName, selIssuerID) {

    $('#IssuerName').val(selIssuerName);
    $('#IssuerId').val(selIssuerID);

    $(selRow).parent().parent().parent().parent().parent().find('.txtIssuer').val(selIssuerName);
    $("#tbl_Issuer").hide();
    //Commented & Changed by Aditya B || 6-May-2020 || To prevent page postback issue after selecting issuer. Reported by Kaustubh T || Start
    // __doPostBack('issuer_name_ValueChanged', 'ValueChanged');
    var btnSelect = $(selRow).parent().parent().parent().parent().parent().find("#btnSelect");
    btnSelect.click();
    //Commented & Changed by Aditya B || 6-May-2020 || To prevent page postback issue after selecting issuer. Reported by Kaustubh T || End
}

//Added by Dashrath on 24-Apr-2018 for WLB bond
function MsgDialog_BondEntry(obj, title, x, dialogText) {

    try {

        if (!dialogConfirmed) {
            if (x === 1) {
                if ($("#pageName").html() != null) {
                    title = "Information - " + $("#pageName").html();
                }

                $('html').append(String.Format("<div id='dialog' title='{0}'><table cellpadding='2' cellspacing='0'><tr><td style='padding:10px;'><img src='../App_Themes/images/imgSuccess.png' style='width:18px;height:18px;'></td><td><p style='float:left;color:#008000;'><span style='float:left;margin:0 0 20px 0;'></span>{1}</p></td> </tr></table></div>",
                    title, dialogText));
            }
            else if (x === 0) {
                if ($("#pageName").html() != null) {
                    title = "Warning - " + $("#pageName").html();
                }

                $('html').append(String.Format("<div id='dialog' title='{0}'><table cellpadding='2' cellspacing='0'><tr><td style='padding:10px;'><img src='../App_Themes/images/Warning_Msg.png' style='width:18px;height:18px;'></td><td><p style='float:left;color:#0368b6;'><span style='float:left;margin:0 0 20px 0;'></span>{1}</p></td> </tr></table></div>",
                    title, dialogText));

            }
            $('#dialog').dialog
                ({
                    height: 180,
                    width: 350,
                    modal: true,
                    resizable: false,
                    draggable: true,
                    close: function (event, ui) { $('html').find('#dialog').remove(); },
                    buttons:
                    {

                        'OK': function () {
                            // $(this).dialog('close');
                            window.close();
                        }
                    }
                });
        }

        return dialogConfirmed;

        $(".ui-widget-overlay").height($("body").height());

    }
    catch (error) {
        console.log("Error: " + error);
    }
}
function ShareTyped(txtShare) {
    //
    var txt;

    var event = event || window.event;
    var keycode = event.keyCode || event.which;
    var char = String.fromCharCode(keycode);
    txt = document.getElementById('txtCurrentShare').value + char;
    document.getElementById('txtCurrentShare').value = txt;
    ShareCollectionSearch(document.getElementById('txtCurrentShare'), event);
}

function ShareCollectionSearch(txtShareSearch, event) {
    //
    $.support.cors = true;
    //   autocompleteInput = $(autocompleteInput).prop('id');
    txtID = "#" + $(txtShareSearch).attr('id');
    autocompleteInput = txtID;
    var strMarketype;

    strMarketype = $(txtID).closest('.ui-widget').find('#hdnMarketype1').val();
    $(txtID).parent().find(".tbl_cust").hide();
    event = event || window.event;
    keycode = event.keyCode || event.which;
    var CurrentShareArray;
    var CurrentShare;

    //
    if (event.keycode == 13) {
        //alert("arrowKeySelectionShareCollectionSearch");
        $(".selected").click();
        return;


    }

    if (keycode != 8) {


        //$(txtID).closest('.ui-widget').find('#hdnPrevText').val($(txtShareSearch).val());

        if ($(txtShareSearch).val().split($(txtID).closest('.ui-widget').find('#hdnPrevText').val()).length > 1) {

            if ($(txtID).closest('.ui-widget').find('#hdnPrevText').val() === "") {
                CurrentShare = $(txtShareSearch).val();
            }
            else {
                CurrentShareArray = $(txtShareSearch).val().split($(txtID).closest('.ui-widget').find('#hdnPrevText').val());
                CurrentShare = CurrentShareArray[CurrentShareArray.length - 1];

            }

        }

        else {
            CurrentShare = $(txtShareSearch).val();
        }
    }




    else {
        //$(txtShareSearch).val($(txtShareSearch).val().replace(",", "~"));
        if ($(txtShareSearch).val() !== "") {

            if ($(txtShareSearch).val().split(",").length >= 1) {
                CurrentShareArray = $(txtShareSearch).val().split(",");
                CurrentShareArray.pop();
                if ($(txtShareSearch).val().substring($(txtShareSearch).val().length - 1, $(txtShareSearch).val().length) == ',') {
                    CurrentShareArray.pop();
                }

                $(txtShareSearch).val(",");
                if (CurrentShareArray.length >= 1) {
                    $(txtShareSearch).val("");
                    for (var i = 0; i < CurrentShareArray.length; i++) {

                        $(txtShareSearch).val($(txtShareSearch).val() + CurrentShareArray[i] + ",");


                    }

                }

            }
            if ($(txtShareSearch).val() == ",") {
                $(txtShareSearch).val("");
            }
            $(txtID).closest('.ui-widget').find('#hdnPrevText').val($(txtShareSearch).val());

        }
        else {
            $(txtID).closest('.ui-widget').find('#hdnPrevText').val("");
        }
        //$('input[type = "text"]').change();
        $(txtID).closest('.ui-widget').find('#hdnShareCode1').val("");
        //  alert("ShareCollectionSearchMainFunction");
        $(txtID).parent().find(".btnSelect").click();
        //$('#ctl00_MainContent_oUCPCtrl_dgvCustCpty_ctl0' + UCPTargetField).change();
    }



    if (keycode != 9) {
        $(txtID).closest('.ui-widget').find('#hdnShareCode1').val("");
    }


    if ($(txtID).val().length < 3) {
        $(txtID).closest('.ui-widget').find('#hdnShareCode1').val("");
        $(txtID).parent().find(".tbl_cust").hide();
    }




    $(autocompleteInput).autocomplete({
        search: function (event, ui) {
            if (event.keyCode == 13 || event.keyCode == 38 || event.keyCode == 40 || event.keyCode == 27 || event.keyCode == 9 || event.keyCode == 16 && event.keyCode == 9) { event.preventDefault(); }
        },
        minLength: 1,
        autoFocus: true,
        focus: function (event, ui) {
            $(autocompleteInput).val(ui.item.label);
            return false;
        },
        source: function (request, response) {

            $.ajax({
                type: "POST",
                url: "../FinIQ_User_Controls/ShareSearch/WebMethod.aspx/GetSharesNames",
                cache: false,
                data: "{'strSearch':'" + CurrentShare + "', 'strMarketype':'" + strMarketype + "', maxResults: 3 }",
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                crossDomain: true,
                complete: function (XMLHttpRequest, textStatus, errorThrown) {
                    //alert(textStatus);
                },
                success: function (data) {
                    //objData = jQuery.parseJSON(data.d);
                    $('.tbl_cust').hide();
                    //response($.map(objData, function (item) {
                    objData = jQuery.parseJSON(data.d);
                    var tbl = "<div style='overflow-y:auto;height:auto;max-height:300px;background-color:#FFFFFF;' class='Grid sharePopup'>"
                    tbl += "<table id='mstrTable' class='TableCustomerSearchResult_shareCollection' cellpadding=1 cellspacing=1 style='border-collapse:collapse;' >"
                    tbl += '<tr><th><div style="width:90%; float:left; padding:3px;">Code</div></th>'
                    //  tbl += '<th><div style="width:80%; float:left; padding:3px;">Share Name</div><div style="width:10%; float:right; padding:3px;" onClick=\"' + "SelectShareDetails(this,'" + 'Close' + "','" + '' + "','" + '' + "','" + '' + "','" + '' + "')" + '\">X</div></th>';
                    tbl += '<th><div style="width:80%; float:left; padding:3px;">Share Name</div><div style="width:10%; float:right; padding:3px;" onClick=\"' + "SelectShareCollectionDetails(this,'" + 'Close' + "')" + '\">X</div></th>';
                    tbl += "</tr>";
                    if (objData != null) {
                        if (objData.length === 0) {
                            $(txtID).parent().find(".tbl_cust").html('');

                            $(txtID).parent().find(".tbl_cust").hide();
                            // alert("No details found.");
                            $(txtID).parent().find("#hdnShareCode1").val('');
                            $(txtID).blur(function () {
                                if ($(txtID).closest('.ui-widget').find('#hdnShareCode1').val() == "") {
                                    $(this).val('');
                                    // $(txtID).parent().find(".btnSelect").click();
                                }
                            });
                            return;
                        }
                        else {


                            for (var i = 0; i < objData.length; i++) {
                                //    tbl += "<tr class='SearchResultRow' onClick=\"SelectShareDetails(this,'" + objData[i].Code + "','" + objData[i].LongName + "','" + objData[i].ExchangeCode + "','" + objData[i].ExchangeName + "','" + objData[i].Ccy + "')\">";
                                // tbl += "<tr class='SearchResultRow' onClick=\"SelectShareDetails(this,'" + objData[i].Code + "',' + objData[i].LongName + ','" + objData[i].ExchangeCode + "','" + objData[i].ExchangeName + "','" + objData[i].Ccy + "')\">";
                                tbl += "<tr class='SearchResultRow' onClick=\"SelectShareCollectionDetails(this,'" + i + "')\">";
                                tbl += '<td contentEditable="false">' + objData[i].Code + '</td>';
                                tbl += '<td>' + objData[i].LongName + '</td>';
                                tbl += '</tr>';
                            }
                            tbl += '</table></div>';
                            tblCust = $(autocompleteInput).parent().find(".tbl_cust").attr('id');
                            $("#" + tblCust).html(tbl);
                            $("#" + tblCust).show();
                            var tbody = $(".TableCustomerSearchResult_shareCollection").find("tbody");
                            var selected = tbody.find("tr:nth-child(2)").addClass("selected");

                            $(txtID).parent().find(".tbl_cust").css("display", "block");
                            $(txtID).blur(function () {

                                if ($(txtID).closest('.ui-widget').find('#hdnShareCode1').val() == "") {
                                    if ($(this).val() == objData[0].Code) {
                                        $(txtID).closest('.ui-widget').find('#hdnShareCode1').val(objData[0].Code)

                                        // alert("ShareCollectionSearch");
                                        $(txtID).parent().find(".btnSelect").click();
                                    }
                                }
                            });
                        }
                    }
                    // }))
                },

                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    $(txtID).parent().find(".tbl_cust").hide();
                    $(txtID).blur(function () {

                        if ($(txtID).closest('.ui-widget').find('#hdnShareCode1').val() == "") {
                            $(this).val('');
                        }
                    });
                },
                select: function (event, ui) {
                    if (ui.item) {
                        $('#hdnShareCode1').val(ui.item.Code);
                        $('#hdnShareLongName1').val(ui.item.LongName);
                    }
                }

            });


        }
    });

}


function SelectShareCollectionDetails(selRow, iRow) {
    //  //
    strCode = objData[iRow].Code;
    strLongName = objData[iRow].LongName;
    strExchangeCode = objData[iRow].ExchangeCode;
    strExchangeName = objData[iRow].ExchangeName;
    strCcy = objData[iRow].Ccy;
    if (strCode == 'Close') {
        $(selRow).closest('.tbl_cust').hide();
    } else {
        if ($(selRow).closest('.tbl_cust')[0].style.display === "block") {
            $(selRow).closest('.ui-widget').find('.textboxAuto').val(strCode);
            $(selRow).closest('.ui-widget').find('#hdnShareCode1').val(strCode);
            $(selRow).closest('.ui-widget').find('#hdnShareLongName1').val(strLongName);
            $(selRow).closest('.ui-widget').find('#hdnExchangeCode1').val(strExchangeCode);
            $(selRow).closest('.ui-widget').find('#hdnExchangeName1').val(strExchangeName);
            $(selRow).closest('.ui-widget').find('#hdnCcy').val(strCcy);
            $(selRow).closest('.tbl_cust').hide();
            $(autocompleteInput).focus();
            $(selRow).closest('.ui-widget').find('#btnSelect').click();
            //document.getElementById('btnSelect').click();
        }
    }


}

isShift = false;
seperator = "/";
dateString = "";
function dateSeperator(txtDate, event) {
    try {

        //Set Max Length.
        event = event || window.event;
        key = event.which || event.keyCode;
        if (key == 9) {
            if (this.value != '') {
                // 
                $("#" + this.id).change;
                // __doPostBack(this.id, '');
            }
        }
        txtDate.setAttribute("maxlength", 11);

        //Only allow Numeric Keys.
        //  
        txtDate.onkeydown = function (e) {
            return IsNumeric_DP(this, e.keyCode);
        };
        //Validate Date as User types.
        txtDate.onkeyup = function (e) {
            ValidateDateFormat(this, e.keyCode);
        };





    } catch (er) { }
}



function IsNumeric_DP(cntrol, keyCode) {
    if (keyCode == 16) {
        isShift = true;
    }
    //Allow only Numeric Keys.
    if (((keyCode >= 48 && keyCode <= 57) || keyCode == 8 || keyCode <= 37 || keyCode <= 39 || (keyCode >= 96 && keyCode <= 105)) && isShift == false) {
        if (cntrol.value.length == 2 && keyCode != 8) {

            if (cntrol.value > 31) {
                return false;
            }
        }
        if (cntrol.value.length == 5 && keyCode != 8) {
            var month = cntrol.value.slice(-2);
            if (month > 12) {
                return false;
            }
        }
        if ((cntrol.value.length == 2 || cntrol.value.length == 5) && keyCode != 8) {
            cntrol.value += seperator;
        }

        return true;
    }
    else {

        return false;
    }
};
function ValidateDateFormat(input, keyCode) {
    dateString = input.value;
    if (keyCode == 16) {
        isShift = false;
    }
    var regex = /(((0|1)[0-9]|2[0-9]|3[0-1])\/(0[1-9]|1[0-2])\/((19|20)\d\d))$/;
    var regex1 = /(((0|1)[0-9]|2[0-9]|3[0-1])\/(0[1-9]|1[0-2])\/((([0-9])\d)))$/;
    //Check whether valid dd/MM/yyyy Date Format.
    if (regex.test(dateString) || regex1.test(dateString) || dateString.length == 0) {
        ShowHideError(input, "none");
    } else {
        ShowHideError(input, "block");
    }
};

function ShowHideError(textbox, display) {
    var row = textbox.parentNode.parentNode;
    var errorMsg = row.getElementsByTagName("span")[0];
    if (errorMsg != null) {
        errorMsg.style.display = display;
    }


};
function ddmmyyyy() {
    var month_n = dateString.slice(3, 5);
    var months = ["", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
    month = parseInt(month_n);
    var date_n = dateString.slice(0, 2);
    var year_n = dateString.slice(6, 11);

    if (year_n.length == 2) {
        var abc = "20";
        var year_n = abc.concat(year_n[0], year_n[1]);
        document.write(date_n + "-" + months[month] + "-" + year_n);
    }

    else if (year_n.length == 4) {
        document.write(date_n + "-" + months[month] + "-" + year_n);
    }

}



function Product_Search(txtShareSearch) {
    $.support.cors = true;
    //   autocompleteInput = $(autocompleteInput).prop('id');
    var txtID = "#" + $(txtShareSearch).attr('id');
    autocompleteInput = txtID;

    //var strMarketype;
    //strMarketype = $(txtID).closest('.ui-widget').find('#hdnMarketype').val();
    $(txtID).parent().find(".tbl_cust").hide();

    var e = event || window.event;
    var keyCode = e.keyCode || e.which;

    if (keyCode != 9) {
        $(txtID).closest('.ui-widget').find('#hdnProductID').val("");
    }


    if ($(txtID).val().length < 3) {
        $(txtID).closest('.ui-widget').find('#hdnProductID').val("");
        $(txtID).parent().find(".tbl_cust").hide();
    }
    $(autocompleteInput).autocomplete({
        minLength: 3,
        autoFocus: true,
        focus: function (event, ui) {
            $(autocompleteInput).val(ui.item.label);
            return false;
        },
        source: function (request, response) {

            $.ajax({
                type: "POST",
                url: "../FinIQ_User_Controls/ProductSearch/WebMethodProduct.aspx/GetProductNames",
                cache: false,
                data: "{'strSearch':'" + request.term + "', 'strMarketype':'" + ' ' + "', maxResults: 3 }",
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                crossDomain: true,
                complete: function (XMLHttpRequest, textStatus, errorThrown) {

                },
                success: function (data) {

                    objData = jQuery.parseJSON(data.d);


                    $('.tbl_cust').hide();
                    //response($.map(objData, function (item) {
                    var objData = jQuery.parseJSON(data.d);
                    var tbl = "<div style='overflow-y:auto;height:auto;max-height:300px;background-color:#FFFFFF;' class='Grid sharePopup'>"
                    tbl += "<table id='mstrTable' class='TableShareSearchResult' cellpadding=1 cellspacing=1 style='border-collapse:collapse;' >"
                    tbl += '<tr><th><div style="width:90%; float:left; padding:3px;">Rider ID</div></th>'
                    // tbl += '<th><div style="width:80%; float:left; padding:3px;">Rider Name</div><div style="width:10%; float:right; padding:3px;" onClick=\"' + "SelectProductDetails(this,'" + 'Close' + "','" + '' + "','" + '' + "','" + '' + "','" + '' + "','" + txtID + "')" + '\">X</div></th>'
                    tbl += '<th><div style="width:80%; float:left; padding:3px;">Rider Name</div>'
                    tbl += '<th><div style="width:80%; float:left; padding:3px;">Rider Type</div>'
                    tbl += '<th><div style="width:80%; float:left; padding:3px;">Rider Code</div>'
                    tbl += ' <div style="width:10%; float:right; padding:3px;" onClick=\"' + "SelectProductDetails(this,'" + 'Close' + "','" + '' + "','" + '' + "','" + '' + "','" + '' + "','" + txtID + "')" + '\">X</div></th>'
                    tbl += "</tr>";
                    if (objData.length === 0) {
                        $(txtID).parent().find(".tbl_cust").html('');

                        $(txtID).parent().find(".tbl_cust").hide();
                        // alert("No details found.");
                        $(txtID).parent().find("#hdnProductID").val('');
                        $(txtID).blur(function () {
                            if ($(txtID).closest('.ui-widget').find('#hdnProductID').val() == "") {
                                $(this).val('');
                                // $(txtID).parent().find(".btnSelect").click();
                            }
                        });
                        return;
                    }
                    else {
                        // alert('here');
                        for (var i = 0; i < objData.length; i++) {

                            // alert(objData[i].RiderID);
                            tbl += "<tr class='SearchResultRow' onClick=\"SelectProductDetails(this,'" + objData[i].NoteMasterId + "','" + objData[i].ProductName + "','" + objData[i].Asset + "','" + objData[i].RiderCode + "','" + objData[i].RiderType + "','" + objData[i].RiderID + "','" + objData[i].RiderName + "','" + txtID + "')\">";
                            tbl += '<td contentEditable="false">' + objData[i].NoteMasterId + '</td>';
                            tbl += '<td>' + objData[i].RiderName + '</td>';
                            tbl += '<td>' + objData[i].RiderType + '</td>';
                            tbl += '<td>' + objData[i].RiderCode + '</td>';
                            tbl += '</tr>';
                        }
                        tbl += '</table></div>';
                        tblCust1 = $(autocompleteInput).parent().find(".tbl_cust").attr('id');
                        $("#" + tblCust1).html(tbl);

                        $("#" + tblCust1).css("display", "block");
                        $(txtID).blur(function () {

                            if ($(txtID).closest('.ui-widget').find('#hdnProductID').val() == "") {
                                if ($(this).val() == objData[0].Code) {
                                    $(txtID).closest('.ui-widget').find('#hdnProductID').val(objData[0].Code)
                                    $(txtID).parent().find(".btnSelect").click();
                                }
                            }
                        });
                    }
                    // }))
                },

                error: function (XMLHttpRequest, textStatus, errorThrown) {


                    $(txtID).parent().find(".tbl_cust").hide();
                    $(txtID).blur(function () {

                        if ($(txtID).closest('.ui-widget').find('#hdnProductID').val() == "") {
                            $(this).val('');
                        }
                    });
                },
                select: function (event, ui) {
                    if (ui.item) {
                        $('#hdnProductID').val(ui.item.Code);
                        $('#hdnProductLongName').val(ui.item.LongName);
                    }
                }

            });


        }
    });

}


function SelectProductDetails(selRow, strCode, strLongName, strExchangeCode, strExchangeName, strCcy, strriderID, strRiderName, txtID) {
    WriteLog("SelectProductDetails");
    try {
        if (strCode == 'Close') {
            $(selRow).closest('.tbl_cust').hide();
        } else {
            $(selRow).closest('.ui-widget').find('.textboxAuto').val(strRiderName);

            $(selRow).closest('.ui-widget').find('#hdnProductID').val(strCode);

            //alert(strExchangeName);
            $(selRow).closest('.ui-widget').find('#hdnProductLongName').val(strLongName);
            $(selRow).closest('.ui-widget').find('#hdnUCPRiderCode').val(strExchangeName);
            $(selRow).closest('.ui-widget').find('#hdnUCPRiderType').val(strCcy);

            $(selRow).closest('.ui-widget').find('#hdnUCPRiderID').val(strriderID);
            $(selRow).closest('.ui-widget').find('#hdnUCPRiderName').val(strRiderName);

            //$(selRow).closest('.ui-widget').find('#hdnExchangeCode').val(strExchangeCode);
            //$(selRow).closest('.ui-widget').find('#hdnExchangeName').val(strExchangeName);
            //$(selRow).closest('.ui-widget').find('#hdnCcy').val(strCcy);
            $(selRow).closest('.tbl_cust').hide();
            $(autocompleteInput).focus();
            $(txtID).parent().find(".btnSelect").click();
            btnSelect = $(txtID).parent().find(".btnSelect").attr('id');
            document.getElementById(btnSelect).click();
        }
    } catch (er) { WriteLog_Error("SelectProductDetails " + er.message); }


}

//Added by Rohit on 23 May 2019 to get control sequence
/*function ChangeRowsTemplatewise(cboTemplate) {
    //var cboTemplate = $('#<%=cboTemplate.ClientID%> option:selected').text();
    //alert('Rohit');
    //alert(cboTemplate);
    //
    if (cboTemplate != '') {
        $.ajax({
            type: "POST",
            url: "../FinIQ_User_Controls/ShareSearch/WebMethod.aspx/GetTemplateSequence",
            cache: false,
            data: "{'templateName':'" + cboTemplate + "'}",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            crossDomain: true,
            complete: function (XMLHttpRequest, textStatus, errorThrown) {

            },
            success: function (data) {
                var objData;
                $.each(data, function (key, value) {
                    var jsonData = JSON.stringify(value);
                    var a1 = new Array();

                    a1 = jsonData.split("~");
                    a1[0] = a1[0].substr(1);

                    a1[2] = a1[2].substring(0, a1[2].length - 1);

                    //a[0] = "UDF"  a[1] = "Custom"  a[2] = "Customer"
                    //alert(a1[0]);
                    //alert(a1[1]);
                    //alert(a1[2]);
                    //$(a1[1]).after($(a1[0]))
                    $(a1[2]).before($(a1[1]))
                    $(a1[1]).before($(a1[0]))
                    //$(a1[0]).after($(a1[2]))
                    //($(a1[2]).after($(a1[0]))).after($(a1[1]));
                })
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
               // alert("Error occured rgregegergreg..");
            },
            select: function (event, ui) {
            }
        });
    }

}*/

//Added by Rohit on 23 May 2019 to get control sequence
function ChangeRowsTemplatewise(cboTemplate) {
    $(document).ready(function () {
        ChangeRowsTemplatewise1(cboTemplate)
    });

}

function ChangeRowsTemplatewise1(cboTemplate1) {
    try {

        WriteLog("ChangeRowsTemplatewise Called");


        //cboTemplate = $('[id$=cboTemplate] option:selected').val();
        ////alert(cboTemplate);
        ////alert(cboTemplate1);
        //if (cboTemplate == undefined)
        //{
        //    //alert('1111');
        //    cboTemplate = cboTemplate1;
        //}
        cboTemplate = cboTemplate1;
        if (cboTemplate != '') {
            $.ajax({
                type: "POST",
                url: "../FinIQ_User_Controls/ShareSearch/WebMethod.aspx/GetTemplateSequence",
                cache: false,
                data: "{'templateName':'" + cboTemplate + "'}",
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                crossDomain: true,
                async: false,  //Changed by SwatiP || Shekhar 4-Oct-2021 <UWI-163>
                complete: function (XMLHttpRequest, textStatus, errorThrown) {
                },
                success: function (data) {
                    //alert('4989848');
                    var objData;
                    if (data.d != "" && JSON.stringify(data.d).replace(/"/g, "").indexOf("~") > -1) {
                        var jsonData = JSON.stringify(data.d).replace(/"/g, "").split("~");
                        if (jsonData != "" && jsonData.length == 3) {
                            var a1 = jsonData;
                            $(a1[2]).before($(a1[1]))
                            $(a1[1]).before($(a1[0]))

                        }
                        else if (jsonData != "" && jsonData.length == 2) {
                            var a1 = jsonData;
                            $(a1[1]).before($(a1[0]))

                        }
                    }
                    Set_FocusedControl();
                    //alert('49');
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    //console.log("Error occured.." + XMLHttpRequest.message);
                    WriteLog("ChangeRowsTemplatewise Ajax error");
                }
            });
        }


    } catch (er) { WriteLog("ChangeRowsTemplatewise " + er.message); }
    finally { WriteLog("ChangeRowsTemplatewise END"); Set_FocusedControl(); }

}


//commented by shreyasv For signalr notifications replacement 8-jan-2021 -start  PLEASE CONTACT BONDS TEAM INCASE ANY QUERIES

//function SubScrib(WebSocketIP, USERID) {
//    // 
//    //alert(WebSocketIP);
//    var TotalChkBx;
//    var Counter;
//    Counter = 0;
//    preM = 'ctl00_MainContent_';
//    secs = 0;
//    count = 0;
//    var rfqid = Math.random();
//    //alert(WebSocketIP);
//    if (WebSocketIP == '' || WebSocketIP == undefined) {
//        // WebSocketIP = "finiq471";  //$("#<%=hdn_WebsocketIP.ClientID%>").val();
//    }

//    // alert(1);
//    if (1 == 1) {
//        var prem;
//        if (rfqid == "") { }
//        else {

//            $(document).ready(function () {

//                var wsprotocol;
//                if (location.protocol == "http:")
//                    wsprotocol = "ws:"
//                else if (location.protocol == "https:")
//                    wsprotocol = "wss:"
//                else
//                    wsprotocol = "ws:"

//                try {
//                    ws = new WebSocket("" + wsprotocol + "//" + WebSocketIP + "/FinIQService/WSCallback.svc");

//                }
//                catch (error) {
//                    //alert(error);
//                }
//                //  ws = new WebSocket("WS://" + WebSocketIP + "/FinIQService/WSCallback.svc");

//                ws.onopen = function () {

//                    if (ws.readyState == WebSocket.OPEN) {

//                        ws.send('MASTERSUBSCRIBE|' + USERID);

//                    }
//                    else {
//                        //alert('Connection is closed', 'success');
//                    }
//                };
//                ws.onmessage = function (evt) {
//                    //alert('Received');
//                    var msg = evt.data;
//                    var strRes = JSON.parse(msg);

//                    var MesssageType = (strRes["MesssageType"] == null ? "" : strRes["MesssageType"].toUpperCase());

//                    if (ws.readyState == WebSocket.OPEN && MesssageType == "NOTIFICATION") {
//                        var millisecondsToWait = 1000;
//                        setTimeout(function () {
//                            $("#ctl00_MainContent_workflowControl_btnProductSearch").click();
//                        }, millisecondsToWait);
//                    }
//                };
//                ws.onerror = function (evt) {
//                    //
//                    //  alert('Error with code : ' + evt.code + '', 'error');
//                };
//                ws.onclose = function (evt) {
//                    //alert('Onclose' + evt.reason);
//                    //alert('Onclose called - Event : ' + evt + ', code : ' + evt.code + ', reason : ' + evt.reason + ', wasClean : ' + evt.wasClean);
//                    //alert('close');
//                    ws.close();
//                    //
//                    if (document.getElementById("ctl00_hdnBOSDealEntry") != null) {
//                        document.getElementById("ctl00_hdnBOSDealEntry").value == "";
//                        //   SubScrib(WebSocketIP, USERID);
//                    }
//                };
//                //  }
//            });
//        }

//    }
//}

//function Response(WebSocketIP, USERID) {
//    ws.onopen = function () {
//        if (ws.readyState == WebSocket.OPEN) {
//            ws.send('RFQRESPONSE|' + USERID);
//        }
//        else {
//            //alert('Connection is closed', 'success');
//        }
//    };
//    ws.onmessage = function (evt) {
//        //alert("Response start....")

//    };
//    ws.onerror = function (evt) {
//        // alert('Error with code : ' + evt.code + '', 'error');
//    };
//    ws.onclose = function (evt) {
//    };

//}
//commented by shreyasv For signalr notifications replacement 8-jan-2021 -end  PLEASE CONTACT BONDS TEAM INCASE ANY QUERIES


function WriteLog(msgLog) {

    console.log(msgLog)
}

function WriteLog_Error(msgLog) {
    console.time();
    console.log(msgLog);
    console.timeEnd();
}


window.onerror = function (msg, url, line) {

    var params = "msg=" + encodeURIComponent(msg) + '&amp;url=' + encodeURIComponent(url) + "&amp;line=" + line;

    WriteLog_Error(params);

};


var chkdigopen = 1;
var chkInterval;
function Embedded_PopUp_Open(PageName, POPUPWidth, POPUPHeight) {
    /* Added by Arati K to disable window scroll on 15 Jan 2020 -- Start*/
    var scrollPosition = [
        self.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft,
        self.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
    ];
    //added by shreyasv for popup size default 07 may 2020
    var bondsPopup = GetSizesForBonds(PageName, POPUPWidth, POPUPHeight)
    POPUPHeight = bondsPopup.popupheight;
    POPUPWidth = bondsPopup.popupwidth;
    //added by shreyasv for popup size default 07 may 2020

    var html = jQuery('html');
    html.data('scroll-position', scrollPosition);
    html.data('previous-overflow', html.css('overflow'));
    //   html.css('overflow', 'hidden');
    //  window.scrollTo(scrollPosition[0], scrollPosition[1]);
    /* Added by Arati K to disable window scroll on 15 Jan 2020 -- End*/
    $('body').find("#ModalBoxInside112").remove();
    $('body').append('<div id="ModalBoxInside112" style="top:0px; left:0px; "width:"+POPUPWidth+"px !important;Height:"+POPUPHeight+"px "+"!important"><iframe id="ifrm11" class="holds-the-iframe" frameborder="0" style="width:100%; height:100%;" Src=' + PageName + '&Master_Popup=POPUP></iframe></div>')

    $('body').find("#ModalBoxInside112").dialog({
        display: 'block',
        modal: true,
        draggable: true,
        autoOpen: true,
        closeOnEscape: true,
        position: { my: 'top+50px', at: 'top', of: window }, //added by shreyasv 2-feb-2021 POPUP Center Alignment 
        resizable: true,    //added by shreyasv for popup size default 05 may 2020
        width: POPUPWidth,
        height: POPUPHeight
        , drag: function (event, ui) { }
        , drop: function (event, ui) { }
        , dragStart: function (event, ui) {
        }
        , dragStop: function (event, ui) {
            if ($('.ui-dialog')[0].offsetTop < 0 || $('.ui-dialog')[0].offsetTop >= $('body')[0].clientHeight) {
                $('.ui-dialog').css('top', '5px');
            }
            if ($('.ui-dialog')[0].offsetleft < 0 || $('.ui-dialog')[0].offsetleft >= $('body')[0].clientWidth) {
                $('.ui-dialog').css('left', '5px');
            }

        }
        , open: function (event, ui) {
            chkdigopen = 1;
            $(".ui-widget-overlay").css({
                background: "rgb(50, 50, 50) !important",
                opacity: ".50 !important",
                filter: "Alpha(Opacity=50) !important",
            });

            // || start ||added by sushmita.h on 27 feb 2020 for close button icon positioning || asked by Udit sir
            $(".ui-button-icon-only .ui-icon").css({
                top: "30%",
                left: "80%"
            });

            //Updated by Shekhar L @26-Aug-2021
            $('iframe').on("load", function () {
                //Updated by Shekhar L @01-Sep-2021
                if (window.localStorage.getItem('FinIQTheme') != null) {
                    if ($(document).find('iframe').length > 0) {
                        $(document).find('iframe').each(function (i, elem) {
                            $($(elem).context.contentDocument).find('link[type="text/css"][id$="ctl00_FinIQTheme"], link[type="text/css"][href*="Style1"]').attr('href', '../App_Themes/' + (window.localStorage.getItem('FinIQTheme') == null ? "Style1" : window.localStorage.getItem('FinIQTheme')) + '.css');
                        });
                    }
                }
            });


            //Commented by shreyasv 2-feb-2021 POPUP Center Alignment --start
            // || end ||added by sushmita.h on 27 feb 2020 for close button icon positioning || asked by Udit sir
            // wleft = Number(Math.abs($(window)[0].innerWidth - ($('.ui-dialog').width())) / 6.5).toFixed(0);
            // if (($(window)[0].innerHeight - 50) >= $('.ui-dialog').height()) {
            // wtop = Number(Math.abs($(window)[0].innerHeight - $('.ui-dialog').height()) / 2).toFixed(0) - 45;
            // } else {
            // wtop = Number($(window)[0].innerHeight / 4).toFixed(0);
            // }
            // // $('.ui-dialog').css({ "position": "fixed", "left": wleft + 'px', "top": Math.abs(wtop) + 'px', "max-width": "max-content", "max-height": "max-content" });
            // $('.ui-dialog').css({ "position": "fixed", "left": "95px", "top": "50px", "max-height": "max-content" });//"max-width": "max-content"
            // $('.ui-dialog.ui-dialog-content').css({ "left": "0px", "top": "20px" });
            //Commented by shreyasv 2-feb-2021 POPUP Center Alignment --end


            $(document).keyup(function (e) {
                if (e.keyCode == 27) {

                    $('body').find("#ModalBoxInside112").dialog("close");
                    e.preventDefault();
                }
            });
            chkInterval = setInterval(function () {
                //updated by Shekhar L @01-Sep-2021
                if ($(document).find('iframe')[0].contentDocument.body != null) {
                    if ($(document).find('iframe')[0].contentDocument.body.text == "" && (POPUPWidth == 0 && POPUPHeight == 0)) {
                        $('body').find("#ModalBoxInside112").dialog("close");
                        clearInterval(chkInterval);
                    } else {
                        clearInterval(chkInterval);
                    }
                }
            }, 100);


        }
        , beforeClose: function (event, ui) {
            clearInterval(chkInterval);
            chkdigopen = 0;
            /* Added by Arati K to show window scroll on 15 Jan 2020 */
            var html = jQuery('html');
            var scrollPosition = html.data('scroll-position');
            html.css('overflow', html.data('previous-overflow'));
            window.scrollTo(scrollPosition[0], scrollPosition[1]);
            $("body").css({ 'overflow': html.data('previous-overflow') });

        }
        , close: function (event, ui) {
            //  $('body input[id="ctl00_hdnIsIframePopUpOpen"]').click();
            if ($('[id$="UpdateProgress1"]').css('display') == 'none') {
                //$('[id$="btnProductSearch"]').click(); //This is implemented to load workflow blotter on popup close
            }
            //Added by Mitali on 30-Apr-2020||To update notification count on popup close

            // to call any clearing code for i-frame inside workflow popup only have to implement Embedded_PopUp_Close_WF function on page level.
            if (eval("typeof document.getElementById('ifrm11').contentWindow.Embedded_PopUp_Close_WF") != "undefined") {
                document.getElementById('ifrm11').contentWindow.Embedded_PopUp_Close_WF();
            }

            if (PageName.toUpperCase().indexOf("FINIQ_BOND_ENTRY") > -1 || PageName.indexOf("Bonds_RFQResponseAction") > -1) {
                getBondsNotifCount(document.getElementById("ctl00_hdnUserNameForNotification").value);
            }
            //End oof addition|Mitali
        }

    });


}

////modified by shreyasv manualPopupSize 08 apr 2021
//modified by shreyasv manualPopupSize 10 may 2021
//modified by shreyasv manualPopupSize 18 may 2021
//modified by shreyasv manualPopupSize 18 may 2021
function GetSizesForBonds(PageName, POPUPWidth, POPUPHeight) {
    try {
        PageName = PageName.toUpperCase();
        var popupwidth = 0, popupheight = 0;
        var queryQuickEntry;
        var queryVar = parseQueryString('BUTTONCAPTION', PageName)
        var w = window.innerWidth;
        var h = window.innerHeight;
        if (queryVar == 'MANUAL') {
            if (POPUPWidth < 1100)
                popupwidth = POPUPWidth;  //Modified by Mitali on 12_nov for mashreq manual trade size changes      
            popupheight = h - (h * (15 / 100));
        }
        //else {
        //    popupwidth: popupwidth == 0 ? w : POPUPWidth, //added by shreyas v for equity manualorder popup size default 03 dev 2020
        //        popupheight = h - (h * (13 / 100));
        //}

        // Modified 17-Mar-2021 || Changed FINIQ_BOND_ENTRY to FINIQ_BOND_ENTRY.ASPX ||shreyas
        queryQuickEntry = parseQueryString('RMWMODE', PageName)
        if (PageName.includes("BONDSECURITYMAPPING") || (PageName.includes("FINIQ_BOND_ENTRY.ASPX") && queryQuickEntry != 'QUICKENTRY') ||
            PageName.includes("CUSTALLOCSIMULATIONPORTFOLIO") ||
            PageName.includes("GENERATESCHEDULE") || PageName.includes("MTM_PRICE_UPLOAD")) //added by shreyasv for bond maintenance popup size default 12 may 2020
        {
            popupwidth = w - (w * (15 / 100));
            popupheight = h - (h * (15 / 100));
        }

        if (PageName.includes("EQ_ORDER_ENTRY") || PageName.includes("ORDER_AGGREGATION/MULTI_BLOTTER_HEDGE_ENTRY.ASPX")
            || PageName.includes("EQUITYDEALENTRY/EQUITYDEALENTRY.ASPX")) {
            popupwidth = w - (w * (15 / 100));
            popupheight = h - (h * (15 / 100));
        }

        if (PageName.includes("EQ_ORDER_ENTRY")) {
            popupwidth = w - (w * (2.5 / 100));
            popupheight = h - (h * (7 / 100));
        }

        if (PageName.includes("EQ_HOLDING_DETAILS.ASPX")) {
            popupwidth = 0;
            popupheight = 0;
        }
        if (PageName.includes("RMWORKSTATION_BONDS/PRODUCTINFO.ASPX")) {
            popupwidth = POPUPWidth;
            popupheight = h - (h * (10 / 100));
        }
        //modified by shreyasv tradeview PopupSize 18 may 2021

        if (PageName.includes("/FINIQ_TRADEVIEW/FINIQ_TRADEVIEW.ASPX")) {
            if (w > 1200) {
                popupwidth = 900;
                popupheight = h - (h * (10 / 100));

            } else {
                popupwidth = w - (w * (40 / 100));
                popupheight = h - (h * (10 / 100));
            }
        }

        //added by shreyasv  02Jun2021  for Mashreq START
        if (PageName.includes("/BONDS_MULTIPLERFQRESPONSE/BONDS_MULTIPLERFQRESPONSE.ASPX")) {
            popupwidth = w - (w * (15 / 100));
            popupheight = h - (h * (10 / 100));
        }
        //added by shreyasv 02Jun2021 for Mashreq END

        var popObj = {
            popupwidth: popupwidth == 0 ? POPUPWidth : popupwidth,
            popupheight: popupheight == 0 ? POPUPHeight : popupheight
        }
        return popObj;
    }
    catch (e) {
        console.log('Error in GetSizesForBonds, includes: ', e);
    }
}



//added by shreyasv 10 may 2021 | unsupported IE function - includes Start
String.prototype.includes = function (str) {
    try {
        var result;
        result = (this.indexOf(str) !== -1) ? true : false;
        return result;
    }
    catch (e) {
        console.log('Error in function, includes: ', e);
    }
}
//added by shreyasv 10 may 2021 | unsupported IE function - includes END

function parseQueryString(variable, PageName) {
    var query = PageName;
    var vars = query.split('&');
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split('=');
        if (decodeURIComponent(pair[0]) == variable) {
            return decodeURIComponent(pair[1]);
        }
    }
    //console.log('Query variable %s not found', variable);
}
//added by shreyasv for popup size default 07 may 2020


//function CloseParentDialog() {
//    $(document).ready(function () {
//        $('.ui-dialog-content').dialog("close");
//    });
//}
flag_close = 0;
function CloseParentDialog() {
    if (flag_close == 0) {
        flag_close = 1;
        window.top.CloseParentDialog();
    }
    $('#ModalBoxInside112').dialog('close')
}

function EnterCustomerControlEvent(txtCustCtl, event) {
    try {
        e = event || window.event;
        event = event || window.event;
        var keyCode = event.which;
        x = $(txtCustCtl).attr("id");

        var txt = $("#" + x).val().trim();
        var term = "";
        term = txt;


        if (txt == "" && (e.keyCode == 8)) {
            //$("#" + x).attr('title', 'Customer Name :  BCFX Customer ID :  RM ID :  ');
            autocomplete_clicked('', '0', '', '', '', '', '', '')
            $("#" + x).blur();
            return;
        }

        if (term == "") {
            $("#" + x).parent().find("#tbl_cust").html("");
            $("#" + x).parent().find("#tbl_cust").hide();
            if (e.keyCode == 13) {

                //$("#" + x).attr('title','Customer Name :  BCFX Customer ID :  RM ID :  ');
                autocomplete_clicked('', '0', '', '', '', '', '', '')
                $("#" + x).blur();
                return;
            }
        }
        if (e.keyCode == 13) {
            //  
            ShowPopup2(x);
            var keyCode = event.which;
            var txt = $("#" + x).val().trim();
            var term = "";
            term = txt;

            /*if (term == "") {
                $("#tbl_cust").html("");
                $("#tbl_cust").hide();

                autocomplete_clicked('', '0', '', '', '', '', '', '')
                return;
            }*/
            // 
            // var path_Name = window.location.pathname;

            var path_Name = "/FinIQWebApp/RMWorkstation/RMW.aspx"; //Edited by shubhamP on 19-Aug-2019
            var myPageName = path_Name.substring(path_Name.lastIndexOf('/') + 1);
            //alert(myPageName);
            var cname = term;

            for (iSingleQoute = 0; iSingleQoute < cname.length - 1; iSingleQoute++) {
                cname = cname.replace("'", "@");
                cname = cname.replace("@", "");
                term = cname;
            }

            //for (iSingleQoute = 0; iSingleQoute < CustomerName.length - 1; iSingleQoute++) {
            //    CustomerName = CustomerName.replace("@", "'");
            //}

            //  alert(term);
            $.support.cors = true;
            $.ajax({
                type: "POST",
                url: "" + path_Name + "/FindCustomer",
                contentType: "application/json; charset=utf-8",
                dataType: "text",
                cache: false,
                data: "{'term':'" + term + "', 'Mode':'" + urlToRest + "'}",
                //data:"{}",
                crossDomain: true, //Modified Code

                //complete: function (jqXHR, status) {
                //    alert("complete: " + status + "\n\nResponse: " + jqXHR.responseText);
                //},

                success: function (data) {
                    // 
                    //var obj = jQuery.parseJSON(data.d);
                    var obj = jQuery.parseJSON(data);
                    var tbl = "<div style='overflow-y:auto;height:auto;max-height:300px;background-color:#FFFFFF;' class='Grid'>"
                    tbl += "<table class='TableSearchResult' cellpadding=1 cellspacing=1 style='border-collapse:collapse;' >"
                    tbl += "<tr><th>Customer Name</th>"
                    tbl += "<th>PAN No</th>"
                    tbl += "<th>DOC ID</th>"  // --<Javed>--Added <DOC ID> column told by Milind N.--<on 23-Dec-2016>
                    tbl += "<th>CIF NO</th>"
                    // --<Nitin>--commentted  <Risk Profile and Settlement Account> column told by Sarang J.--<on 31-Jul-2019>
                    //tbl += "<th>Risk Profile</th>" 
                    //// tbl += "<th>Allocation Code</th>"
                    //tbl += "<th>Settlement Account</th></tr>";
                    // --<Javed>--Added <DOC ID> column told by Milind N.--<on 23-Dec-2016>
                    var objData;
                    $.each(obj, function (key, value) {

                        //var mydata = obj;

                        tojson: var jsonData = JSON.stringify(value);
                        objData = $.parseJSON(jsonData);
                    })


                    if (objData === null || objData.length === 0) {
                        $("#" + x).parent().find("#tbl_cust").html("");
                        $("#" + x).parent().find("#tbl_cust").hide();
                        alert("No details found for selected customer");
                        autocomplete_clicked('', '0', '', '', '', '', '', '')
                        $("#" + x).blur();
                        //$("#" + x).attr('title', 'Customer Name :  BCFX Customer ID :  RM ID :  ');                                     
                        return;

                    }
                    else {
                        for (var i = 0; i < objData.length; i++) {
                            //tbl += "<tr>";
                            // alert(objData[i].CustomerName);
                            // tbl += "<tr class='SearchResultRow' onClick=\"autocomplete_clicked('" + objData[i].CustomerName + "','" + objData[i].CustomerID + "','" + objData[i].AH_CIF_No + "','" + objData[i].AH_Type_1 + "','" + objData[i].AccountNo + "','" + objData[i].AH_Doc_ID + "')\">"
                            var cname = objData[i].CustomerName;

                            for (iSingleQoute = 0; iSingleQoute < cname.length - 1; iSingleQoute++) {
                                cname = cname.replace("'", "@");
                            }
                            //alert(cname);
                            tbl += "<tr class='SearchResultRow' onclick=\"autocomplete_Customer('" + cname + "','" + objData[i].CustomerID + "','" + objData[i].AH_CIF_No + "','" + objData[i].AH_Type_1 + "','" + objData[i].AccountNo + "','" + objData[i].AH_Risk_Profile_Rating + "','" + objData[i].AH_Doc_ID + "')\">"


                            //   tbl += '<tr class="SearchResultRow" onclick="autocomplete_Customer("' + objData[i].CustomerName + '","' + objData[i].CustomerID + '","' + objData[i].AH_CIF_No + '","' + objData[i].AH_Type_1 + '","' + objData[i].AccountNo + '","' + objData[i].AH_Doc_ID + ' ")">';


                            //tbl += "<td>hhhhhh</td>";
                            tbl += "<td>" + objData[i].CustomerName + "</td>";
                            tbl += "<td>" + objData[i].CustomerID + "</td>";
                            tbl += "<td>" + objData[i].AH_Doc_ID + "</td>";   // --<Javed>--Added <DOC ID> column told by Milind N.--<on 23-Dec-2016>
                            tbl += "<td>" + objData[i].AH_CIF_No + "</td>";
                            // --<Nitin>--commentted  <Risk Profile and Settlement Account> column told by Sarang J.--<on 31-Jul-2019>
                            //        tbl += "<td>" + objData[i].AH_Risk_Profile_Rating + "</td>";
                            //// tbl += "<td>" + objData[i].AH_ALLOCATION_CODE + "</td>";
                            //        tbl += "<td>" + objData[i].AccountNo + "</td>";
                            // --<Nitin>--commentted  <Risk Profile and Settlement Account> column told by Sarang J.--<on 31-Jul-2019>
                            tbl += "</tr>";
                        }
                        tbl += "</table></div>";
                        $("#" + x).parent().find("#tbl_cust").html(tbl);
                        $("#" + x).parent().find("#tbl_cust").show();
                    }
                    $("#" + x).parent("#dialog2").hide();
                },

                error: function (xhr, textStatus, error) {
                    //called on ajax call error
                    // alert();
                    //  alert("Error: " + error);
                }
            });
        }
    } catch (error) {
        alert(error);
    }
}

function EndRequestHandler1(sender, args) {
    // Start Added on 09-Apr-2019 For Popup position
    $(document).ready(function () {
        // 
        x = localStorage.getItem("x");
        y = localStorage.getItem("y");
        $(".PopupCcy").css("left", Number(x) + "px");
        $(".PopupCcy").css("top", (Number(y)) + "px");
        $(".PopupCcy").css("margin", "");
        //$(".PopupCcy").offset(top, y);
    });
    // End Added on 09-Apr-2019 For Popup position

    document.onkeypress = function (event, args) { return true; }
    $(window).keypress = function (event, args) { return true; }
    Set_FocusedControl();


}
// <START>Added on 17-Sept-2019 For Checking all checkboxes in Product Schedule Page : Rishabh And Joel
function checkAll_ProductSchedule(chkAll) {
    //
    var GridView = chkAll.parentNode.parentNode.parentNode;
    var inputList = GridView.getElementsByTagName("input");

    for (var i = 0; i < inputList.length; i++) {

        if (inputList[i].type == "checkbox" && chkAll != inputList[i]) {
            if (chkAll.checked) {
                inputList[i].checked = true;

            }
            else {
                inputList[i].checked = false;

            }
        }
    }

}
function AllowNumericValuesOnly_ProductSchedule(e) {
    var keycode;
    if (window.event)
        keycode = window.event.keyCode;
    else if (event)
        keycode = event.keyCode;
    else if (e)
        keycode = e.which;
    else return true;

    if ((keycode > 47 && keycode <= 57)) {
        return true;
    }
    else { return false; }
    return true;
}
function enterKeyPress_ProductSchedule(e, btnToBeClicked) {
    var keycode;
    if (window.event)
        keycode = window.event.keyCode;
    else if (event)
        keycode = event.keyCode;
    else if (e)
        keycode = e.which;
    else return true;
    if (keycode == 13) {
        document.getElementById(btnToBeClicked).click()
    }
}
//<END Rishabh & Joel>

//<Start - Pranjali K/Dhanashri S|| Export functionality for UCPSimulation tab>

function CallDownload(flag) {


    //var selectedValue = ddl.options[ddl.selectedIndex].value;


    ctl00_MainContent_oUCPWhatIF_hdnDownloadType
    if (flag == "Image") {
        downloadImage()
    }
    else {
        downloadPDF()
    }

}
function downloadImage() {

    var id = "ctl00_MainContent_pnlWhatIF";
    var divWidth = document.getElementById(id).offsetWidth;
    var divHeight = document.getElementById(id).offsetHeight;

    var doc = new jsPDF('p', 'mm', [divHeight, divWidth]);

    html2canvas(document.getElementById(id), {
        onrendered: function (canvas) {
            var imgData = canvas.toDataURL();
            downloadURI(imgData, "Document.png");
        }
    });
}




function downloadURI(uri, name) {
    var link = document.createElement("a");

    link.download = name;
    link.href = uri;
    document.body.appendChild(link);
    link.click()
    link.setAttribute('target', '_blank');
}


function downloadPDF() {
    // alert(id);

    var id = "ctl00_MainContent_pnlWhatIF";
    var divWidth = document.getElementById(id).offsetWidth;
    var divHeight = document.getElementById(id).offsetHeight;

    var doc = new jsPDF('p', 'mm', [divHeight, divWidth]);

    html2canvas(document.getElementById(id), {
        background: '#FFFFFF',
        dpi: 900, // Set to 300 DPI
        scale: 1, // Adjusts your resolution
        onrendered: function (canvas) {
            var imgData = canvas.toDataURL('image/jpeg');
            doc.addImage(imgData, 'JPEG', 10, 10, 730, 250);
            doc.save('Document.pdf');



        }
    });
}


//<End - Pranjali K/Dhanashri S|| Export functionality for UCPSimulation tab>



//<Start - Pranjali K/Dhanashri S|| Serach scenario>
function ScenarioChange() {
    try {
        document.getElementById('<%=Scenario_name.ClientID%>').value = document.getElementById('<%=autocomplete_1.ClientID%>').value
    }
    catch (er) {
        console.log(er.message)
    }
}

function SearchScenario(control, e) {

    //<Start || Changed by Arshin S || on 8th Jan 2018 ||PP-31 Multi deal entry issues ::  When click on search icon should search resp search items || asked by Ganesh D>
    var x = control.id.replace("Image", "");

    //if (x == "ctl00_MainContent_FindCustSmart_autocomplete_1") {
    //}
    //else {
    //  //  alert(x.parent().find("autocomplete_1").attr('id'));
    //  //  x = $(x).parent().find("autocomplete_1");
    //    x = $(x).attr('id');

    //}
    //<End || Changed by Arshin S || on 8th Jan 2018 ||PP-31 Multi deal entry issues ::  When click on search icon should search resp search items || asked by Ganesh D>
    var keyCode = event.which;

    var txt = $("#" + x).val().trim();
    var term = "";
    term = txt;

    // changed by Shekhar on 03-Apr-2019
    e = e || window.event;
    if (e.keyCode == 13) {

        $('form input, body').on("keypress", function (e) {
            if (e.keyCode == 13) {
                e.stopPropagation ? e.stopPropagation() : (e.cancelBubble = true);
                e.returnvalue = null;
                return false;
            }

        });

        return false;

    }

    //Added By Bhavya for selection using arrow keys 02-11-19
    if (e.keyCode == 38 || e.keyCode == 40 || e.keyCode == 27 || e.keyCode == 9 || e.keyCode == 16 && e.keyCode == 9) {
        return;
    }
    else if (term.length >= 3) //Added By Bhavya for selection using arrow keys End - 02-11-19
    //if (e.keyCode == 13 || keyCode == 1)
    {
        EnterEventCustControl(x, txt, term, "");
    }
}

function EnterEventCustControl(x, txt, term, event_Name) {
    ShowPopup2(x);
    //var keyCode = event.which;
    //var txt = $("#" + x).val().trim();
    //var term = "";
    //term = txt;

    if (term == "") {
        $("#" + x).parent().find("#tbl_ScenarioMaster").html("");
        $("#" + x).parent().find("#tbl_ScenarioMaster").hide();

        autocomplete_clicked(x, '', '0', '', '')
        return;
    }
    // 
    var path_Name = window.location.pathname;

    var myPageName = path_Name.substring(path_Name.lastIndexOf('/') + 1);



    $.support.cors = true;
    $.ajax({
        type: "POST",
        url: "../FinIQ_User_Controls/WhatifScenarioSearch/web_WhatifScenarioSearch.aspx/FindScenario",
        contentType: "application/json; charset=utf-8",
        dataType: "text",
        cache: false,
        data: "{'term':'" + term + "', 'Mode':'" + urlToRest + "'}",
        //data:"{}",
        crossDomain: true, //Modified Code

        //complete: function (jqXHR, status) {
        //    alert("complete: " + status + "\n\nResponse: " + jqXHR.responseText);
        //},

        success: function (data) {

            //alert(1);
            //var obj = jQuery.parseJSON(data.d);
            var obj = jQuery.parseJSON(data);

            var tbl = "<div style='overflow-y:auto;height:auto;max-height:300px;background-color:#FFFFFF;' class='Grid'>"
            tbl += '<table class="TableSearchResult" width="100px" cellpadding=1 cellspacing=1 style="border-collapse:collapse;">'
            tbl += "<tr><th style='display:none;'>PAN</th>"
            //tbl += "<th>Scenario ID</th>"
            tbl += "<th>Scenario Code</th>"
            tbl += "<th>Scenario Curvename</th>"
            tbl += "<th>Scenario Description</th>"

            // tbl += "<th>Allocation Code</th>"
            //tbl += "<th>Settlement Account</th>";
            tbl += '<th style="width:7px;"><button class="btn" style="cursor:pointer;height:8px;width:20px;" onClick=\"' + "autocomplete_clicked('" + x + "','" + '' + "','" + '' + "','" + '' + "','" + '' + "')" + '\">X</button></th>'
            tbl += "</tr>";

            //tbl += '<th style="min-width:12px;max-width:23px;"><button class="btn" style="cursor:pointer;height:12px;width:24px;" onClick=\"' + "autocomplete_clicked('" + x + "','" + '' + "','" + '' + "','" + '' + "','" + '' + "','" + '' + "','" + '' + "','" + '' + "')" + '\">X</button></th>'

            var objData;
            $.each(obj, function (key, value) {

                tojson: var jsonData = JSON.stringify(value);
                objData = $.parseJSON(jsonData);
            })

            if (objData.length === 0) {
                $("#" + x).parent().find("#tbl_ScenarioMaster").html("");
                $("#" + x).parent().find("#tbl_ScenarioMaster").hide();
                //alert("No details found for selected customer");
                autocomplete_clicked(x, '', '0', '', '', '')
                return;


            }
            else {

                if (event_Name === "onblur") {
                    if (objData.length === 1) {
                        autocomplete_clicked(x, objData[0].SM_ID, objData[0].SM_ScenarioCode, objData[0].SM_ScenarioName, objData[0].SM_ScenarioDescription, objData[0].SM_Curvename) //, objData[0].AH_CIF_No, objData[0].AH_Type_1, objData[0].AccountNo, objData[0].AH_Doc_ID
                    }
                    else {
                        showCust(objData, tbl, x);
                    }
                }
                else {
                    showCust(objData, tbl, x);
                }


            }
            $("#" + x).parent().find("#dialog2").hide();
        },

        error: function (xhr, textStatus, error) {
            //called on ajax call error
            // alert();
            //  alert("Error: " + error);
        }
    });
}


function showCust(objData, tbl, x) {
    for (var i = 0; i < objData.length; i++) {
        //tbl += "<tr>";


        tbl += "<tr class='SearchResultRow' onClick=\"autocomplete_clicked('" + x + "','" + objData[i].SM_ID + "','" + objData[i].SM_ScenarioCode + "','" + objData[i].SM_ScenarioName + "','" + objData[i].SM_ScenarioDescription + "','" + objData[i].SM_Curvename + "')\">"
        //tbl += "<tr class='SearchResultRow' onClick=\"autocomplete_clicked('" + x + "','" + objData[i].CustomerName + "','" + objData[i].CustomerID + "','" + objData[i].AH_CIF_No + "','" + objData[i].AH_Type_1 + "','" + objData[i].AccountNo + "','" + objData[i].AH_Doc_ID + "','" + objData[i].Acct_Type + "')\">"
        //tbl += "<td>hhhhhh</td>";

        //tbl += "<td style='height:0px !important;'>" + objData[i].SM_ID + "</td>";
        tbl += "<td style='height:0px !important;'>" + objData[i].SM_ScenarioCode + "</td>";
        tbl += "<td style='height:0px !important;'>" + objData[i].SM_ScenarioName + "</td>";
        tbl += "<td style='height:0px !important;'>" + objData[i].SM_Curvename + "</td>";
        //tbl += "<td style='height:0px !important;'>" + objData[i].SM_ScenarioDescription + "</td>";
        //tbl += "<td style='height:0px !important;'>" + objData[i].SM_ScenarioName + "</td>";


        // tbl += "<td>" + objData[i].CDM_TLT_ID + "</td>";
        //tbl += "<td>" + objData[i].AH_CIF_No + "</td>";
        // tbl += "<td>" + objData[i].AH_ALLOCATION_CODE + "</td>";
        //tbl += "<td colspan='2'>" + objData[i].AccountNo + "</td>";
        tbl += "</tr>";
    }
    tbl += "</table></div>";
    //alert(x);

    $("#" + x).parent().find("#tbl_ScenarioMaster").html(tbl);
    $("#" + x).parent().find("#tbl_ScenarioMaster").show();
    var tbody = $(".TableSearchResult").find("tbody");
    var selected = tbody.find("tr:nth-child(2)").addClass("selected");
}
//<End || Changed by Arshin S || on 23th July 2018 || Asked by Prashant M>

function ShowPopup2(x) {
    try {
        $("#" + x).parent().find("#dialog2").show();
    } catch (er) {
        console.log(er.message)
    }

}




function autocomplete_changed(event) {

}

function ClearCustomerControl(event) {
    var txt = $("#" + x).val().trim();

    if (term == "") {
        autocomplete_clicked(x, '', '0', '', '', '')
        // alert($('#Scenario_ID').value);
        return;
    }
}



function autocomplete_clicked(tr, SM_ID, SM_ScenarioCode, SM_ScenarioName, SM_ScenarioDescription, SM_Curvename) //CDM_TLT_ID, AH_CIF_No, AH_ALLOCATION_CODE, AH_Type_1, AccountNo, AH_Doc_ID, Acct_Type
{
    x = tr;



    //  alert($(tr).parent().parent().parent().parent().html());
    $("#" + x).parent().find('#Scenario_Code').val(SM_ScenarioCode);
    $("#" + x).parent().find('#Scenario_name').val(SM_ScenarioName);
    $("#" + x).val(SM_ScenarioName);
    //$("#" + x).parent().find('#Scenario_ID').val(SM_ID);
    // $('#sel_cust_tlt_id').val(CDM_TLT_ID);
    //$("#" + x).parent().find('#sel_cust_rm_id').val(AH_CIF_No);
    //  $('#sel_cust_allocation_code').val(AH_ALLOCATION_CODE);
    //$("#" + x).parent().find('#sel_cust_type').val(AH_Type_1);
    //$("#" + x).parent().find('#sel_cust_Doc_ID').val(AH_Doc_ID);


    $("#" + x).parent().find('#Scenario_CurveName').val(SM_Curvename);
    //$("#" + x).parent().find('#Scenario_Description').val(SM_ScenarioDescription);

    $("#" + x).parent().find("#tbl_ScenarioMaster").hide();
    //__doPostBack('Scenario_name_ValueChanged', 'ValueChanged');
    $("#" + x).parent().find("#btnSelect").click();


    $("#lastcontrol").val("ctl00_MainContent_FindScenarioSmart_autocomplete_1");
    $("#ctl00_MainContent_FindScenarioSmart_autocomplete_1").focus();
}



//<End - Pranjali K/Dhanashri S|| Serach scenario>

function KeysAllowedForNotional_NEW(event) {
    try {
        //  26-Apr-2019 by Shekhar

        //changed whode function 0n 12-Jun-2019 by shekhar

        event = event || window.event;
        charkode = (event.which) ? event.which : event.keyCode;

        var obj;
        if (event.target) { obj = event.target; }
        else if (event.srcElement) { obj = event.srcElement; }

        if (charkode != 8) {

            //if ((Len(obj.value) > 0) && (!(isNumeric(Right(obj.value, 1)))))
            if ((Len(obj.value) > 0) && (Right(obj.value, 1) != "." && (!(isNumeric(Right(obj.value, 1)))))) {
                return false;
            }

            else {


                if (charkode == 46) {
                    //Check if the text already contains the . character
                    if (obj.value.indexOf('.') === -1) {
                        return true;
                    } else {
                        return false;
                    }
                } else {
                    //on 22-May-2019 Added by Shekhar for Notional
                    character = String.fromCharCode(charkode)
                    if (((charkode > 47 && charkode < 58)) || (character == "K" || character == "M" || character == "B" || character == "T" || character == "L" || character == "P" || character == "k" || character == "m" || character == "b" || character == "t" || character == "l" || character == "p" || character == ".")) {
                        return true;
                    } else {
                        return false;
                    }
                }
            }

        }


    }
    catch (error) {

    }
    finally {
        charCode = ""
        event = undefined;
    }
}


function FormatSpread(spread) {
    //
    var rel_Amount = /\d+(K$(?![K|M|B])|M$(?![K|M|B])|B$(?![K|M|B]))/i;
    var rel_Char = /(K|M|B)/i;
    var pos;
    var number;
    var rel_invalidChar = /[\#|\@|!|\&|\*|\%|\\|\+|\*|\^|\-]/;
    try {
        //var rel_Amount = /([-+]?([0-9]*\.)?[0-9]+[K|M|B]*$)/i;

        if (spread.search(rel_invalidChar) != -1) {
            return null;
        }
        else if (spread.search(/[A-Z]/i) != -1) {
            return null;
        }
        else {
            return spread;
        }
    }
    catch (error) {

    }
    finally {
        rel_Amount = null;
        rel_Char = null;
        pos = null;
        number = null;
        rel_invalidChar = null;
        notional = null;
    }
}


function resizeIframe() {

    ht = 545;//$(window.top.document).find('.ui-dialog-content  iframe')[0].contentWindow.document.body.offsetHeight;
    window.top.postMessage(ht, "*");

}

window.addEventListener('message', function (e) {
    $(window.top.document).find('.ui-dialog-content  iframe').height(e.data + 'px');
}, false);






//--Bond Shreyas

function EnterEventProduct(autompleteprod1, e) {
    try {

        var keyCode = event.which;

        var product = autompleteprod1;

        var txt = autompleteprod1.value;

        var term = "";
        term = txt

        if (term == "") {
            $("#tbl_prod").html("");
            $("#tbl_prod").hide();
            autocomplete_prodclicked("", 0, '')
            return;
        }

        if (e.keyCode == 13) {
            if (term.length >= 3) {
                // ShowPopup1();
                $("#dialog1").show();

                if (keyCode >= 32)
                    term = txt + String.fromCharCode(event.which);
                else
                    if (keyCode == 8)
                        term = txt.substring(0, txt.length - 1);

                if (term == "") {
                    $("#tbl_prod").html("");
                    $("#tbl_prod").hide();
                    //autocomplete_prodclicked("", 0)
                    return;
                }


                //autocomplete_prodclicked("", 0)


                //alert(term);

                var LoginID = "";

                var LoginID = $('[id$="hdnLoginID"]').val();//'<=hdnLoginID.Value%>';
                var entityID = $('[id$="HdnEntityId"]').val();//'<=HdnEntityId.Value%>';

                var path_Name = window.location.pathname;
                var myPageName = path_Name.substring(path_Name.lastIndexOf('/') + 1);

                $.support.cors = true;
                $.ajax({
                    type: "POST",
                    url: "../FinIQ_User_Controls/FinIQ_WebMethods.aspx/FindProduct",// + myPageName + "/FindProduct",
                    contentType: "application/json; charset=utf-8",
                    dataType: "text",
                    cache: false,
                    crossDomain: true, //Modified Code            
                    data: "{'strEntityID':'" + entityID + "', 'strLogin':'" + LoginID + "', 'strProductName':'" + term + "', 'strPagingValue':'0', 'strCurrentPage':'0', 'QueryString':''}",
                    //async: true,
                    //cache: false,
                    success: function (data) {
                        //alert(data);
                        var obj = jQuery.parseJSON(data);
                        var tbl = "<div style='overflow-y:auto;height:auto;max-height:300px;background-color:#FFFFFF;' class='Grid'><table class='TableSearchResult' border=1 cellpadding=1 cellspacing=1 style='border-collapse:collapse;background-color:#FFFFFF'><tr><th>Product Name</th><th>Product Id</th></tr>";

                        var objData;
                        $.each(obj, function (key, value) {
                            var jsonData = JSON.stringify(value);
                            objData = $.parseJSON(jsonData);
                        })

                        if (objData.length === 0) {
                            $("#tbl_prod").html("");
                            $("#tbl_prod").hide();
                            //alert("No details found for selected product");
                            autocomplete_prodclicked('', 0, '');
                            return false;


                        }
                        else {
                            for (var i = 0; i < objData.length; i++) {

                                tbl += "<tr onClick=\"autocomplete_prodclicked('" + objData[i].Product_Name + "','" + objData[i].Note_Master_ID + "', '" + objData[i].Template_Id + "')\">"
                                tbl += "<td>" + objData[i].Product_Name + "</td>";
                                tbl += "<td>" + objData[i].Note_Master_ID + "</td>";

                                tbl += "</tr>";
                            }

                            tbl += "</table></div>";
                            $("#tbl_prod").html(tbl);
                            $("#tbl_prod").show();

                        }
                        $("#dialog1").hide();

                    },
                    error: function (xhr, textStatus, error) {

                        console.log("Error: " + error);
                    }

                });
            }
        }

    } catch (error) { console.log(error.message); }
}


function autocomplete_prodclicked(Product_Name, Note_Master_ID, Template_ID) {

    $('#ProductName').val(Product_Name);
    $('#NoteMasterID').val(Note_Master_ID);
    $('#hdnTemplateID').val(Template_ID);
    var product = $('[id$="autompleteprod1"]')[0].id;// '<=autompleteprod1.ClientID>';

    document.getElementById(product).value = Product_Name;


    $("#tbl_prod").hide();
    __doPostBack('prod_name_ValueChanged', 'ValueChanged');
}

//Aditya B || 04-Feb-2020 || For Workbench || Start
//Desc: Made seperate copy of an existing "Embedded_PopUp_Open" function. Added an extra parameter "ApplicationType" in the new function.
//Reason: There are two types applications(Angular & DotNet) getting launched from workbench. Angular doesn't require "&Master_Popup=POPUP" param in their URL whereas Dotnet applications requires "&Master_Popup=POPUP" param in their URL. 
function Embedded_PopUp_Open_Workbench(PageName, POPUPWidth, POPUPHeight, ApplicationType) {
    //
    /* Added by Arati K to disable window scroll on 15 Jan 2020 -- Start*/
    var scrollPosition = [
        self.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft,
        self.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
    ];

    var html = jQuery('html');
    html.data('scroll-position', scrollPosition);
    html.data('previous-overflow', html.css('overflow'));
    //   html.css('overflow', 'hidden');
    //  window.scrollTo(scrollPosition[0], scrollPosition[1]);
    /* Added by Arati K to disable window scroll on 15 Jan 2020 -- End*/
    $('body').find("#ModalBoxInside112").remove();

    if (ApplicationType.trim().toUpperCase() == "ANGULAR") {
        $('body').append('<div id="ModalBoxInside112" style="top:0px; left:0px; "width:"+POPUPWidth+"px !important;Height:"+POPUPHeight+"px "+"!important"><iframe id="ifrm11" frameborder="0" style="width:100%; height:100%;" Src=' + PageName + '></iframe></div>')
    }
    else {
        $('body').append('<div id="ModalBoxInside112" style="top:0px; left:0px; "width:"+POPUPWidth+"px !important;Height:"+POPUPHeight+"px "+"!important"><iframe id="ifrm11" frameborder="0" style="width:100%; height:100%;" Src=' + PageName + '&Master_Popup=POPUP></iframe></div>')
    }

    $('body').find("#ModalBoxInside112").dialog({
        display: 'block',
        modal: true,
        draggable: true,
        autoOpen: true,
        closeOnEscape: true,
        width: POPUPWidth,
        height: POPUPHeight
        , drag: function (event, ui) { }
        , drop: function (event, ui) { }
        , dragStart: function (event, ui) {
        }
        , dragStop: function (event, ui) {
            if ($('.ui-dialog')[0].offsetTop < 0 || $('.ui-dialog')[0].offsetTop >= $('body')[0].clientHeight) {
                $('.ui-dialog').css('top', '5px');
            }
            if ($('.ui-dialog')[0].offsetleft < 0 || $('.ui-dialog')[0].offsetleft >= $('body')[0].clientWidth) {
                $('.ui-dialog').css('left', '5px');
            }

        }
        , open: function (event, ui) {

            $(".ui-widget-overlay").css({
                background: "rgb(50, 50, 50) !important",
                opacity: ".50 !important",
                filter: "Alpha(Opacity=50) !important",
            });

            wleft = Number(Math.abs($(window)[0].innerWidth - ($('.ui-dialog').width())) / 6.5).toFixed(0);
            if (($(window)[0].innerHeight - 50) >= $('.ui-dialog').height()) {
                wtop = Number(Math.abs($(window)[0].innerHeight - $('.ui-dialog').height()) / 2).toFixed(0) - 45;
            } else {
                wtop = Number($(window)[0].innerHeight / 4).toFixed(0);
            }
            // $('.ui-dialog').css({ "position": "fixed", "left": wleft + 'px', "top": Math.abs(wtop) + 'px', "max-width": "max-content", "max-height": "max-content" });
            $('.ui-dialog').css({ "position": "fixed", "left": "95px", "top": "50px", "max-width": "max-content", "max-height": "max-content" });
            $('.ui-dialog.ui-dialog-content').css({ "left": "0px", "top": "20px" });


            $(document).keyup(function (e) {
                if (e.keyCode == 27) {

                    $('body').find("#ModalBoxInside112").dialog("close");
                    e.preventDefault();
                }
            });


            //Updated by Shekhar L @26-Aug-2021 
            $('iframe').on("load", function () {
                //Updated by Shekhar L @01-Sep-2021
                if (window.localStorage.getItem('FinIQTheme') != null) {
                    if ($(document).find('iframe').length > 0) {
                        //debugger
                        $(document).find('iframe').each(function (i, elem) {
                            $($(elem).context.contentDocument).find('link[type="text/css"][id$="ctl00_FinIQTheme"], link[type="text/css"][href*="Style1"]').attr('href', '../App_Themes/' + (window.localStorage.getItem('FinIQTheme') == null ? "Style1" : window.localStorage.getItem('FinIQTheme')) + '.css');
                        });
                    }
                }
            });
        }
        , beforeClose: function (event, ui) {

            /* Added by Arati K to show window scroll on 15 Jan 2020 */
            var html = jQuery('html');
            var scrollPosition = html.data('scroll-position');
            html.css('overflow', html.data('previous-overflow'));
            window.scrollTo(scrollPosition[0], scrollPosition[1]);
            $("body").css({ 'overflow': html.data('previous-overflow') });

        }
        , close: function (event, ui) {
            //  $('body input[id="ctl00_hdnIsIframePopUpOpen"]').click();
            if ($('[id$="UpdateProgress1"]').css('display') == 'none') {
                //$('[id$="btnProductSearch"]').click(); //This is implemented to load workflow blotter on popup close
            }
        }

    });
}
//Aditya B || 04-Feb-2020 || For Workbench || End

function ShowPopup1(message) {
    $(function () {

    });
};
//<Start= Added by Pranjali K/Joel D on 18th Feb 2020 | Resizeable grid rows| Reported  by Omkar Tapkire>

function whatifGridAlignment() {
    $('#ctl00_MainContent_oUCPWhatIF_dgvCurveDetails').find('tr').each(function (index) {
        $($('#ctl00_MainContent_oUCPWhatIF_dgvRecord').find('tr')[index].children[0]).height($('#ctl00_MainContent_oUCPWhatIF_dgvCurveDetails').find('tr')[index].children[0].offsetHeight);
    });
}
//<End= Added by Pranjali K/Joel D on 18th Feb 2020 | Resizeable grid rows| Reported  by Omkar Tapkire>

/* start 27-Mar-2029 moved from master page by Shekhar */

//Added By RizwanS on 22-Jan-2020 // News Feed

function closeSideNav() {
    try {
        document.getElementsByClassName("NewsPopup")[0].style.display = "none"
        document.getElementsByClassName("NewsPopup")[1].style.display = "none"
        NotifyFlag == false;

    } catch (error) { console.log(error.message); }
}

// END





function getNotificationCountForUser() {
    try {
        return true;        //Added by BhagyashriB on 12-APr-2022 for BBVA SOLAR | As discussed with AkshayD
        var newsURL = location.origin + "/finiqwebapp/News_Twitter/News_Twitter.aspx/getNotificationCountForUser";
        if ($("#ctl00_hdnUserNameForNotification").val() != null) {
            l_id = $("#ctl00_hdnUserNameForNotification").val().trim();
        } else {
            l_id = '0';
        }
       
        $.ajax({

            type: "POST",
            url: newsURL,
            data: JSON.stringify({ "LoginID": l_id }),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            crossDomain: true,
            async: true,
            success: function (data) {

                var obj = jQuery.parseJSON(data.d);

                if (obj != null) {
                    $("#notificationCount").html(obj);
                }

            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                console.log("Error while fetching  news " + errorThrown);

            }
        });
    } catch (error) {
        console.log(error.message);

    }

}

function clearNotificationCountForUser() {
    try {

        var newsURL = window.location.origin + "/finiqwebapp/News_Twitter/News_Twitter.aspx/clearNotificationCount";

        $.ajax({

            type: "POST",
            url: newsURL,
            data: JSON.stringify({ "LoginID": $("#ctl00_hdnUserNameForNotification").val().trim() }),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            crossDomain: true,
            async: true,
            success: function (data) {

                var obj = jQuery.parseJSON(data.d);
                $("#notificationCount").html(0);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                console.log("Error while fetching  news " + errorThrown);


            }
        });
    } catch (error) {
        console.log(error.message);

    }

}

function getNewsCount() {
    try {
        return false;
        var newsURL = location.origin + "/finiqwebapp/News_Twitter/News_Twitter.aspx/getNewsDetails";

        $.ajax({

            type: "POST",
            url: newsURL,
            data: {},
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            crossDomain: true,
            async: true,
            success: function (data) {

                var obj = jQuery.parseJSON(data.d);

                var str = "";
                var strFooter = "";
                $(obj).each(function (i, ele) {

                    str = str + "<div class='newsheader'> <span class='newsText'>" + ele.Headline + "</span></div><div class='triangleNewsInfo'></div><div class=''></div><div class='NewsBrodcaster'><span class='news-user'>" + ele.News_Publish_By + "</span></div><div class='NewsUpdatedAt'><span class='newsTime'>" + ele.News_Publish_At + "</span></div>";
                    //   strFooter = strFooter + "<div class='divWrapper'><div class='newsFooter'> <span class='newsFooterText'>" + ele.News_Description + "</span></div><div class='newsFootertriangleNewsInfo'></div><div class=''></div><div class='newsFooterNewsBrodcaster'><span class='newsFooternews-user'>" + ele.News_Publish_By + "</span></div><div class='newsFooterNewsUpdatedAt'><span class='newsFooternewsTime'>" + ele.News_Publish_At + "</span></div></div><div class='newsSeparator'> </div>";
                    // strFooter = strFooter + "<div class='divWrapper'><div class='newsFooter'> <span class='newsFooterText'>" +"\"" + ele.News_Description +"\"" + "</span></div><div class='newsFootertriangleNewsInfo'></div><div class=''></div><div class='newsFooterNewsBrodcaster'><span class='newsFooternews-user'> - " + ele.News_Publish_By + "</span></div></div><div class='newsSeparator'> </div>";
                    strFooter = strFooter + "<div class='divWrapper'><div class='newsFooter'> <span class='newsFooterText'>" + "\"" + ele.Headline + "\"" + "</span><span class='newsFooternews-user'> - " + ele.News_Publish_By + "</span></div></div><div class='newsSeparator'> </div>";



                });

                $("#newsPanel").append(str);

                $(".NewsCount").html(obj.length);
                $("#notificationFooter").find("marquee").append(strFooter);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                console.log("Error while fetching  news " + errorThrown);


            }
        });
    } catch (error) {
        console.log(error.message);

    }

}
//Start|Added by Jassim/Mitali on 28-Apr-2020| for bonds notification changes 
function getBondsNotifCount(loginId) {
    try {
        return true;    //Added by BhagyashriB on 01-Apr-2022 for BBVA SOLAR as discussed with SheetalK
        // return false;
        var notifURL = window.location.origin + "/finiqwebapp/FinIQ_Bond_Entry/FinIQ_Bond_Entry.aspx/GetNotificationCount";

        $.ajax({

            type: "POST",
            url: notifURL,

            data: "{'L_ID':'" + loginId + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            crossDomain: true,
            async: true,
            success: function (data) {
                //
                var objData;
                $.each(data, function (key, value) {
                    tojson: var jsonData = JSON.stringify(value);
                    objData = $.parseJSON(jsonData);

                })
                //Modiefied by Mitali on 20-May-2020| to handle L ids in groups that are not notified
                if (objData != null) {
                    var count = parseInt(objData[0].Order_Blotter_NotificationCount) + parseInt(objData[0].RFQ_NotificationCount)


                    // $(document).find('#BondsNotifPopup').show();

                    $("#NotifCount").html(count);

                    //$("#notificationFooter").find("marquee").append(strFooter);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                console.log("Error while fetching  Bonds Notif Count " + errorThrown);


            }
        });
    } catch (error) {
        console.log(error.message);

    }

}

//$('body').find('div.FinIQ_Notification').height($('body').find('div.FinIQ_Notification')[0].offsetHeight + parseInt($('.FinIQ_Notification span')[0].offsetHeight));


// $('.FinIQ_Notification').draggable();







function getBondsNotifications(loginId) {
    try {
        //
        // return false;
        var notifURL = window.location.origin + "/finiqwebapp/FinIQ_Bond_Entry/FinIQ_Bond_Entry.aspx/GetNotificationPanelDetails";

        $.ajax({

            type: "POST",
            url: notifURL,

            data: "{'count':'" + "20" + "', 'dealType':'" + "ORDER" + "', 'loginID':'" + loginId + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            crossDomain: true,
            async: true,
            success: function (data) {
                //
                //var obj = jQuery.parseJSON(data.d);
                var objData;

                $.each(data, function (key, value) {
                    tojson: var jsonData = JSON.stringify(value);
                    objData = $.parseJSON(jsonData);

                })
                var str = "";
                var strFooter = "";

                for (var i = 0; i < objData.length; i++) {
                    if (objData[i].ONA_Action_Name == "NWMRFQ") { //For New RFQ Notifications
                        if (objData[i].Direction == "Buy" || objData[i].Direction == "BUY") {
                            str = str + "<div class='newsheader'> <span class='newsBondsText' onclick=\"OpenWorkflow('Manual RFQ Workflow','" + objData[i].ONA_Deal_NO + "')\">"
                            str = str + "" + objData[i].RM_Name + " has placed an indicative ask price request: " + objData[i].ONA_Deal_NO + " for bond: " + objData[i].Product_Name + " of " + objData[i].BondCcy + " " + FormatAmount(objData[i].Nominal_Amount) + " </span></div> "
                            str = str + "<div class='triangleNewsInfo'></div><div class=''></div> "
                            //str = str + "<div class='NewsBrodcaster'><span class='news-user'>" + objData[i].RM_Name + "</span></div> "
                            str = str + "<div class='NewsUpdatedAt'><span class='newsTime'>" + objData[i].ONA_Updated_At + "</span></div>";
                        }
                        else {
                            str = str + "<div class='newsheader'> <span class='newsBondsText' onclick=\"OpenWorkflow('Manual RFQ Workflow','" + objData[i].ONA_Deal_NO + "')\" >"
                            str = str + "" + objData[i].RM_Name + " has placed an indicative bid price request: " + objData[i].ONA_Deal_NO + " for bond: " + objData[i].Product_Name + " of " + objData[i].BondCcy + " " + FormatAmount(objData[i].Nominal_Amount) + " </span></div> "
                            str = str + "<div class='triangleNewsInfo'></div><div class=''></div> "
                            //str = str + "<div class='NewsBrodcaster'><span class='news-user'>" + objData[i].RM_Name + "</span></div> "
                            str = str + "<div class='NewsUpdatedAt'><span class='newsTime'>" + objData[i].ONA_Updated_At + "</span></div>";
                        }

                    }
                    else if (objData[i].ONA_Action_Name == "RESRFQ") { //For Responded RFQ Notifications
                        if (objData[i].Direction == "Buy" || objData[i].Direction == "BUY") {
                            str = str + "<div class='newsheader'> <span class='newsBondsText' onclick=\"OpenWorkflow('Manual RFQ Workflow','" + objData[i].ONA_Deal_NO + "')\">"
                            str = str + "" + objData[i].RM_Name + " has responded to an indicative ask price request: " + objData[i].ONA_Deal_NO + " for bond: " + objData[i].Product_Name + " of " + objData[i].BondCcy + " " + FormatAmount(objData[i].Nominal_Amount) + " </span></div> "
                            str = str + "<div class='triangleNewsInfo'></div><div class=''></div> "
                            //str = str + "<div class='NewsBrodcaster'><span class='news-user'>" + objData[i].RM_Name + "</span></div> "
                            str = str + "<div class='NewsUpdatedAt'><span class='newsTime'>" + objData[i].ONA_Updated_At + "</span></div>";
                        }
                        else {
                            str = str + "<div class='newsheader'> <span class='newsBondsText' onclick=\"OpenWorkflow('Manual RFQ Workflow','" + objData[i].ONA_Deal_NO + "')\">"
                            str = str + "" + objData[i].RM_Name + " has responded to an indicative bid price request: " + objData[i].ONA_Deal_NO + " for bond: " + objData[i].Product_Name + " of " + objData[i].BondCcy + " " + FormatAmount(objData[i].Nominal_Amount) + " </span></div> "
                            str = str + "<div class='triangleNewsInfo'></div><div class=''></div> "
                            //str = str + "<div class='NewsBrodcaster'><span class='news-user'>" + objData[i].RM_Name + "</span></div> "
                            str = str + "<div class='NewsUpdatedAt'><span class='newsTime'>" + objData[i].ONA_Updated_At + "</span></div>";
                        }

                    }
                    else if (objData[i].ONA_Action_Name == "AMDREQ") { //For Order Amend Request Notifications
                        str = str + "<div class='newsheader'> <span class='newsBondsText' onclick=\"OpenWorkflow('ORDER','" + objData[i].ONA_Deal_NO + "')\">"
                        str = str + "RM " + objData[i].RM_Name + " has requested for amendment of " + objData[i].Direction + " order: " + objData[i].ONA_Deal_NO + " for bond: " + objData[i].Product_Name + " of " + objData[i].BondCcy + " " + FormatAmount(objData[i].Nominal_Amount) + " </span></div> "
                        str = str + "<div class='triangleNewsInfo'></div><div class=''></div> "
                        //str = str + "<div class='NewsBrodcaster'><span class='news-user'>" + objData[i].RM_Name + "</span></div> "
                        str = str + "<div class='NewsUpdatedAt'><span class='newsTime'>" + objData[i].ONA_Updated_At + "</span></div>";

                    }

                    else if (objData[i].ONA_Action_Name == "CANREQ") { //For Order Cancel Request Notifications
                        str = str + "<div class='newsheader'> <span class='newsBondsText' onclick=\"OpenWorkflow('ORDER','" + objData[i].ONA_Deal_NO + "')\">"
                        str = str + "RM " + objData[i].RM_Name + " has requested for cancellation of " + objData[i].Direction + " order: " + objData[i].ONA_Deal_NO + " for bond: " + objData[i].Product_Name + " of " + objData[i].BondCcy + " " + FormatAmount(objData[i].Nominal_Amount) + " </span></div> "
                        str = str + "<div class='triangleNewsInfo'></div><div class=''></div> "
                        //str = str + "<div class='NewsBrodcaster'><span class='news-user'>" + objData[i].RM_Name + "</span></div> "
                        str = str + "<div class='NewsUpdatedAt'><span class='newsTime'>" + objData[i].ONA_Updated_At + "</span></div>";

                    }
                    else if (objData[i].ONA_Action_Name == "USGORD") { //For New Order Notifications
                        str = str + "<div class='newsheader'> <span class='newsBondsText' onclick=\"OpenWorkflow('ORDER','" + objData[i].ONA_Deal_NO + "')\">"
                        str = str + "RM " + objData[i].RM_Name + " has placed a new " + objData[i].Direction + " order: " + objData[i].ONA_Deal_NO + " for bond: " + objData[i].Product_Name + " of " + objData[i].BondCcy + " " + FormatAmount(objData[i].Nominal_Amount) + " </span></div> "
                        str = str + "<div class='triangleNewsInfo'></div><div class=''></div> "
                        //str = str + "<div class='NewsBrodcaster'><span class='news-user'>" + objData[i].RM_Name + "</span></div> "
                        str = str + "<div class='NewsUpdatedAt'><span class='newsTime'>" + objData[i].ONA_Updated_At + "</span></div>";
                    }
                    else if (objData[i].ONA_Action_Name == "ASGORD") {
                        str = str + "<div class='newsheader'> <span class='newsBondsText' onclick=\"OpenWorkflow('ORDER','" + objData[i].ONA_Deal_NO + "')\">"
                        str = str + objData[i].Direction + " order: " + objData[i].ONA_Deal_NO + " for bond: " + objData[i].Product_Name + " of " + objData[i].BondCcy + " " + FormatAmount(objData[i].Nominal_Amount) + " amendment has been accepted. </span></div> "
                        str = str + "<div class='triangleNewsInfo'></div><div class=''></div> "
                        //str = str + "<div class='NewsBrodcaster'><span class='news-user'>" + objData[i].RM_Name + "</span></div> "
                        str = str + "<div class='NewsUpdatedAt'><span class='newsTime'>" + objData[i].ONA_Updated_At + "</span></div>";

                    }
                    else if (objData[i].ONA_Action_Name == "CANORD") {
                        str = str + "<div class='newsheader'> <span class='newsBondsText' onclick=\"OpenWorkflow('ORDER','" + objData[i].ONA_Deal_NO + "')\">"
                        str = str + objData[i].Direction + " order: " + objData[i].ONA_Deal_NO + " for bond: " + objData[i].Product_Name + " of " + objData[i].BondCcy + " " + FormatAmount(objData[i].Nominal_Amount) + " has been cancelled. </span></div> "
                        str = str + "<div class='NewsUpdatedAt'><span class='newsTime'>" + objData[i].ONA_Updated_At + "</span></div>";
                    }

                }

                $("#BondsNotifPanel").html(str);
                $(".BondsNotifCount").html(objData.length);
                //$("#notificationFooter").find("marquee").append(strFooter);

                // createNotificationBox($('#BondsNotifPanel .newsheader:first-child > span.newsBondsText').text());
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                console.log("Error while fetching  Bonds Notification " + errorThrown);


            }
        });
    } catch (error) {
        console.log(error.message);

    }

}
function OpenWorkflow(WorkflowCode, DealNo) {
    //
    var WorkflowName;
    if (WorkflowCode == "Pri Mkt Order Blotter") {
        WorkflowName = "Primary Market Orders";
    }
    else if (WorkflowCode == 'Manual RFQ Workflow') {
        WorkflowName = "Special Price Request Blotter (Bonds)";		//Modified by Mitali for rfq notification click issue to open rfq blotter|16-Sep-2020
    }
    else if (WorkflowCode == "ORDER") {
        WorkflowName = "Bond Order Blotter";
    }
    else if (WorkflowCode == "Bond Deal Workflow") {
        WorkflowName = "Bond Trades Blotter";
    }
    var PopUpPath = $("#ctl00_Hdn_Popup_Path").val();
    if (PopUpPath.indexOf("Master_Popup=POPUP") == -1) {
        //alert("not a popup");
        //window.open('../Workflow/Trade_Workflow_Blotter.aspx?Fixed Income - Workflow Blotter&Mode=CST&csrfToken=' + $("#ctl00_hdncsrfToken").val() + '&NotificationWorkflowName=' + WorkflowName + '&RefID=' + DealNo , '_self');
        //Modified by Mitali on 07 Aug 2020| to handle incorrect redirection to Workflow Blotter Transactions
        //window.open($('.FinIQ_Menu ul li ul li a:contains("Workflow Blotter")').attr('href') + '&NotificationWorkflowName=' + WorkflowName + '&RefID=' + DealNo, '_top', '');
        window.open($('.FinIQ_Menu ul li ul li a:not(a:contains("Workflow Blotter Transactions")):contains("Workflow Blotter")').attr('href') + '&NotificationWorkflowName=' + WorkflowName + '&RefID=' + DealNo, '_top', '');
    }
}
//End|Added by Jassim/Mitali on 28-Apr-2020| for bonds notification changes  

function FinIQ_Notify(msgText, msgType) {
    //alert(msgText);
    if (msgText != undefined || msgText != '' || msgText != '-') {
        $("#notifyBox span").html(msgText);
        //alert("1");
        $(document).ready(function () {
            //alert("1");
            $("#notifyBox").removeClass().addClass('notify').addClass(msgType);

            $(".notify").hide();

            setTimeout(function () {
                $(".notify").show('fade', options, 100);
            }, 500);

        });
    }
    else {
        Notify_Close();
    }
}
//Added by Arshad K on 6 April 2016 for replaceAll
/*String.prototype.replaceAll = function (search, replacement) {
    var target = this;
    return target.replace(new RegExp(search, 'g'), replacement);
};
*/
function Notify_Close() {
    //alert("2");
    var closeme = $(this).parent();
    setTimeout(function () {
        $(closeme).hide('fade', options, 100);
    }, 500);
}


function setDefault() {
    document.getElementById("ctl00_hdnPageFontFam").value = "Verdana";
    document.getElementById("ctl00_hdnPageFontSize").value = "12";
    document.getElementById("ctl00_hdnPageFontColor").value = "000000";
    document.getElementById("ctl00_hdnPageBackColor").value = "FFFFFF";
    document.getElementById("ctl00_hdnMenuFontFam").value = "Verdana";
    document.getElementById("ctl00_hdnMenuFontSize").value = "12";
    document.getElementById("ctl00_hdnMenuFontColor").value = "FFFFFF";
    document.getElementById("ctl00_hdnMenuBackColor").value = "02754E";
    document.getElementById("ctl00_hdnInputFontColor").value = "000000";
    document.getElementById("ctl00_hdnInputBackColor").value = "EDEDED";
    setProps();
}

function setProps() {
    document.getElementById("txtPageFontFam").value = document.getElementById("ctl00_hdnPageFontFam").value;
    document.getElementById("txtPageFontSize").value = document.getElementById("ctl00_hdnPageFontSize").value;
    document.getElementById("txtPageFontColor").value = document.getElementById("ctl00_hdnPageFontColor").value;
    document.getElementById("txtPageBackColor").value = document.getElementById("ctl00_hdnPageBackColor").value;
    document.getElementById("txtMenuFontFam").value = document.getElementById("ctl00_hdnMenuFontFam").value;
    document.getElementById("txtMenuFontSize").value = document.getElementById("ctl00_hdnMenuFontSize").value;
    document.getElementById("txtMenuFontColor").value = document.getElementById("ctl00_hdnMenuFontColor").value;
    document.getElementById("txtMenuBackColor").value = document.getElementById("ctl00_hdnMenuBackColor").value;
    document.getElementById("txtInputFontColor").value = document.getElementById("ctl00_hdnInputFontColor").value;
    document.getElementById("txtInputBackColor").value = document.getElementById("ctl00_hdnInputBackColor").value;
    storeProps();
}


function storeProps() {
    $(document).ready(function () {
        if (!typeof PageLoad_RMW == 'function') {
            fontName = document.getElementById("txtPageFontFam").value;
            fontSize = document.getElementById("txtPageFontSize").value + "px";
            fontColor = "#" + document.getElementById("txtPageFontColor").value + " !important";
            backColor = "#" + document.getElementById("txtPageBackColor").value + " !important";
            fontMenuName = document.getElementById("txtMenuFontFam").value;


            fontMenuSize = document.getElementById("txtMenuFontSize").value + "px";
            fontMenuColor = "#" + document.getElementById("txtMenuFontColor").value + " !important";
            backMenuColor = "#" + document.getElementById("txtMenuBackColor").value + " !important";
            fontInputColor = "#" + document.getElementById("txtInputFontColor").value + " !important";
            backInputColor = "#" + document.getElementById("txtInputBackColor").value + " !important";

            document.getElementById("ctl00_hdnPageFontFam").value = document.getElementById("txtPageFontFam").value;
            document.getElementById("ctl00_hdnPageFontSize").value = document.getElementById("txtPageFontSize").value;
            document.getElementById("ctl00_hdnPageFontColor").value = document.getElementById("txtPageFontColor").value;
            document.getElementById("ctl00_hdnPageBackColor").value = document.getElementById("txtPageBackColor").value;
            document.getElementById("ctl00_hdnMenuFontFam").value = document.getElementById("txtMenuFontFam").value;
            document.getElementById("ctl00_hdnMenuFontSize").value = document.getElementById("txtMenuFontSize").value;
            document.getElementById("ctl00_hdnMenuFontColor").value = document.getElementById("txtMenuFontColor").value
            document.getElementById("ctl00_hdnMenuBackColor").value = document.getElementById("txtMenuBackColor").value
            document.getElementById("ctl00_hdnInputFontColor").value = document.getElementById("txtInputFontColor").value
            document.getElementById("ctl00_hdnInputBackColor").value = document.getElementById("txtInputBackColor").value

            //shekhar 29-May-2019
            $('.lbl,.ddl,.btn:not(.btnMargin, .LPDisableLink), .txt, input:not(.btnMargin, .LPDisableLink), label, textarea, select').css({ 'font-family': fontName, 'font-size': fontSize, 'color': fontColor });
            $('span, label, select').css({ 'font-family': fontName, 'font-size': fontSize });
            $('td, th').css({ 'font-family': fontName, 'font-size': fontSize });
            $('.txt, input:not(.btnMargin, .LPDisableLink), textarea, select, .ddl, .btn').css({ 'color': fontInputColor, 'background-color': backInputColor })
            $('.FinIQ_MenuBG ul li a, .FinIQ_lblFormName, .FinIQ_lblUser').css({ 'font-family': fontMenuName, 'color': fontMenuColor, 'font-size': fontMenuSize });
            $('body, th').css({ 'background-color': backColor });
            $('.FinIQ_lblFormName').css({ 'color': fontColor });
            $('.FinIQ_MenuBG, .strip2, .FinIQ_lblUser').css({ 'background-color': backMenuColor });
            $('.FinIQ_MenuBG UL li UL > li a ').css({ 'color': 'black' });
            $(".FinIQ_MenuBG ul li a").hover(function (e) {
                $(this).css("background-color", backMenuColor);
            }, function () {
                $(this).css("background-color", "");
            });
        }
    });
}


function copyColor(id) {
    var val = id.value;
    document.getElementById("ctl00_hdnCopyColor").value = val;
}

function pasteColor(id, call) {
    // 
    id.value = document.getElementById("ctl00_hdnCopyColor").value;
    colorChange(id, call)
}


function selectChange(id, call) {
    var val = id.value;
    if (call == "Page") {
        fontName = document.getElementById("txtPageFontFam").value;
        $('.lbl, .txt, input, .ddl, span, label, .btn, th, tr, textarea, select').css({ 'font-family': fontName });
        document.getElementById("ctl00_hdnPageFontFam").value = fontName;
    }
    else {
        fontMenuName = document.getElementById("txtMenuFontFam").value;
        $('.FinIQ_MenuBG ul li a, .FinIQ_lblFormName, .FinIQ_lblUser').css({ 'font-family': fontMenuName })
        document.getElementById("ctl00_hdnMenuFontFam").value = fontMenuName;
    }
}

function plusFontSize(id, call) {
    var val = parseInt(id.value);
    var val = val + 1;
    id.value = val;
    if (call == "Page") {
        fontSize = document.getElementById("txtPageFontSize").value + "px";
        $('.lbl, .txt, input, .ddl, span, label, .btn, th, tr, textarea, select').css({ 'font-size': fontSize });
        document.getElementById("ctl00_hdnPageFontSize").value = document.getElementById("txtPageFontSize").value;
    }
    else {
        fontMenuSize = document.getElementById("txtMenuFontSize").value + "px";
        document.getElementById("ctl00_hdnMenuFontSize").value = document.getElementById("txtMenuFontSize").value;
        $('.FinIQ_MenuBG ul li a, .FinIQ_lblFormName, .FinIQ_lblUser').css({ 'font-size': fontMenuSize });
    }
}

function minusFontSize(id, call) {
    var val = parseInt(id.value);
    var val = val - 1;
    id.value = val;
    if (call == "Page") {
        fontSize = document.getElementById("txtPageFontSize").value + "px";
        $('.lbl, .txt, input, .ddl, span, label, .btn, th, tr, textarea, select').css({ 'font-size': fontSize });
        document.getElementById("ctl00_hdnPageFontSize").value = document.getElementById("txtPageFontSize").value;
    }
    else {
        fontMenuSize = document.getElementById("txtMenuFontSize").value + "px";
        document.getElementById("ctl00_hdnMenuFontSize").value = document.getElementById("txtMenuFontSize").value;
        $('.FinIQ_MenuBG ul li a, .FinIQ_lblFormName, .FinIQ_lblUser').css({ 'font-size': fontMenuSize });
    }
}

$('.jscolor').on('input', function () {
    //alert('Input changed');
});

function colorChange(id, call) {
    var val = id.value;
    if (call == "PageFontColor") {
        fontColor = "#" + document.getElementById("txtPageFontColor").value + " !important";


        $('.lbl, .txt, input, .ddl,  label, .btn,  th,  textarea, select').css({ 'color': fontColor });

        document.getElementById("ctl00_hdnPageFontColor").value = document.getElementById("txtPageFontColor").value;
        fontMenuColor = "#" + document.getElementById("txtMenuFontColor").value + " !important";
        $('.FinIQ_lblUser').css({ 'color': fontMenuColor });
    }
    else if (call == "MenuFontColor") {
        fontMenuColor = "#" + document.getElementById("txtMenuFontColor").value + " !important";
        document.getElementById("ctl00_hdnMenuFontColor").value = document.getElementById("txtMenuFontColor").value
        $('.FinIQ_MenuBG ul li a, .FinIQ_lblFormName, .FinIQ_lblUser').css({ 'color': fontMenuColor });
        fontColor = "#" + document.getElementById("txtPageFontColor").value + " !important";
        $('.FinIQ_lblFormName').css({ 'color': fontColor });
    }
    else if (call == "InputFontColor") {
        fontInputColor = "#" + document.getElementById("txtInputFontColor").value + " !important";
        document.getElementById("ctl00_hdnInputFontColor").value = document.getElementById("txtInputFontColor").value;
        $('.txt, input, textarea, select, .ddl, .btn').css({ 'color': fontInputColor });
    }
    else if (call == "PageBackColor") {
        backColor = "#" + document.getElementById("txtPageBackColor").value + " !important";
        document.getElementById("ctl00_hdnPageBackColor").value = document.getElementById("txtPageBackColor").value;
        $('body, th').css({ 'background-color': backColor });

        $('td.FinIQ_MenuBG table td').css({ 'background-color': $('.FinIQ_MenuBG>td').css("background-color") });
    }
    else if (call == "MenuBackColor") {

        backMenuColor = "#" + document.getElementById("txtMenuBackColor").value + " !important";
        document.getElementById("ctl00_hdnMenuBackColor").value = document.getElementById("txtMenuBackColor").value
        $('.FinIQ_MenuBG, .strip2, .FinIQ_lblUser').css({ 'background-color': backMenuColor });
        $('.FinIQ_MenuBG UL li UL > li a ').css({ 'color': 'black' });

        $(".FinIQ_MenuBG ul li a").hover(function (e) {
            $(this).css("background-color", backMenuColor);
        }, function () {
            $(this).css("background-color", "");
        });
    }
    else if (call == "InputBackColor") {
        backInputColor = "#" + document.getElementById("txtInputBackColor").value + " !important";
        document.getElementById("ctl00_hdnInputBackColor").value = document.getElementById("txtInputBackColor").value;
        $('.txt, input, textarea, select, .ddl, .btn').css({ 'background-color': backInputColor });
    }

}



function showWarpperDiv() {
    try {
        $("body").find(".Menu_FormName").find("#wrapper").each(function () {
            $(this).find("#divtri, #ctl00_FavMenu").show();
        })

    } catch (er) {
        console.log(er.message);
    }
}
//   End

function SH_News(cnt) {
    if (document.getElementById(cnt).checked == true) {
        document.getElementById('ctl00_head_sp_News').style.display = 'block';
    }
    else {
        document.getElementById('ctl00_head_sp_News').style.display = 'none';
    }
    //  $(".slidingDiv").hide(); //Commented by AshwiniP on 27112019
}

/* Added By Sudhir Mali on 22-May-2018  
  Purpose : MBB MY => For bridging purpose
  - Navigate to ECDG system (4.5) from DCI (3.5) and vice versa. */
//
function ClearSession() {
    document.getElementById('ctl00_btnClearSession').click();
}



function Called_onDocumentReady() {


    $(".notify .close").click(function () {
        //alert | success | error | warning | info | custom       
        //alert("close");
        var closeme = $(this).parent();
        setTimeout(function () {
            $(closeme).hide('fade', options, 100);
        }, 500);
    });





    try {
        SetLoading();
          SetMenuBarSize();//updated by Shekhar L @29-Sep-2021 
        //Changed by Ashutosh.A|| 23-Feb-2021 || Change contains to include || Consulted with neeral for the same. 
        //Added By neeral on 11-Feb-2021 verified by ShekharL
        if (window.location.pathname.indexOf("FinIQ_UCPDealEntry.aspx") <= -1) {
            $('input').removeAttr("tabindex");
            $('select').removeAttr("tabindex");
            $('a').removeAttr("tabindex");
            $('img').removeAttr("tabindex");
            $('textarea').removeAttr("tabindex");
        }

        //Start Added By Shraddha D on 27-Aug-2019 for currency Popup
        $(".Grid").find("a").each(function () {
            $(this).on("click", function (e) {
                try {
                    var x = e.pageX - this.offsetLeft;
                    var y = e.pageY - this.offsetTop;
                    localStorage.setItem("x", Number(x) + 10);
                    localStorage.setItem("y", Number(y) + 10);
                } catch (er) { }
            });
        });


        if ($(".PopupCcy")[0] != undefined) {
            if (localStorage.getItem("x") != "" && $(".PopupCcy")[0].className.includes("SpreadEngine")) {
                x = localStorage.getItem("x");
                y = localStorage.getItem("y");

                var screen_width = window.innerWidth;
                var screen_height = window.innerHeight;
                //  
                if (screen_height > (Number(y) + 245)) {
                    $(".PopupCcy").css("top", (Number(y)) + "px");
                    $(".PopupCcy").offset(top, y);
                }
                else {
                    var z = Number(y) - 245;
                    localStorage.setItem("y", z);
                    $(".PopupCcy").css("top", (Number(z) + "px"));
                    $(".PopupCcy").offset(top, z);
                }
                $(".PopupCcy").css("left", Number(x) + "px");
                $(".PopupCcy").css("margin", "");

                $(".PopupCcy").css("z-index", "9999");  //saurabh.p 06-May-2020 popup overlap issue
            }
        }

        //End Added By Shraddha D on 27-Aug-2019 for currency Popup

        $('.Grid input[type="text"]').on("focus", function () {
            try {
                currenttxtVal = $(this).val();
                if ($(this).closest("table").hasClass("Grid") && ($(this).closest("tr").children('td:first').find('input[type="checkbox"]').length > 0)) {

                    if ($(this).closest("tr").children('td:first').find('input[type="checkbox"]').is(":checked")) {
                    }
                    else {
                        $(this).closest("tr").children('td:first').find('input[type="checkbox"]').click();
                    }
                }

            } catch (error) { console.log(error.message); }
        });



    } catch (error) { console.log(error.message); }



    if (typeof SetSorting_Filter1 == "function") {
        SetSorting_Filter1();
    }

    DropDownStyle = "Client";
    $('.ddl, select').each(function (i) {
        try {

            $("#ctl00_DropDownStyle option:selected").each(function () {
                DropDownStyle = $(this).text();
                if (DropDownStyle == "Demo") {
                    //$('.gbMasterTable').addClass('gbMasterTable2').removeClass('gbMasterTable');
                    //$('.GridHeader').addClass('GridHeader2').removeClass('GridHeader');
                    //$('.GridItem').removeClass('GridItem').addClass('GridItem GridItem2');
                }

            });

            if (DropDownStyle == "Demo") {

                w = $(this).width();
                // $(this).width(Number(Number(w) + 12) + "px");
                var onChange = $(this).attr('onchange');
                var orgDropdownStr = $(this).attr('class');
                var orgDropdown;
                if (orgDropdownStr != undefined) {
                    orgDropdown = orgDropdownStr.split(' ');
                }

                var convertMe = "Y";
                $(orgDropdown).each(function (i, ddlclass) {
                    /*if (ddlclass == "ddlNoTheme") {
                        convertMe = "N";
                    }*/
                });

                if ($(this).attr("class") !== "lstIndex") {
                    if (convertMe == "Y") {
                        if (onChange == undefined) {
                            $(this)
                                .selectmenu({
                                    style: 'popup',
                                    width: Number(w + 12),//$(this).width(),
                                    maxHeight: 150
                                });
                        }

                        else {
                            $(this)
                                .selectmenu({
                                    style: 'popup',
                                    width: Number($(this).width()) + 12,
                                    maxHeight: 150,
                                    change: function () { eval(onChange); }
                                });
                        }

                    }

                }

                else {

                }

            }
            else {

            }
        } catch (er) { console.log(er.message); }
    });

    $('input[type="text"], .txt').each(function (i, that) {
        try {
            //   console.log("input " + i);
            w = $(that).width();
            if (w > 0) {
                if (DropDownStyle == "Demo") {
                    $(that).css("box-sizing", "border-box !important");
                    //   console.log($(that).css("box-sizing"));
                    // $(this).width(Number(Number(w) + 15) + "px");
                }
                else {
                    $(that).css("box-sizing", "content-box !important");
                    //       console.log($(that).css("box-sizing"));
                    //$(this).width(Number(Number(w) - 7) + "px");
                    // $(this).width(Number(Number(w) + 5) + "px");
                }
            }
        }
        catch (er) { console.log(er.message); }
    });
    $('textarea').each(function () {
        try {
            w = $(this).width();
            if (w > 0) {
                if (DropDownStyle == "Demo") {
                    // $(this).width(Number(Number(w) + 15) + "px");
                }
                else {
                    //$(this).width(Number(Number(w) - 7) + "px");
                    // $(this).width(Number(Number(w) + 5) + "px");
                }
            }
        }
        catch (er) { console.log(er.message); }
    });



    $(".ui-datepicker-trigger").each(function (dt, dt1) {
        $(dt1).removeAttr("src");
    });




}


function SetLoading() {

    if (window.localStorage.getItem('FinIQTheme') == "All_Black") {
        $(document).find('.loading_parent').css({ "background-image": 'url("../App_Resources/All_Black/loading_1.gif")' });
    }
    $("img").each(function () {
        try {
            if ($(this).attr('src') != null) {
                var src = $(this).attr('src').split('/');
                var file = src[src.length - 1];
                if (file == "loading_ajax.gif" || file == "loading.gif" || file == "ajax-loader7.gif") {
                    //$(this).removeAttr('width').width('auto').height('20px'); Shekhar sir asked by Milind for Dubai demo 25March2021
                    $(this).removeAttr('width').width('auto').height('5px');
                    $(this).removeClass('loading_img').addClass('loading_img');
                    $(this).parent().find('span').removeClass('loading_span').addClass('loading_span');
                    $(this).parent().removeClass('loading_parent').addClass('loading_parent');

                    // $(this).parent().css({ "left": Number($('.FinIQ_lblFormName #pageName').offset().left + $('.FinIQ_lblFormName #pageName').width())+20 });
if (window.localStorage.getItem('FinIQTheme') == "All_Black") {                     
    $(this).attr('src', $(this).attr('src').replace("Ajax_loader_White", "All_Black"));
}
                }
                
            }
        } catch (er) { }
    });

}

//Updated on Mashreq by Shekhar L @28-Sep-2021
function SetMenuBarSize_Mashreq() {
    var menuWidth = $(".FinIQ_Menu ul:first-child li").outerWidth();
    var topMenuCount = $(".FinIQ_Menu ul:first li:first-child").length;
    $(".FinIQ_Menu").width("max-content");

    $('.FinIQ_Menu > ul > li').on("mouseover", function () {
        try {
            lCount = $(this).find('ul li').length;
            elems = $(this).find('ul li');

            var maxWidth = Math.max.apply(null, $(elems).map(function (i, j) {
                return $(j).width();
            }).get());
            lHeight = 30;
            wHeight = ($(window)[0].innerHeight) - 45;
            $(this).find('ul').width((maxWidth * (Math.ceil((lCount * lHeight) / wHeight))) + 20);
        } catch (er) { }
    });

}



function CallAllJS_Funs() {

    if (typeof NewsNotification == "function") {
        //  NewsNotification();
    }

    //saurabh.p 06-May-2020 removed clearing of label on pageload
    //if (typeof FinIQ_Notify == "function") {
    //    FinIQ_Notify("", "");
    //}
    if (typeof SetSorting_Filter1 == "function") {
        SetSorting_Filter1();
    }
    if (typeof ContextMenuPopup == "function") {
        ContextMenuPopup();
    }
    if (typeof SetLoading == "function") {
        SetLoading();
    }
    if (typeof SetMenuBarSize == "function") {
        SetMenuBarSize();
    }
    if (typeof SetIabIndex == "function") {
        SetIabIndex();
    }
    if (typeof PageLoad_WFLAccessControl == 'function') {
        PageLoad_WFLAccessControl();
    }
    if (typeof PageLoad_RMW == 'function') {
        PageLoad_RMW();
    }

    if (typeof SetDropdownPopup == "function") { //for icon panel in udfmetada Shekhar
        SetDropdownPopup();
    }

    if (typeof DisabledRow_DropDownColor == "function") {
        DisabledRow_DropDownColor();
    }
    if (typeof stickCopyright == "function") {
        stickCopyright();
    }
    if (typeof CheckBoxInGrid == "function") {
        CheckBoxInGrid();
    }
}

function checkWindowParent(Popup) { }
//checkWindowParent('POPUP');
/* end 27-Mar-2029 moved from master page by Shekhar */

//Aditya B || 10-Apr-2020 || Issue fixed: Switching fund smart search user control not working on funds order entry. Reported by Trupti Joshi || Start
function EnterEventFundsCode(txtAutomplete, event) {

    var path_Name = window.location.pathname;
    var myPageName = path_Name.substring(path_Name.lastIndexOf('/') + 1);

    //Aditya B || 18-Nov-2020 || For Mashreq || To hide funds details pop-up when search text is empty. || JIRA: MASINT-734 || Start  
    if ($("#FinIQ_FundsCode_txtAutomplete").val().trim() == '') {
        $("#tblFundsDetails").hide();
        return;
    }
    //Aditya B || 18-Nov-2020 || For Mashreq || To hide funds details pop-up when search text is empty. || JIRA: MASINT-734 || End

    try {
        return $.ajax({
            type: "POST",
            url: "" + myPageName + "/GetFundsDetails",
            contentType: "application/json; charset=utf-8",
            datatype: "text",
            cache: false,
            data: "{txtFundsName:'" + $("#FinIQ_FundsCode_txtAutomplete").val() + "'}",
            crossDomain: true,
            success: function (result) {
                var tbl = "<div style='overflow-y:auto;height:auto;background-color:#FFFFFF;' class='Grid'>"
                tbl += "<table class='TableSearchResult' style='cursor:default;' width=400px   >"
                tbl += "<tr><th>Fund Name(s)</th></tr>"
                $.each(result, function (key, value) {
                    var jsonData = JSON.stringify(value);
                    objData = $.parseJSON(jsonData);
                })
                if (objData === null || objData.length === 0) {
                    //alert("No funds found."); Commented by Aditya B || 18-Nov-2020
                    $("#tblFundsDetails").hide();
                    return;
                }
                else {
                    for (var i = 0; i < objData.length; i++) {
                        tbl += "<tr id='" + i + " ' class='SearchResultRow'  onClick=\"autoComplete_FundClicked(this,'" + objData[i].fundCode + "','" + objData[i].fundName + "','" + objData[i].fundCcy + "')\">";
                        tbl += "<td>" + objData[i].fundName + "</td>";
                        tbl += "</tr>";
                    }
                    tbl += "</table></div>";
                    $("#tblFundsDetails").show();
                    $("#tblFundsDetails").html(tbl);
                }
            },
            error: function (request, status, error) {
                alert(request.responseText);
            }
        });
    }
    catch (err) {
        console.log(err.message);
    }
}
function autoComplete_FundClicked(selRow, fundCode, fundName, fundCcy) {
    $("#FinIQ_FundsCode_txtAutomplete").val(fundName)
    //alert(fundCode);
    $('#FinIQ_FundsCode_hdnFundCode').val(fundCode);
    $('#FinIQ_FundsCode_hdnFundCcy').val(fundCcy);
    $("#tblFundsDetails").hide();

    //Commented & Changed by Aditya B || 03-Jun-2020 || Start 
    //Issue: Button id was null hence button click was not getting fired. Changed logic below to get the correct button id to call it's click event.
    //Issue Reported By: Febin A/Shivankan G
    //document.getElementById('<%=btnSelectFC.ClientID()%>').click();
    var btnSelect = $(selRow).parent().parent().parent().parent().parent().find("#btnSelectFC1");  //Aditya B || 30-Sep-2020 || Changed button id from "btnSelectFC" to "btnSelectFC1"  
    btnSelect.click();
    //Commented & Changed by Aditya B || 03-Jun-2020 || End
}
//Aditya B || 10-Apr-2020 || Issue fixed: Switching fund smart search user control not working on funds order entry. Reported by Trupti Joshi || End


//commented by shreyasv For signalr notifications replacement 8-jan-2021 -start  PLEASE CONTACT BONDS TEAM INCASE ANY QUERIES

//Akshika || 18-Aug-2020 || start
//function SubScribetoBondsPrices(WebSocketIP, USERID) {

//    //  

//    var TotalChkBx;
//    var Counter;
//    Counter = 0;
//    preM = 'ctl00_MainContent_';
//    secs = 0;
//    count = 0;
//    var rfqid = Math.random();

//    //Remove hardcoded IP || 23-09-2020 || Sheetalk || as asked by anand sir/PrasadP 
//    // if (WebSocketIP == '' || WebSocketIP == undefined) {
//    // WebSocketIP = "52.163.241.178";  //$("#<%=hdn_WebsocketIP.ClientID%>").val();
//    // }
//    var myPageName = path_Name.substring(path_Name.lastIndexOf('/') + 1);
//    //alert(1);
//    if (1 == 1) {
//        var prem;
//        if (rfqid == "") { }
//        else {

//            $(document).ready(function () {
//                //Change this for the pagename
//                //  
//                if (myPageName == "FinIQ_Trading_Portal_Bonds.aspx") {
//                    var wsprotocol;
//                    if (location.protocol == "http:")
//                        wsprotocol = "ws:"
//                    else if (location.protocol == "https:")
//                        wsprotocol = "wss:"
//                    else
//                        wsprotocol = "ws:"

//                    try {
//                        // ws = new WebSocket("wss://" + WebSocketIP + "/FinIQservice/WorkflowCallback.svc");  http://192.168.2.204:82/finiqservice_ws/WorkflowCallback.svc
//                        wsBondsPrices = new WebSocket("" + wsprotocol + "//" + WebSocketIP + "/FinIQService/WSCallback.svc");
//                        // alert("" + wsprotocol + "//" + WebSocketIP + "/FinIQService/WSCallback.svc");
//                    }
//                    catch (error) {
//                        //alert(error);
//                    }

//                    wsBondsPrices.onopen = function () {
//                        //alert("After Open");
//                        // alert(ws.readyState);
//                        if (wsBondsPrices.readyState == WebSocket.OPEN) {
//                            // alert('value : ' + $("#<%=hdnUserID.ClientID%>").val());
//                            //$("#<%=hdnUserID.ClientID%>").val()
//                            //   ws.send('MASTERSUBSCRIBE|' + USERID);  mdw
//                            wsBondsPrices.send('MASTERSUBSCRIBE|' + USERID);
//                            //ws.Subscribe('MASTERSUBSCRIBE|' + USERID);
//                            console.log('subscribed to bonds prices');
//                            // alert(" After Subscription");
//                        }
//                        else {
//                            //alert('Connection is closed', 'success');
//                        }
//                    };
//                    wsBondsPrices.onmessage = function (evt) {
//                        // alert('Received');
//                        //  
//                        var msg = evt.data;
//                        var strRes = JSON.parse(msg);
//                        if (wsBondsPrices.readyState == WebSocket.OPEN && strRes["MesssageType"].toUpperCase() == "SUBSCRIBE") {
//                            // alert('SUBSCRIBED');
//                        }
//                        else if (wsBondsPrices.readyState == WebSocket.OPEN && strRes["MesssageType"].toUpperCase() == "UNSUBSCRIBE") {
//                        }
//                        else if (wsBondsPrices.readyState == WebSocket.OPEN && strRes["MesssageType"].toUpperCase() == "NOTIFICATION") {
//                        }
//                        else {
//                            try {
//                                //
//                                // alert(strRes["MessageContent"]);
//                                if (myPageName == "FinIQ_Trading_Portal_Bonds.aspx") {
//                                    processWSCallbackData(strRes["MessageContent"]);
//                                }


//                                //processWSCallbackData2(strRes["MessageContent"]);
//                            }
//                            catch (Exception) { }
//                        }
//                    };
//                    wsBondsPrices.onerror = function (evt) {

//                        //  
//                        //  alert('Error with code : ' + evt.code + '', 'error');
//                    };
//                    wsBondsPrices.onclose = function (evt) {
//                        //alert('Onclose' + evt.reason);
//                        //alert('Onclose called - Event : ' + evt + ', code : ' + evt.code + ', reason : ' + evt.reason + ', wasClean : ' + evt.wasClean);
//                        SubScribetoBondsPrices(WebSocketIP, USERID);
//                    };
//                }

//                //<Start= Added by Pranjali K/Joel D on 18th Feb 2020 | Resizeable grid rows| Reported  by Omkar Tapkire>
//                whatifGridAlignment();
//                //<End= Added by Pranjali K/Joel D on 18th Feb 2020 | Resizeable grid rows| Reported  by Omkar Tapkire>

//            });
//        }

//    }
//}

//Akshika || 18-Aug-2020 || End
//commented by shreyasv For signalr notifications replacement 8-jan-2021 -end  PLEASE CONTACT BONDS TEAM INCASE ANY QUERIES




//modified SetEvent_DateControl function by Shekhar for Webpack slowness issue raised by UCP , Workflow team @10-Sep-2020
//Updated by Shekhar @04-Nov-2020 .replace(/_txtDate([^_txtDate]*)$/, '$1') reported by Nitin Narute:Customer Profile
var _DisabledWeekDays = false;
var _DateFormat = 'dd-NNN-yyyy';
var _AllowBlank = false;
var GlobalServerDate;
(function SetEvent_DateControl() {

    $(document).ready(function () {
        try {
            $.support.cors = true;

            if ($('[id$="txtDate"]:not(.txtDateTime)').length <= 0) {
                //added by Shekhar on 14-Ma-2022 added condtion for exception handling
                if (Sys != undefined || typeof (Sys) != "undefined") {
                    Sys.WebForms.PageRequestManager.getInstance().remove_endRequest(SetEvent_DateControl);//modified by ShekharL @10-Sep-2020 
                    Sys.WebForms.PageRequestManager.getInstance().add_endRequest(SetEvent_DateControl); //modified by ShekharL @10-Sep-2020
                }
            } else {
                if (GlobalServerDate == undefined) {
                    $.ajax({
                        type: 'POST',
                        url: '../FinIQ_User_Controls/FinIQ_WebMethods.aspx/GlobalServerDate',
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        crossDomain: true,
                        async: true,//(navigator.vendor == "") ? false : true,
                        success: function (data) {
                            if (data != null) {
                                GlobalServerDate = data.d;
                                $(document).ready(function () {
                                    try {
                                        if ($('[id$="txtDate"]').length > 0) {
                                            $('[id$="txtDate"]').each(function (i, j) {
                                                if ($(j).parent().parent().parent().parent().parent().find('[id$="hdnSetDefaultDate"]').val().toUpperCase() == "TRUE") {
                                                    if ($(j).val() == "") {
                                                        $(j).val(GlobalServerDate);
                                                    }
                                                }
                                            });
                                        }
                                    } catch (er) {
                                        console.log(er.message);
                                    }
                                });
                            }
                        },
                        error: function (xhr, ajaxOptions, thrownError) {
                            console.log(thrownError);
                        }
                    });
                }
                //Updated by Shekhar L @09-Dec-2021 for DateTime picker
                if ($('[id$="txtDate"]:not(.txtDateTime)').length > 0) {
                    $('[id$="txtDate"]:not(.txtDateTime)').each(function (i, j) {
                        //Condition added updated by Shekhar @23-Sep-2020 invisible and DatetimePicker datecontrols get undefined id issue on UCP, BondMaintanace, etc. page.

                        if ($($(j).parent().parent().parent().parent().parent().find('[id$="divDate"]'))[0] != undefined) {

                            _DisabledWeekDays = $(j).parent().find('[id$="hdnDisabledWeekDays"]').val();
                            _DateFormat = (($(j).parent().find('[id$="hdnDateFormat"]').val() == undefined) ? 'dd-NNN-yyyy' : $(j).parent().find('[id$="hdnDateFormat"]').val());
                            _AllowBlank = (($(j).parent().find('[id$="hdnAllowBlank"]').val() == undefined) ? false : $(j).parent().find('[id$="hdnAllowBlank"]').val());

                            window[$(j)[0].id.replace(/_txtDate([^_txtDate]*)$/, '$1') + 'Calender'] = new CalendarPopup($($(j).parent().parent().parent().parent().parent().find('[id$="divDate"]'))[0].id);
                            window[$(j)[0].id.replace(/_txtDate([^_txtDate]*)$/, '$1') + 'Calender'].showNavigationDropdowns();
                            window[$(j)[0].id.replace(/_txtDate([^_txtDate]*)$/, '$1') + 'Calender'].setDisabledWeekDays(_DisabledWeekDays);
                            //window[$(j)[0].id.replace(/_txtDate([^_txtDate]*)$/, '$1') + 'Calender'].select($(j)[0], $(j)[0].id, _DateFormat);
                            //return window[$(j)[0].id.replace(/_txtDate([^_txtDate]*)$/, '$1') + 'Calender'].checkdate($(j)[0], $(j)[0].id, _DateFormat);

                            $(this.id.replace(/_txtDate([^_txtDate]*)$/, '$1') + 'Calender').blur(function () {
                                _AllowBlank = (($(j).parent().find('[id$="hdnAllowBlank"]').val() == undefined) ? false : $(j).parent().find('[id$="hdnAllowBlank"]').val());
                                _DateFormat = (($(this).parent().find('[id$="hdnDateFormat"]').val() == undefined) ? 'dd-NNN-yyyy' : $(this).parent().find('[id$="hdnDateFormat"]').val());
                                return checkdate(this.id, this.text, _DateFormat);
                            });
                            $(j).on("click", function (event) {
                                // _AllowBlank = (($(j).parent().find('[id$="hdnAllowBlank"]').val() == undefined) ? false : $(j).parent().find('[id$="hdnAllowBlank"]').val());
                                _DateFormat = (($(this).parent().find('[id$="hdnDateFormat"]').val() == undefined) ? 'dd-NNN-yyyy' : $(this).parent().find('[id$="hdnDateFormat"]').val());
                                eval(this.id.replace(/_txtDate([^_txtDate]*)$/, '$1') + 'Calender').select(this, this.id, _DateFormat);
                                return false;
                            }).on("blur", function (event) {
                                // _AllowBlank = (($(j).parent().find('[id$="hdnAllowBlank"]').val() == undefined) ? false : $(j).parent().find('[id$="hdnAllowBlank"]').val());
                                _DateFormat = (($(this).parent().find('[id$="hdnDateFormat"]').val() == undefined) ? 'dd-NNN-yyyy' : $(this).parent().find('[id$="hdnDateFormat"]').val());
                                if ($(j).val() == "") {
                                    $(j).parent().find('[id$="hdnAllowBlank"]').val(true);
                                }
                                return checkdate(this.id, GlobalServerDate, _DateFormat);
                            }).on("focus", function () {
                                this.select();
                            });
                            if (GlobalServerDate != undefined && $(j).parent().parent().parent().parent().parent().find('[id$="hdnSetDefaultDate"]').val().toUpperCase() == "TRUE") {
                                // _AllowBlank = (($(j).parent().find('[id$="hdnAllowBlank"]').val() == undefined) ? false : $(j).parent().find('[id$="hdnAllowBlank"]').val());
                                if ($(j).val() == "") {
                                    $(j).val(GlobalServerDate);
                                }
                            }
                        }
                    });
                }
                Sys.WebForms.PageRequestManager.getInstance().remove_endRequest(SetEvent_DateControl);//modified by ShekharL @10-Sep-2020 
                Sys.WebForms.PageRequestManager.getInstance().add_endRequest(SetEvent_DateControl); //modified by ShekharL @10-Sep-2020
            }
        } catch (er) {
            console.log(er.message);
        }
    });
})();

function Anchor_Click(anchor, event) {
    try {
        _DateFormat = (($(anchor).parent().parent().find('[id$="hdnDateFormat"]').val() == undefined) ? 'dd-NNN-yyyy' : $(anchor).parent().parent().find('[id$="hdnDateFormat"]').val());
        // _AllowBlank = (($(j).parent().find('[id$="hdnAllowBlank"]').val() == undefined) ? false : $(j).parent().find('[id$="hdnAllowBlank"]').val());
        eval(anchor.id.replace('_anchor_cal', '') + 'Calender').select($(anchor).parent().parent().find('[id$="txtDate"]')[0], anchor.id, _DateFormat);
    } catch (er) {
        console.log(er.message);
    }
}

///////ADDED BY NEERAL on 31-July-2020 For multiselect dropdown control

function multiSelectCheckAllOption(element) {
    if ($(element).is(":checked")) {

        $(element).parent().parent().parent().find("[id*=chkOption]").each(function () {
            $(this).prop('checked', true);
        });
    } else {
        $(element).parent().parent().parent().find("[id*=chkOption]").each(function () {
            $(this).prop('checked', false);
        });
    }
    getSelectedValue(element);
}

function multiSelectCheckSingleOption(element) {
    if ($(element).parent().parent().parent().find("[id*=chkOption]:checked").length === $(element).parent().parent().parent().find("[id*=chkOption]").length) {

        $(element).parent().parent().parent().find("[id*=chkCheckAll]").each(function () {
            $(this).prop('checked', true);
        });
    } else {
        $(element).parent().parent().parent().find("[id*=chkCheckAll]").each(function () {
            $(this).prop('checked', false);
        });
    }

    getSelectedValue(element);
}

function getSelectedValue(element) {
    //
    var hdnSelectedValue = $(element).parent().parent().parent().parent().parent().parent().find("[id*=hdnSelectedValue]")[0];
    hdnSelectedValue.value = "";
    $(element).parent().parent().parent().find("[id*=chkOption]").each(function () {
        //  
        if ($(this)[0].checked) {
            //            hdnSelectedValue.value += "~" + $(this).parent().parent().find("[id*=lblOption]")[0].textContent;
            //hdnSelectedValue.value += $(this).parent().parent().find("[id*=lblOption]")[0].textContent + "~";  //05-Sep-2020 AkshayD to avoid first ~
            hdnSelectedValue.value += $(this).parent().parent().find("[id*=chkOption]")[0].value + "~";  //05-Sep-2020 AkshayD to avoid first ~
        }
    });

    hdnSelectedValue.value = hdnSelectedValue.value.slice(0, hdnSelectedValue.value.length - 1); //05-Sep-2020 AkshayD to avoid last ~

}

function multiSelectSearch(element) {


    $(element).parent().find("[id*=lblOption]").each(function () {
        if ($(this)[0].innerHTML.toString().toLowerCase().includes(element.value.toLowerCase())) {
            $(this).parent().parent()[0].style.display = "revert";
        } else {
            $(this).parent().parent()[0].style.display = "none";
        }
    });
}
///////ENDED BY NEERAL on 31-July-2020 For multiselect dropdown control

//// Added by Aditya Bhong ||22122020 ||Start
function multiSelectCheckSingleOption_Workbench(element) {
    if ($(element).parent().parent().parent().find("[id*=chkOption]:checked").length === $(element).parent().parent().parent().find("[id*=chkOption]").length) {

        $(element).parent().parent().parent().find("[id*=chkCheckAll]").each(function () {
            $(this).prop('checked', true);
        });
    } else {
        $(element).parent().parent().parent().find("[id*=chkCheckAll]").each(function () {
            $(this).prop('checked', false);
        });
    }

    getSelectedValue_Workbench(element);
}

function getSelectedValue_Workbench(element) {
    //
    var hdnSelectedValue = $(element).parent().parent().parent().parent().parent().parent().find("[id*=hdnSelectedValue]")[0];
    hdnSelectedValue.value = "";
    $(element).parent().parent().parent().find("[id*=chkOption]").each(function () {
        //  
        if ($(this)[0].checked) {
            //            hdnSelectedValue.value += "~" + $(this).parent().parent().find("[id*=lblOption]")[0].textContent;
            hdnSelectedValue.value += $(this).parent().parent().find("[id*=lblOption]")[0].textContent + "~";  //05-Sep-2020 AkshayD to avoid first ~
        }
    });

    hdnSelectedValue.value = hdnSelectedValue.value.slice(0, hdnSelectedValue.value.length - 1); //05-Sep-2020 AkshayD to avoid last ~

}

//Aditya B || 29-Dec-2020 || For multiselect template dropdown on workbench || Start
function multiSelectCheckAllOption_Workbench(element) {
    if ($(element).is(":checked")) {

        $(element).parent().parent().parent().find("[id*=chkOption]").each(function () {
            $(this).prop('checked', true);
        });
    } else {
        $(element).parent().parent().parent().find("[id*=chkOption]").each(function () {
            $(this).prop('checked', false);
        });
    }
    getSelectedValue_Workbench(element);
}
//Aditya B || 29-Dec-2020 || For multiselect template dropdown on workbench || End

var urlToRest = "CustomerName";

function EnterEvent(txtCustCtl, event) {
    try {
        e = event || window.event;
        event = event || window.event;
        var keyCode = event.which;
        x = $(txtCustCtl).attr("id");

        var txt = $("#" + x).val().trim();
        var term = "";
        term = txt;
        e = e || window.event;
        if (e.keyCode == 13) {
            $('form input, body').on("keypress", function (e) {
                if (e.keyCode == 13) {
                    e.stopPropagation ? e.stopPropagation() : (e.cancelBubble = true);
                    e.returnvalue = null;
                    return false;
                }
            });
            return false;
        }


        if (txt == "" && (e.keyCode == 8)) {
            //$("#" + x).attr('title', 'Customer Name :  BCFX Customer ID :  RM ID :  ');
            autocomplete_customer_clicked('', '0', '', '', '', '', '', '')
            $("#" + x).blur();
            return;
        }

        if (term == "") {
            $("#" + x).parent().find("#tbl_cust").html("");
            $("#" + x).parent().find("#tbl_cust").hide();
            if (e.keyCode == 13) {

                //$("#" + x).attr('title','Customer Name :  BCFX Customer ID :  RM ID :  ');
                autocomplete_customer_clicked('', '0', '', '', '', '', '', '')
                $("#" + x).blur();
                return;
            }
        }
        //Added By Bhavya for selection using arrow keys 02-11-19
        if (e.keyCode == 38 || e.keyCode == 40 || e.keyCode == 27 || e.keyCode == 9 || e.keyCode == 16 && e.keyCode == 9) {
            return;
        }
        else if (term.length >= 3) //Added By Bhavya for selection using arrow keys End - 02-11-19
        //if (e.keyCode == 13 || keyCode == 1)
        {
            //    EnterEventCustControl(x, txt, term, "");
            //}
            //if (e.keyCode == 13) {
            ShowPopup2(x);
            var keyCode = event.which;
            var txt = $("#" + x).val().trim();
            var term = "";
            term = txt;

            /*if (term == "") {
                $("#tbl_cust").html("");
                $("#tbl_cust").hide();

                autocomplete_clicked('', '0', '', '', '', '', '', '')
                return;
            }*/
            // 
            var path_Name = window.location.pathname;
            var myPageName = path_Name.substring(path_Name.lastIndexOf('/') + 1);
            //alert(myPageName);
            var cname = term;

            for (iSingleQoute = 0; iSingleQoute < cname.length - 1; iSingleQoute++) {
                cname = cname.replace("'", "@");
                cname = cname.replace("@", "");
                term = cname;
            }

            //for (iSingleQoute = 0; iSingleQoute < CustomerName.length - 1; iSingleQoute++) {
            //    CustomerName = CustomerName.replace("@", "'");
            //}

            //  alert(term);
            $.support.cors = true;
            $.ajax({
                type: "POST",
                url: "" + myPageName + "/FindCustomer",
                contentType: "application/json; charset=utf-8",
                dataType: "text",
                cache: false,
                data: "{'term':'" + term + "', 'Mode':'" + urlToRest + "'}",
                //data:"{}",
                crossDomain: true, //Modified Code

                //complete: function (jqXHR, status) {
                //    alert("complete: " + status + "\n\nResponse: " + jqXHR.responseText);
                //},

                success: function (data) {
                    // 
                    //var obj = jQuery.parseJSON(data.d);
                    var obj = jQuery.parseJSON(data);
                    var tbl = "<div style='overflow-y:auto;height:auto;max-height:300px;background-color:#FFFFFF;' class='Grid'>"
                    tbl += "<table class='TableSearchResult' cellpadding=1 cellspacing=1 style='border-collapse:collapse;' >"
                    tbl += "<tr><th>Customer Name</th>"
                    tbl += "<th>PAN No</th>"
                    tbl += "<th>DOC ID</th>"  // --<Javed>--Added <DOC ID> column told by Milind N.--<on 23-Dec-2016>
                    tbl += "<th>CIF NO</th>"
                    // --<Nitin>--commentted  <Risk Profile and Settlement Account> column told by Sarang J.--<on 31-Jul-2019>
                    //tbl += "<th>Risk Profile</th>"
                    //// tbl += "<th>Allocation Code</th>"
                    //tbl += "<th>Settlement Account</th></tr>";
                    // --<Javed>--Added <DOC ID> column told by Milind N.--<on 23-Dec-2016>
                    var objData;
                    $.each(obj, function (key, value) {

                        //var mydata = obj;

                        tojson: var jsonData = JSON.stringify(value);
                        objData = $.parseJSON(jsonData);
                    })


                    if (objData === null || objData.length === 0) {
                        $("#" + x).parent().find("#tbl_cust").html("");
                        $("#" + x).parent().find("#tbl_cust").hide();
                        // alert("No details found for selected customer");  //Commented by AshwiniP on 27012020 to avoid browser alerts on customer search
                        autocomplete_customer_clicked('', '0', '', '', '', '', '', '')
                        $("#" + x).blur();
                        //$("#" + x).attr('title', 'Customer Name :  BCFX Customer ID :  RM ID :  ');                                    
                        return;

                    }
                    else {
                        for (var i = 0; i < objData.length; i++) {
                            //tbl += "<tr>";
                            // alert(objData[i].CustomerName);
                            // tbl += "<tr class='SearchResultRow' onClick=\"autocomplete_clicked('" + objData[i].CustomerName + "','" + objData[i].CustomerID + "','" + objData[i].AH_CIF_No + "','" + objData[i].AH_Type_1 + "','" + objData[i].AccountNo + "','" + objData[i].AH_Doc_ID + "')\">"
                            var cname = objData[i].CustomerName;

                            for (iSingleQoute = 0; iSingleQoute < cname.length - 1; iSingleQoute++) {
                                cname = cname.replace("'", "@");
                            }
                            //alert(cname);
                            tbl += "<tr class='SearchResultRow' onclick=\"autocomplete_Customer(this,'" + cname + "','" + objData[i].CustomerID + "','" + objData[i].AH_CIF_No + "','" + objData[i].AH_Type_1 + "','" + objData[i].AccountNo + "','" + objData[i].AH_Risk_Profile_Rating + "','" + objData[i].AH_Doc_ID + "')\">" //Modified By Dinesh On 18-05-2020.


                            //   tbl += '<tr class="SearchResultRow" onclick="autocomplete_Customer("' + objData[i].CustomerName + '","' + objData[i].CustomerID + '","' + objData[i].AH_CIF_No + '","' + objData[i].AH_Type_1 + '","' + objData[i].AccountNo + '","' + objData[i].AH_Doc_ID + ' ")">';


                            //tbl += "<td>hhhhhh</td>";
                            tbl += "<td>" + objData[i].CustomerName + "</td>";
                            tbl += "<td>" + objData[i].CustomerID + "</td>";
                            tbl += "<td>" + objData[i].AH_Doc_ID + "</td>";   // --<Javed>--Added <DOC ID> column told by Milind N.--<on 23-Dec-2016>
                            tbl += "<td>" + objData[i].AH_CIF_No + "</td>";
                            // --<Nitin>--commentted  <Risk Profile and Settlement Account> column told by Sarang J.--<on 31-Jul-2019>
                            //        tbl += "<td>" + objData[i].AH_Risk_Profile_Rating + "</td>";
                            //// tbl += "<td>" + objData[i].AH_ALLOCATION_CODE + "</td>";
                            //        tbl += "<td>" + objData[i].AccountNo + "</td>";
                            // --<Nitin>--commentted  <Risk Profile and Settlement Account> column told by Sarang J.--<on 31-Jul-2019>
                            tbl += "</tr>";
                        }
                        tbl += "</table></div>";
                        $("#" + x).parent().find("#tbl_cust").html(tbl);
                        $("#" + x).parent().find("#tbl_cust").show();
                        var tbody = $(".TableSearchResult").find("tbody");
                        var selected = tbody.find("tr:nth-child(2)").addClass("selected");
                    }
                    $("#" + x).parent("#dialog2").hide();
                },

                error: function (xhr, textStatus, error) {
                    //called on ajax call error
                    // alert();
                    //  alert("Error: " + error);
                }
            });
        }
    } catch (error) {
        alert(error);
    }
}

function ShowPopup2(message) {
    $(function () {
        $("#" + x).parent("#dialog2").show();
        //$("#dialog").dialog({
        //    title: "jQuery Dialog Popup",

        //    buttons: {
        //        Close: function () {
        //            $(this).dialog('close');
        //        }
        //    },

        //    modal: true
        //});
    });
};

function autocomplete_customer_clicked(CustomerName, CustomerID, CDM_TLT_ID, AH_CIF_No, AH_ALLOCATION_CODE, AH_Type_1, AccountNo, AH_Risk_Profile_Rating, AH_Doc_ID) {
    try {
        for (iSingleQoute = 0; iSingleQoute < CustomerName.length - 1; iSingleQoute++) {
            CustomerName = CustomerName.replace("@", "'");
        }
        $('#cust_name').val(CustomerName);
        $("#" + x).val(CustomerName);

        $('#sel_cust_bcfx_id').val(CustomerID);
        // $('#sel_cust_tlt_id').val(CDM_TLT_ID);
        $('#sel_cust_rm_id').val(AH_CIF_No);
        //  $('#sel_cust_allocation_code').val(AH_ALLOCATION_CODE);
        $('#sel_cust_type').val(AH_Type_1);
        $('#sel_cust_Doc_ID').val(AH_Doc_ID);
        $('#sel_cust_Risk_Profile').val(AH_Risk_Profile_Rating);
        $("#tbl_cust").hide();
        // __doPostBack('cust_name_ValueChanged', 'ValueChanged');
        document.getElementById('<%=btnSelect.ClientID()%>').click();
    } catch (error) {
        alert(error);
    }
}

function autocomplete_Customer(selRow, CustomerName, CustomerID, CDM_TLT_ID, AH_CIF_No, AH_ALLOCATION_CODE, AH_Type_1, AccountNo, AH_Risk_Profile_Rating, AH_Doc_ID) {
    try {
        for (iSingleQoute = 0; iSingleQoute < CustomerName.length - 1; iSingleQoute++) {
            CustomerName = CustomerName.replace("@", "'");
        }
        // 
        $("#" + x).parent().find('#cust_name').val(CustomerName);
        $("#" + x).val(CustomerName);
        //cust_name_ValueChanged alert(CustomerName);
        $("#" + x).parent().find('#sel_cust_bcfx_id').val(CustomerID);
        // $('#sel_cust_tlt_id').val(CDM_TLT_ID);
        $("#" + x).parent().find('#sel_cust_rm_id').val(AH_CIF_No);
        //  $('#sel_cust_allocation_code').val(AH_ALLOCATION_CODE);
        $("#" + x).parent().find('#sel_cust_type').val(AH_Type_1);
        $("#" + x).parent().find('#sel_cust_Doc_ID').val(AH_Doc_ID);
        $("#" + x).parent().find('#sel_cust_Risk_Profile').val(AH_Risk_Profile_Rating);

        $("#" + x).parent().find("#tbl_cust").hide();
        $("#" + x).parent().find("#btnSelect").click(); //Modified By Dinesh On 18-05-2020.
        //$(selRow).closest('btnSelect').click(); //Modified By Dinesh On 18-05-2020.
        // __doPostBack('cust_name_ValueChanged', 'ValueChanged'); //Modified By Dinesh On 18-05-2020.
        //  document.getElementById('<%=btnSelect.ClientID()%>').click(); //Commented By Dinesh On 18-05-2020.
    } catch (error) {
        alert(error);
    }
}
//// Added by Aditya Bhong ||22122020 ||End

//Added by Devesh J on 17-feb-2021

function allowNominalWithMKBDecimalwithMinus(event, ctl, decimalPoint) {
    var charCode;
    var txt;
    var len;
    var dot;
    var minus;
    var m_low, b_low, k_low, m_Cap, b_Cap, k_Cap;
    if (event.shiftKey && event.keyCode == 45) { return false; }
    try {

        charCode = (event.which) ? event.which : event.keyCode;
        if (charCode == 8 || charCode == 9 || charCode == 37 || charCode == 38 || charCode == 39 || charCode == 40 || charCode == 46) {
            return true;
        }
        txt = $(ctl).val();
        len = txt.length;
        dot = txt.indexOf('.');
        minus = txt.indexOf('-');
        m_low = txt.indexOf('m');
        b_low = txt.indexOf('b');
        k_low = txt.indexOf('k');
        m_Cap = txt.indexOf('M');
        b_Cap = txt.indexOf('B');
        k_Cap = txt.indexOf('K');
        mLen = txt.split('m').length;
        kLen = txt.split('k').length;
        bLen = txt.split('b').length;
        dotLen = txt.split('.').length;
        minusLen = txt.split('-').length;
        if (((charCode > 47 || charCode < 58) && event.shiftKey) || charCode == 107) { return false; }
        if (charCode > 31 && (charCode < 45 || (charCode > 57 && charCode < 96) || charCode > 105) && charCode != 46 && (charCode != 66 && charCode != 77 && charCode != 75) && (charCode != 98) && charCode != 190 && charCode != 110 && charCode != 189 && charCode != 109) {
            return false;

        } else {

            if (charCode == 47) {
                return false;
            }
            if (m_low >= 0 && charCode == 109) {

                return false;
            }

            if (b_low >= 0 && charCode == 98) {
                return false;
            }
            if (k_low >= 0 && charCode == 107) {
                return false;
            }
            if (m_Cap >= 0 && charCode == 77) {
                return false;
            }
            if (b_Cap >= 0 && charCode == 66) {
                return false;
            }
            if (k_Cap >= 0 && charCode == 75) {
                return false;
            }
            if (dot >= 0 && charCode == 46) {
                return false;
            }
            if (minus >= 0 && charCode == 45) {
                return false;
            }

            if (event.keyCode == 65 || event.keyCode == 191 || event.keyCode == 76 || event.keyCode >= 67 && event.keyCode <= 74 || event.keyCode >= 78 && event.keyCode <= 90
                || event.keyCode >= 106 && event.keyCode < 109 || event.keyCode == 111 || event.keyCode >= 186 && event.keyCode <= 188) {
                return false
            }

            if (len > 1 && (event.keyCode == 109 || event.keyCode == 189)) {
                return false;
            }

            if (dot > 0 || minus > 0) {
                var CharAfterdot = (len + 1) - dot;
                if (CharAfterdot > (Number(decimalPoint) + 1)) {
                    if (event.keyCode == 8 || event.keyCode == 46 || event.keyCode == 75 || event.keyCode == 77 || event.keyCode == 66 || event.keyCode == 9) {
                        return true;
                    }
                    else { return false }
                    return false;
                }
            }
            if (dotLen > 1 || minusLen > 1) {
                var nextChar = event.keyCode;
                var prevChar = txt.charAt(len - 1);
                if (nextChar == 75 || nextChar == 77 || nextChar == 66 || nextChar == 109 || nextChar == 189) {
                    if (prevChar == "." && (nextChar == 75 || nextChar == 77 || nextChar == 66 || nextChar == 109 || nextChar == 189)) {
                        return false
                    }

                }

                if (nextChar == 109 || nextChar == 189 || nextChar == 75 || nextChar == 77 || nextChar == 66) {
                    if (prevChar == "-" && (nextChar == 109 || nextChar == 189 || nextChar == 75 || nextChar == 77 || nextChar == 66)) {
                        return false
                    }

                }

                if (mLen > 1 || kLen > 1 || bLen > 1) {
                    if (event.keyCode == 8 || event.keyCode == 46 || event.keyCode == 9) {

                        return true;
                    }
                    return false;
                }

                if (dotLen > 1 && (event.keyCode == 110 || event.keyCode == 190)) {
                    return false
                }

                else if (minusLen > 1 && (event.keyCode == 109 || event.keyCode == 189)) {
                    return false
                }
                else {
                    return true
                }
            }


            //if (minusLen > 1) {
            //    var nextChar = event.keyCode;
            //    var prevChar = txt.charAt(len - 1);
            //    if (nextChar == 109 || nextChar == 189 || nextChar == 75 || nextChar == 77 || nextChar == 66) {
            //        if (prevChar == "-" && (nextChar == 109 || nextChar == 189 || nextChar == 75 || nextChar == 77 || nextChar == 66)) {
            //            return false
            //        }
            //        //var CharAfterdot = event.keyCode
            //        //  //  if (CharAfterdot >=48 && CharAfterdot <=57 || CharAfterdot >=96 && CharAfterdot <=105 ) {
            //        //              if (CharAfterdot == 77 || CharAfterdot == 76 || CharAfterdot == 75) {
            //        //            return false
            //        //            }
            //        //           return false
            //        //      //  }
            //    }

            //    if (event.keyCode == 109 || event.keyCode == 189) {
            //        return false
            //    }
            //    else {
            //        return true
            //    }
            //}

            if (mLen > 1 || kLen > 1 || bLen > 1) {
                if (event.keyCode == 8 || event.keyCode == 46 || event.keyCode == 9) {

                    return true;
                }
                return false;
            }
        }
        return true;
    }
    catch (error) {
        WriteLog_Error("allowNominalWithMKBDecimalwithMinus :" + er.message);
    }
    finally {
        charCode = null;
        txt = null;
        len = null;
        dot = null;
        minus = null;
        m_low = null;
        b_low = null;
        k_low = null;
        m_Cap = null;
        b_Cap = null;
        k_Cap = null;

    }

}



function onlyNumberwithMinus(event, ctl) {
    console.log(event.type);
    var charCode;
    var txt;
    var len;
    //var dot;
    var minus;
    if (event.shiftKey && event.keyCode == 45) { return false; }
    if (event.shiftKey) { return false; } //Added by MohitM || Approved by shekhar sir || BBVAORINT-246
    try {
        //
        charCode = (event.which) ? event.which : event.keyCode
        txt = $(ctl).val();
        len = txt.length;
        //dot = txt.indexOf('.');
        minus = txt.indexOf('-');
        if (event.type == 'keypress') { //Added by MohitM || Approved by shekhar sir || BBVAORINT-246
        if (charCode == 110 || charCode == 190) {
            return false;
        }

        if (len >= 1 && (event.keyCode == 109 || event.keyCode == 189 || charCode == 45)) {
            return false;
        }

        //if (((charCode > 47 || charCode < 58) && event.shiftKey) || charCode == 107 || charCode == 109) { return false; }

        if (charCode == 8 || charCode == 9 || charCode == 37 || charCode == 38 || charCode == 39 || charCode == 40) { //added by devesh for arrow keys working on 7-Feb-2020
            return true;
        }

        //if (charCode > 31 && (charCode < 45 || (charCode > 57 && charCode < 96) || charCode > 105) && (charCode != 110 || charCode != 190) ) {
        //    return false;
        //}

        if (charCode > 31 && (event.keyCode < 48 || event.keyCode > 57) && event.keyCode != 8 && (event.keyCode != 109 || event.keyCode != 189) && charCode != 45) {
            return false;
            }
            return true;
        }
        if (event.type = 'keydown') { //Added by MohitM || Approved by shekhar || BBVAORINT-246
            if (len >= 1 && event.keyCode == 189) {
                return false;
            }
            if (event.keyCode >= 48 && event.keyCode <= 57) {
        return true;
            }
            if ((len == 0 && event.keyCode == 189) || event.keyCode == 8 || event.keyCode == 9 || charCode == 37 || charCode == 38 || charCode == 39 || charCode == 40) {
                return true;
            }
            return false;
        }
    }
    catch (error) {
        WriteLog_Error("onlyNumberwithMinus  :" + error.message);
    }
    finally {
        charCode = null;
        txt = null;
        len = null;
        // dot = null;
        minus = null;
    }
}
//ended by Devesh J on 17-feb-2021
//Added by Anand K on 20-Apr-2021
function EnterEventDealerID_New(x1, event) {

    var x = x1.id;// $(x).attr('id');

    var keyCode = event.which;
    var txt = $("#" + x).val().trim();
    var term = "";
    term = txt;

    if (term == "") {
        $("#" + x).parent().find("#tbl_cust_PS_ID").html("");
        $("#" + x).parent().find("#tbl_cust_PS_ID").hide();

        // autocomplete_clickedDealer(eval(x), '', '0', '', '', '', '', '', '')
        autocomplete_clickedDealer(x, null);  //Commented  and Added by Shekhar @01-Sep2020 and changed as per Aanad K. & Shreys V.
        return;
    }
    //updated by Shekhar @01-Sep2020 and changed as per Aanad K. & Shreys V.
    if (event.keyCode == 38 || event.keyCode == 40 || event.keyCode == 13) {
        arrowKey_txtRMSearch(x, event);
    }
    //Added by Akshika B on 11-Jan-2021 for tab key press
    else if (event.keyCode == 9) {
        return;
    }
    //Added by Akshika B on 04-jan-2021 for rm smart search
    else {

        //    if (term.length >= 3) {



        ShowPopup2();

        if (term == "") {
            $("#" + x).parent().find("#tbl_cust_PS_ID").html("");
            $("#" + x).parent().find("#tbl_cust_PS_ID").hide();

            // autocomplete_clickedDealer(eval(x), '', '0', '', '', '', '', '', '')
            autocomplete_clickedDealer(x, null);  //Commented  and Added by Shekhar @01-Sep2020 and changed as per Aanad K. & Shreys V.
            return;
        }

        var path_Name = window.location.pathname;
        var myPageName = path_Name.substring(path_Name.lastIndexOf('/') + 1);
        var CurrentRowIndex = document.getElementById('ctl00_MainContent_hdnCurrentRowIndex').value;
        var Entity_Id = '<% =oRes.LoginUserInfo.HomeEntityID %>';
        var UserId = '<% =oRes.LoginUserInfo.FinIQUserID%>';
        //var EntityID = document.getElementById('ctl00_MainContent_cboEntity').value;
        //var CurrentUser = document.getElementById('ctl00_MainContent_hdnCurrentUser').value;
        //var dropdownId = $("#" + x).parent().parent().parent().find("td:eq(2) select").attr("id");
        var datastring;
        datastring = "{'I_Entity_id':'" + Entity_Id + "', 'strsearch':'" + txt + "'}";


        $.support.cors = true;
        $.ajax({
            type: "POST",
            url: "" + myPageName + "/Get_Dealers",
            contentType: "application/json; charset=utf-8",
            dataType: "text",
            cache: false,
            data: datastring,

            crossDomain: true, //Modified Code


            success: function (data) {
                var obj = jQuery.parseJSON(data);
                var tblRM = "<div style='overflow-y:auto;height:auto;max-height:300px;background-color:#FFFFFF;width:220px;Cursor:pointer' class='Grid'>"
                tblRM += "<table class='TableSearchResult' cellpadding=1 cellspacing=1 style='border-collapse:collapse;width:220px;' >"
                tblRM += "<th> Dealer Name </th>"
                tblRM += "<th> Dealer Id </th>"
                //tblRM += "<th> PS Name </th>"
                objData = [];  // Added by Shekhar @01-Sep2020 and changed as per Aanad K. & Shreys V.


                $.each(obj, function (key, value) {
                    tojson: var jsonData = JSON.stringify(value);
                    objData = $.parseJSON(jsonData);
                })

                if (objData.length === 0) {
                    $("#" + x).parent().find("#tbl_PSID").html("");
                    $("#" + x).parent().find("#tbl_PSID").hide();
                    //alert("No details found for selected id");
                    // autocomplete_clickedDealer(eval(x), '', '0', '', '', '', '', '', '')
                    autocomplete_clickedDealer(x, null);//Commented  and Added by Shekhar @01-Sep2020 and changed as per Aanad K. & Shreys V.

                }
                else {
                    for (var i = 0; i < objData.length; i++) {
                        //  tblRM += "<tr class='SearchResultRow trHover' onClick=\"autocomplete_clickedDealer('" + x + "','" + objData[i].Rm_Name + "','" + objData[i].Rm_Id + "','" + objData[i].Rm_Id + "')\">"                       
                        tblRM += '<tr class="SearchResultRow trHover" onClick="autocomplete_clickedDealer(' + x + ', event);">'; //Commented  and Added by Shekhar @01-Sep2020 and changed as per Aanad K. & Shreys V.
                        tblRM += "<td>" + objData[i].Dealer_Host_Name + "</td>";
                        tblRM += "<td>" + objData[i].Dealer_External_ID + "</td>";
                        tblRM += "</tr>";
                    }
                    //
                    tblRM += "</table></div>";
                    $("#" + x).parent().find("#tbl_rm").html(tblRM);
                    $("#" + x).parent().find("#tbl_rm").show();
                    //
                }
                $("#" + x).parent().find("#dialogRM").hide();
                return
            },

            error: function (xhr, textStatus, error) {
            }


        });
        //Commented by Akshika B on 04-jan-2021
        //   }
    }
    return true;
};

function autocomplete_clickedDealer(x, event) {
    try {
        if (event != null) {
            if ((event || window.event).type == "click" || event.keyCode == 13) {
                if (event.target != undefined && (event.target.rowIndex || (event || window.event).target.parentElement.rowIndex) > 0) {
                    var selectedRowIndex = (event.target.rowIndex || (event || window.event).target.parentElement.rowIndex);
                    if ((objData != null || objData.length > 0) && objData[0].__type == "FinIQWebApp.SearchEngine.Dealer_Ref") {
                        Rm_Name = objData[selectedRowIndex - 1].Dealer_Host_Name;
                        Rm_Id = objData[selectedRowIndex - 1].Dealer_External_ID;
                    } else {
                        Rm_Name = '';
                        Rm_Id = '';
                    }
                    // $("#" + x).parent().find("#PS_Name").hide();
                    //$("#" + x).parent().find("#btnRMSelect").click();
                    //$("#" + x).parent().find('#hdnRMNameSmartCtrl').val(RMName)
                    //$("#" + x).parent().find('#hdnRMIDSmartCtrl').val(RMID)
                    //document.getElementById('ctl00_MainContent_hdnRMNameSmartCtrl').value = RMID
                    //document.getElementById('ctl00_MainContent_hdnRMIDSmartCtrl').value = RMName

                    // AssignValuesToAllocatedRows()
                    //var x = 0
                }
                else {
                    Rm_Name = '';
                    Rm_Id = '';
                }

                $(x).parent().find('#Dealer_Host_Name').val(Rm_Name);
                $(x).parent().find('#Dealer_External_ID').val(Rm_Id);
                $(x).val(Rm_Name);
                $(x).parent().find("#btnRMSelect2").click();
            }
            event.cancelBubble = true;
            event.returnValue = false;
        }
        return;
    } catch (er) {
        console.log(er.message);
    }
}
//End Anand K on 20-Apr-2021
//Prachi || 21-05-2021
function arrowKeyFundSearch(txtSearch) {
    var keyCode;
    var event = event || window.event;
    if (event.keyCode == 13 || event.keyCode == 38 || event.keyCode == 40 || event.keyCode == 27 || event.keyCode == 9 || event.keyCode == 16 && event.keyCode == 9) {
        return;
    }
    else {
        Fund_Search(txtSearch, event)
    }
}


function Fund_Search(txtFundSearch) {
    var path_Name = window.location.pathname;
    var myPageName = path_Name.substring(path_Name.lastIndexOf('/') + 1);
    $.support.cors = true;
    txtID = "#" + $(txtFundSearch).attr('id');
    autocompleteInput = txtID;

    $(txtID).parent().find(".tbl_cust").hide();

    var keyCode;
    var event = event || window.event;
    if (event != undefined) {
        keyCode = event.keyCode || event.which;
    }

    if (keyCode != 9) {
        $(txtID).closest('.ui-widget').find('#hdnFundCode').val("");
    }
    if ($(txtID).val().length < 1) {
        $(txtID).closest('.ui-widget').find('#hdnFundCode').val("");
        $(txtID).parent().find(".tbl_cust").hide();
    }

    $(autocompleteInput).autocomplete({
        search: function (event, ui) {
            if (event.keyCode == 13 || event.keyCode == 38 || event.keyCode == 40 || event.keyCode == 27 || event.keyCode == 9 || event.keyCode == 16 && event.keyCode == 9) { event.preventDefault(); }
        },
        minLength: 1,
        autoFocus: true,
        focus: function (event, ui) {
            $(autocompleteInput).val(ui.item.label);
            return false;
        },
        source: function (request, response) {
            $.ajax({
                type: "POST",
                url: "" + myPageName + "/GetFundsDetails",
                cache: false,
                data: "{'txtFundsName':'" + request.term + "', 'id':'" + txtID + "', maxResults: 3 }",
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                crossDomain: true,
                complete: function (XMLHttpRequest, textStatus, errorThrown) {
                },
                success: function (data) {
                    $.each(data, function (key, value) {
                        var jsonData = JSON.stringify(value);
                        objData = $.parseJSON(jsonData);
                    })

                    $('.tbl_cust').hide();
                    var tbl = "<div style='overflow-y:auto;height:auto;max-height:300px;background-color:#FFFFFF;' class='Grid sharePopup'>";
                    tbl += "<table id='mstrTable' class='tblFundSearch' cellpadding=1 cellspacing=1 style='border-collapse:collapse;' >";
                    tbl += '<tr><th><div style="width:90%; float:left; padding:3px;">Fund Code</div></th>';
                    //Changed to handle null object if no data || MASCLI-1429 || Prachi <start>
                    tbl += '<th><div style="width:80%; float:left;">Fund Name</div><div style="width:10%; float:right; padding-right:3px;" onClick=\"' + "SelectFundDetails(this,'" + 'Close' + "','" + '' + "','" + '' + "')" + '\">X</div></th>';
                    tbl += "</tr>";
                    if (objData == null || objData == undefined || objData.length === 0) {
                        $(txtID).parent().find(".tbl_cust").html('');
                        $(txtID).parent().find(".tbl_cust").hide();
                        $(txtID).parent().find("#hdnFundCode").val('');
                        $(txtID).blur(function () {
                            if ($(txtID).closest('.ui-widget').find('#hdnFundCode').val() === "") {
                                $(this).val('');
                            }
                        });

                        tbl += "<tr class='SearchResultRow'>";
                        tbl += '<td colspan="2" contentEditable="false">No details found.</td>';
                        tbl += '</tr>';
                        tbl += '</table></div>';
                        tblCust1 = $(autocompleteInput).parent().find(".tbl_cust").attr('id');
                        $("#" + tblCust1).html(tbl);
                        $("#" + tblCust1).show();
                        return;

                    }
                    //Changed to handle null object if no data || MASCLI-1429 || Prachi <end>
                    else {

                        for (var i = 0; i < objData.length; i++) {

                            if (objData[i].NoteMasterId != undefined || objData[i].NoteMasterId != null)
                                tbl += "<tr class='SearchResultRow' onClick=\"SelectFundDetails(this,'" + objData[i].fundCode + "','" + objData[i].fundName + "','" + objData[i].fundCcy + "', '" + objData[i].NoteMasterId + "')\">";
                            else
                                tbl += "<tr class='SearchResultRow' onClick=\"SelectFundDetails(this,'" + objData[i].fundCode + "','" + objData[i].fundName + "','" + objData[i].fundCcy + "', '')\">";

                            tbl += '<td contentEditable="false">' + objData[i].fundCode + '</td>';

                            if (objData[i].ISIN != undefined || objData[i].ISIN != null)
                                tbl += '<td>' + objData[i].fundName + ' ' + '(' + objData[i].ISIN + ')</td>';
                            else
                                tbl += '<td>' + objData[i].fundName + '</td>';

                            tbl += '</tr>';
                        }
                        tbl += '</table></div>';
                        tblCust1 = $(autocompleteInput).parent().find(".tbl_cust").attr('id');
                        $("#" + tblCust1).html(tbl);
                        $("#" + tblCust1).show();
                        var tbody = $(".TableShareSearchResult").find("tbody");
                        var selected = tbody.find("tr:nth-child(2)").addClass("selected");
                        $(txtID).blur(function () {
                            if ($(txtID).closest('.ui-widget').find('#hdnFundCode').val() === "") {
                                if ($(this).val() == objData[0].fundCode) {
                                    $(txtID).closest('.ui-widget').find('#hdnFundCode').val(objData[0].fundCode);
                                    $(txtID).parent().find(".btnSelectFC").click();
                                }
                            }
                        });
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    $(txtID).parent().find(".tbl_cust").hide();
                    $(txtID).blur(function () {
                        if ($(txtID).closest('.ui-widget').find('#hdnFundCode').val() === "") {
                            $(this).val('');
                        }
                    });
                },
                select: function (event, ui) {
                    if (ui.item) {
                        $('#hdnFundCode').val(ui.item.fundCode);
                        $('#hdnFundCcy').val(ui.item.fundCcy);
                    }
                }
            });
        }
    });
}


function SelectFundDetails(selRow, strFundCode, fundName, strFundCcy, sNoteMasterId) {
    if (strFundCode == 'Close') {
        $(selRow).closest('.tbl_cust').hide();
    } else {
        $(selRow).closest('.ui-widget').find('.textboxAuto').val(fundName);
        $(selRow).closest('.ui-widget').find('#hdnFundCode').val(strFundCode);
        $(selRow).closest('.ui-widget').find('#hdnFundCcy').val(strFundCcy);
        $(selRow).closest('.ui-widget').find('#hdnNoteMasterId').val(sNoteMasterId);
        $(selRow).closest('.tbl_cust').hide();
        $(autocompleteInput).focus();
        $(txtID).parent().find(".btnSelectFC").click();
    }
}

//Started by SwatiP for Autocomplete control
function lblCode_Click(element) {

    console.log("Helloooooo")
    var hdnSelectedCode = $(element).parent().parent().parent().parent().parent().parent().find("[id*=hdnSelectedCode]")[0];
    hdnSelectedCode.value = "";
    hdnSelectedCode.value = element.text
    //document.getElementById("demo").innerHTML = "Hello World";
}

function AutoCompleteSearch(element) {

     $(element).parent().parent().parent().parent().parent().find("[id*=hdnCode]").each(function () { //Changed by SwatiP on 27-9-2021 <mascli 1559>

        if ($(this)[0].innerHTML.toString().toLowerCase().includes(element.value.toLowerCase())) {
            /*         $(this).parent().parent().parent().parent().parent().find("[id*=lblOption]").parent().parent().style.display  = "revert";*/
            $(this).parent().parent().parent().parent().parent()[0].style.display = "revert"
            $(this).parent().parent()[0].style.display = "revert";
        } else {
            //$(this).parent().parent().parent().parent().parent().parent()[0].style.display = "none";
            $(this).parent().parent()[0].style.display = "none";
        }
    });
}
//swati end

//Added by SwatiP on 24-06-2021
function Closepnl_Click(element) {

    $(element).parent().parent().parent().parent().find("[id*=divAutoCompleteOptions]")[0].close;


}
// Anand K 21062021
function DisallowNegativeSign(el, event) {

    if (event.which == 45 || el.value.indexOf('-') != -1) {
        return false;

    }
    return true;
}


//to open Creditcheck pop up in center from deal Entry |  09June2021 | Updated 29thJune2021
//Verified by Shekhar sir
function CollateralWindowPopup(url, w, h) {
    try {
        var popupLeft, popupTop;
        if (window.screenLeft == 0) {
            popupLeft = screen.width / 2 - w; //window.innerWidth / 2;
            popupTop = screen.height / 2 - h;//(window.innerHeight / 2) - 100;
        }
        else {
            popupLeft = (screen.width / 2 + w) * -1; //window.innerWidth / 2;
            popupTop = screen.height / 2 - h;//(window.innerHeight / 2) - 100;
        }
        window.open(url, 'OpenPopup', 'menubar=0,status=0,scrollbars=no,resizable=yes,width=' + w + ',height=' + h + ', top=' + popupTop + ',left=' + popupLeft);
    }
    catch (e) {
        console.log('Error in CollateralWindowPopup, includes: ', e);
    }
}

//Added by Shubham Podhade on 06-Jul-2021 | Notify blotter on obj creation JS Side Support | START
function NotifyBlotterONObjectCreation(objectRefNo, LoginID, message, objType, sourceSystem, entityId) {
    try {
        var obj = {};
        obj.objectRefNo = objectRefNo;
        obj.LoginID = LoginID;
        obj.message = message;
        obj.objType = objType;
        obj.sourceSystem = sourceSystem;
        obj.entityId = entityId;
        var myPageName = 'Trade_Workflow_Blotter.aspx';
        $.support.cors = true;
        $.ajax({
            type: "POST",
            url: "" + myPageName + "/NotifyBlotterONObjectCreation",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            cache: false,
            data: JSON.stringify(obj),
            crossDomain: true,
            success: function (data) {
                //console.log('NotifyBlotterONObjectCreation AJAX Call OK');
            },
            error: function (x, e) {
                console.log('Error in AJAX' + e);
            }
        });
    } catch (error) {
        console.log("Error in NotifyBlotterONObjectCreation Common JS method: " + error);
    }
}
//Added by Shubham Podhade on 06-Jul-2021 | Notify blotter on obj creation JS Side Support | END


//Added by BhagyashriB on 13-July-2021 for accepting alphabets, numbers and space only
function allowAlphaNumericSpace(e) {

    var code = ('charCode' in e) ? e.charCode : e.keyCode;		//Changed by BhagyashriB on 26-Aug-2021 | condition for sapce removed, space will not be allowed
    if (!(code > 47 && code < 58) && // numeric (0-9)
        !(code > 64 && code < 91) && // upper alpha (A-Z)
        !(code > 96 && code < 123)) { // lower alpha (a-z)
        e.preventDefault();
    }
}
//End by BhagyashriB on 13-July-2021


//MASCLI-1459 || Prachi || 24-Sep-2021 <start>
function arrowKey_txtCIFSearch_EQ(that) {
    var tbody = $(".tblCIFSearch").find("tbody");
    var selectedEQCIF;
    selectedEQCIF = tbody.find(".selectedEQCIF");
    if (event.keyCode == 38) {
        selectedEQCIF.removeClass("selectedEQCIF");
        if (selectedEQCIF.prev().length == 0) {
            tbody.find("tr:last").addClass("selectedEQCIF");
        } else {
            selectedEQCIF.prev().addClass("selectedEQCIF");
            var scrollTP = $(".tbl_cust1").scrollTop();
            $(".tbl_cust1").scrollTop(scrollTP - 10);
        }
    }
    else if (event.keyCode == 40) {
        selectedEQCIF.removeClass("selectedEQCIF");
        if (selectedEQCIF.next().length == 0) {
            tbody.find("tr:nth-child(2)").addClass("selectedEQCIF");
            $(".tbl_cust1").scrollTop(0);
        } else {
            selectedEQCIF.next().addClass("selectedEQCIF");
            var scrollTP = $(".tbl_cust1").scrollTop();
            $(".tbl_cust1").scrollTop(scrollTP + 10);
        }
    }
    else if (event.keyCode == 13) {
        if (selectedEQCIF == undefined || selectedEQCIF.length != 0) {
            $(".selectedEQCIF").click();
            $(".tbl_cust1").hide();
        }
        else
            document.getElementById('btnSelect').click();
    }
    else if (event.keyCode == 27) {
        $(".tbl_cust1").hide();
    }
    else if (event.keyCode == 16 && event.keyCode == 9) {
        $(".tbl_cust1").hide();
    }
    else if (event.keyCode == 9) {
        $(".tbl_cust1").hide();
        debugger
        if (selectedEQCIF == undefined || selectedEQCIF.length != 0) {
            $(".selectedEQCIF").click();
            $(".tbl_cust1").hide();
        }
        else
            $(that).parent().find('[id*=btnSelect]').click()
            //document.getElementById('btnSelect').click();
    }
    else if (event.keyCode == 17 || event.keyCode == 45) {
        arrowKey_CIFSearch_EQ(that);
    }
}
function arrowKey_CIFSearch_EQ(txtSearch) {

    var keyCode;
    var event = event || window.event;
    if (event.keyCode == 13 || event.keyCode == 38 || event.keyCode == 40 || event.keyCode == 27 || event.keyCode == 9 || event.keyCode == 16 && event.keyCode == 9) {
        return;
    }
    else {
        CIF_Search_EQ(txtSearch, event)
    }
}


function CIF_Search_EQ(txtCIFSearch, event) {
    //updated by Chandrashekhar 15-Feb-2019 for bnp bond demo

    txtID = "#" + $(txtCIFSearch).attr('id');
    autocompleteInput = txtID;

    $(txtID).parent().find(".tbl_cust1").hide();
    Mode = $(txtID).parent().find('.txtCustomerMode').val();
    RMID = $(txtID).parent().find('.txtCustomerRMId').val();

    SessionID = document.getElementById('hdnSessionID').value;
    LRCMode = document.getElementById('hdnLRCMode').value;

    $(autocompleteInput).on("focus", function () { });

    var keyCode;
    var event = event || window.event;
    if (event != undefined)
        keyCode = event.keyCode || event.which;

    if (keyCode != 9)
        $(txtID).closest('.ui-widget').find('#hdn_searchcustCIFNO').val("");

    if ($(txtID).val().length < 3)
        $('.tbl_cust1').hide();

    $(autocompleteInput).autocomplete({
        search: function (event, ui) {
            if (event.keyCode == 13 || event.keyCode == 38 || event.keyCode == 40 || event.keyCode == 27 || event.keyCode == 9 || event.keyCode == 16 && event.keyCode == 9) { event.preventDefault(); }
        },
        minLength: 3,
        autoFocus: false,
        focus: function (event, ui) {
            $(autocompleteInput).val(ui.item.label);
            return false;
        },
        source: function (request, response) {
            $.support.cors = true;
            $.ajax({
                type: "POST",
                url: "../FinIQ_User_Controls/ShareSearch/WebMethod.aspx/GetCustomersWithCif",  //added by shreyas v 5-Nov-2020 Mashreq/1finiq changes to support customer CIF Search

                cache: false,
                data: "{'strSearch':'" + request.term + "', 'Mode':'" + Mode + "','sRMID':'" + RMID + "','SessionID':'" + SessionID + "','LRCMode':'" + LRCMode + "', maxResults: 3 }",
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                crossDomain: true,
                async: true,
                complete: function (XMLHttpRequest, textStatus, errorThrown) {
                },
                success: function (data) {
                    objData = jQuery.parseJSON(data.d);
                    $('.tbl_cust1').hide();
                    var objData = jQuery.parseJSON(data.d);
                    var tbl = "<div style='overflow-y:auto;height:auto;max-height:300px;;' class='Grid sharePopup'>"
                    tbl += "<table id='mstrTable' class='tblCIFSearch' cellpadding=1 cellspacing=1 style='border-collapse:collapse;' >"
                    tbl += '<tr><th><div style="width:90%; float:left; padding:3px;">CIF</div></th>'

                    //updated by Chandrashekhar 15-Feb-2019 for bnp bond demo
                    tbl += '<th><div style="width:80%; float:left; padding:3px;">Party Name</div><div style="width:10%; float:right; padding:3px;" onClick=\"' + "SelectCustomerDetails_EQ(this,'" + 'Close' + "','" + '' + "','" + '' + "','" + '' + "')" + '\">X</div></th>';
                    tbl += "</tr>";

                    //HemlataA on 31-03-2020 added null condition.
                    if (objData === null) {
                        $(txtID).closest('.ui-widget').find('#hdn_searchcustCIFNO').val("");
                        //MASCLI-908 || Prachi || 28-Sep-2021
                        //$('#<%=tbl_cust1.ClientID%>').html("");
                        //$('#<%=tbl_cust1.ClientID%>').hide();
                        $('.tbl_cust1').html('');
                        $('.tbl_cust1').hide();
                        tbl += "<tr class='SearchResultRow1'>";
                        tbl += '<td>No details found for selected Customer.</td>'; // contentEditable="true"
                        tbl += '</tr>';
                        tbl += '</table></div>';
                        tblCust1 = $(autocompleteInput).parent().find(".tbl_cust1").attr('id');
                        $("#" + tblCust1).html(tbl);
                        $("#" + tblCust1).css("display", "block");
                        return;
                    }

                    else if (objData.length === 0) {
                        $(txtID).closest('.ui-widget').find('#hdn_searchcustCIFNO').val("");
                        //MASCLI-908 || Prachi || 28-Sep-2021
                        //$('#<%=tbl_cust1.ClientID%>').html("");
                        //$('#<%=tbl_cust1.ClientID%>').hide();
                        $('.tbl_cust1').html('');
                        $('.tbl_cust1').hide();
                        tbl += "<tr class='SearchResultRow1'>";
                        tbl += '<td>No details found for selected Customer.</td>'; // contentEditable="true"
                        tbl += '</tr>';
                        tbl += '</table></div>';
                        tblCust1 = $(autocompleteInput).parent().find(".tbl_cust1").attr('id');
                        $("#" + tblCust1).html(tbl);
                        $("#" + tblCust1).css("display", "block");
                        return;
                    }
                    else {

                        console.log("start " + $.now());
                        for (var i = 0; i < objData.length; i++) {
                            if (objData[i].Type == undefined) { //Rohit P on 23-Apr-2020
                                CustType = "";
                            }
                            else {
                                CustType = objData[i].Type;//Rohit P on 23-Apr-2020
                            }
                            tbl += "<tr onClick=\"SelectCustomerDetails_EQ(this,'" + objData[i].ID + "','" + objData[i].Code + "','" + CustType + "','" + objData[i].CIF_No + "')\">";
                            tbl += '<td>' + objData[i].CIF_No + '</td>'; // contentEditable="true"
                            tbl += '<td>' + objData[i].Code + '</td>';


                            tbl += '</tr>';
                            console.log(i + " || " + $.now());
                        }
                        tbl += '</table></div>';
                        console.log("append complete " + $.now());
                        tblCust1 = $(autocompleteInput).parent().find(".tbl_cust1").attr('id');
                        console.log($.now());
                        $("#" + tblCust1).html('');
                        $("#" + tblCust1).html(tbl);
                        $("#" + tblCust1).css("display", "block");
                        var tbody = $(".tblCIFSearch").find("tbody");
                        var selectedEQCIF = tbody.find("tr:nth-child(2)").addClass("selectedEQCIF");
                        //arrowKeySelection();
                    }
                    // }))
                },

                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    try {
                        tbl += "<tr  class='SearchResultRow1_new SearchResultRow1_new'>";
                        tbl += '<td>No details found for selected Customer.</td>'; // contentEditable="true"
                        tbl += '</tr>';
                        tbl += '</table></div>';
                        $(txtID).closest('.ui-widget').find('#hdn_searchcustCIFNO').val("");
                        tblCust1 = $(autocompleteInput).parent().find(".tbl_cust1").attr('id');

                        $("#" + tblCust1).html(tbl);
                        $("#" + tblCust1).css("display", "block");

                    } catch (e) {

                    }
                }
            });
        }
    });
}



function SelectCustomerDetails_EQ(selRow, strCode, strLongName, strExchangeCode, strCIF_No) {//, strExchangeName, strCcy) {
    try {
        if (strCode == 'Close') {
            $(selRow).closest('.tbl_cust1').hide();
        } else {
            $(selRow).closest('.ui-widget').find('.textboxAuto').val(strCIF_No);
            $(selRow).closest('.ui-widget').find('#hdn_searchcustCode').val(strCode);
            $(selRow).closest('.ui-widget').find('#hdn_searchcustName').val(strLongName);
            $(selRow).closest('.ui-widget').find('#hdnClientCode').val(strExchangeCode);
            $(selRow).closest('.ui-widget').find('#hdn_searchcustCIFNO').val(strCIF_No);

            //    $(selRow).closest('.ui-widget').find('#hdnClientName').val(strExchangeName);
            // $(selRow).closest('.ui-widget').find('#hdnCcy').val(strCcy);
            $(selRow).closest('.tbl_cust1').hide();
            //alert(strCode);
            $(selRow).focus();
            $(autocompleteInput).focus();
          //Change Added By Shekhar Sir|MohiniM || MASCLI-1866 || 28-Oct-2021 -Start
            //document.getElementById('btnSelect').click();
          $(selRow).closest('.ui-widget').find('[id$="btnSelect"]').click();
            //Change Added By Shekhar Sir|MohiniM || MASCLI-1866 || 28-Oct-2021 -End
            //$(this).parent().find(".btntxtCustomerSearch").click();
            // var tempclick = $("input[id$='btntxtCustomerSearch']")[0].id
            // $("#"+tempclick).click()
        }
    } catch (er) { console.log(er.message); }
}
//MASCLI-1459 || Prachi || 24-Sep-2021 <end>

//UCP pricing control <start>
var connection;
var lpArr;
var sortedAllPrices;
function connectSignalRCore() {

    try {
        if (document.getElementById('tblPostCardPricer') == undefined) {
            createEQLPTable();
        }
       
        console.log("create table complete ");
        connection = new signalR.HubConnectionBuilder()

            .withUrl("https://mapleapi.test-bestpriceexecution.com/FinIQSignalRCoreAPIBeta/NotificationHub")
            .configureLogging(signalR.LogLevel.Trace)
            .build();
       
        connection.start().catch(err => console.error(err.toString()));
       
        connection.on("ReceiveRFQStatus", (user, message) => {

            console.log("Yes, Got The Data : : ", JSON.parse(user).responseData);

            if (JSON.parse(user).responseData && JSON.parse(user).responseData.length > 0) {
                var tempArr = [];
                for (let i = 0; i < JSON.parse(user).responseData.length; i++) {
                    const price = {
                        'price': JSON.parse(user).responseData[i].DRAOUT,
                        'rfq': JSON.parse(user).responseData[i].EP_ER_QuoteRequestId,
                        'lp': JSON.parse(user).responseData[i].PP_CODE,
                        'pricingID': 0,
                        'clientyield': JSON.parse(user).responseData[i].ClientYield,
                        'maxnotional': JSON.parse(user).responseData[i].MaxNotional,
                        'minnotional': JSON.parse(user).responseData[i].MinNotional
                    };
                    tempArr.push(price);
                }

                UCPBindPrices(tempArr)
            }

        });

    } catch (e) {
        console.log("connectSignalRCore : " + e.message);
    }
}

function callHubCore(ppdDetails, globalToken) {

    try {
        console.log('ppdDetails :: ', ppdDetails)

        connection.invoke("pushToken", "DemoappOE", globalToken).catch(err => console.error(err.toString()));

        connection.invoke("SendRFQStatus", '{\"PPDetails\":\"' + ppdDetails + '\",\"UserID\": \"DemoappOE\"}').catch(err => console.error(err.toString()));

    } catch (e) {

        console.log("callHubCore : " + e.message);
    }

}

function stopSignalRConnection() {
    if(connection != null)  
        connection.stop();
}

function UCPBindPrices(res) {


    console.log("in UCPBindPrices", res, lpArr);
    for (let j = 0; j < res.length; j++) {
        if (res[j].price != 'Timeout' && res[j].price != 'Rejected' && res[j].price != 'Unsupported') {
            for (let k = 0; k < lpArr.length; k++) {
                if (res[j].rfq === lpArr[k].rfq && (lpArr[k].price != res[j].price)) {
                    lpArr[k].price = res[j].price;
                    lpArr[k].priceforsorting = res[j].price;
                    lpArr[k].clientyield = res[j].clientyield;
                    lpArr[k].maxnotional = res[j].maxnotional;
                    lpArr[k].minnotional = res[j].minnotional;
                    lpArr[k].totalTime = 300;
                    lpArr[k].formattedmaxnotional = UCPPricingFormatter(res[j].maxnotional);
                    lpArr[k].formattedminnotional = UCPPricingFormatter(res[j].minnotional);
                    lpArr[k].timer = UCPPricingStartCountDown(lpArr[k].totalTime, k);
                    $("#PRICE_" + res[j].rfq).html(res[j].price);
                    $("#ORDERBTN_" + res[j].rfq).prop('disabled',false);

                    $("#FORMATMINMAX_" + res[j].rfq).html(UCPPricingFormatter(res[j].minnotional) + " / " + UCPPricingFormatter(res[j].maxnotional));
                    $("#TIME_" + res[j].rfq).html(UCPPricingStartCountDown(lpArr[k].totalTime, k, "TIME_" + res[j].rfq));

                }
            }
        }
        else {
            for (let k = 0; k < lpArr.length; k++) {
                if (res[j].rfq === lpArr[k].rfq) {
                    // lpArr[k].price = res[j].price.split(",")[0];
                    lpArr[k].priceforsorting = 0;
                }
            }
        }

        //if (lpArr && lpArr.length > 0) {
        //    var tempArr = lpArr.filter(e => (isNaN(e.priceforsorting) == false && Number(e.priceforsorting) != 0))
        //    sortedAllPrices = (tempArr && tempArr.length > 0) ? tempArr.FCNSortBy('priceforsorting') : [];
        //    console.log("SortedAllPrice:", sortedAllPrices);
        //}

    }


    //document.getElementById('tblLP').innerHTML = "";
    //var tblMain = document.createElement('table');
    //var trMain = document.createElement('tr');


    //var arrPricing = lpArr;
    //for (var i = 0; i < arrPricing.length; i++) {

    //    var table = document.createElement('table');
    //    addControl(table, 'label', arrPricing[i]['lp'], "lpHeaderLabel");

    //    if (arrPricing[i]['timer'] == undefined) {
    //        addControl(table, 'label', "-", "lpHeaderLabel");
    //    }
    //    else
    //        addControl(table, 'label', arrPricing[i]['timer'], "lpHeaderLabel");

    //    addControl(table, 'empty', '', "");
    //    addControl(table, 'empty', '', "");
    //    debugger
    //    addControl(table, 'label', arrPricing[i]['price'], "lpHeaderLabel", arrPricing[i]['rfq']);
    //    addControl(table, 'empty', '', "");
    //    addControl(table, 'empty', '', "");
    //    addControl(table, 'hidden', arrPricing[i]['rfq'], "");
    //    addControl(table, 'empty', '', "");

    //    addControl(table, 'button', 'Order', "btn FinIQ_MenuBG order-button");
    //    if (arrPricing[i]['formattedminnotional'] == undefined || arrPricing[i]['formattedmaxnotional'] == undefined) {
    //        addControl(table, 'label', "", "lpHeaderLabel");
    //    }
    //    else {
    //        addControl(table, 'label', arrPricing[i]['formattedminnotional'] + " / " + arrPricing[i]['formattedmaxnotional'], "lpHeaderLabel");
    //    }

    //    var td = document.createElement('td');
    //    td.appendChild(table);
    //    trMain.appendChild(td);

    //    tblMain.appendChild(trMain);
    //}

    //document.getElementById('tblLP').appendChild(tblMain);

}


function createEQLPTable() {
    //debugger;
    var srfqID = $('#ctl00_MainContent_ctl11_hdnUCPPricingArray').val();
    if (srfqID == "" || srfqID == undefined) {
        return;
    }
	if ($('#ctl00_MainContent_ctl11_hdnPricingMode').val() == 'EMAIL') { return;}
    console.log(srfqID);
    const temp = srfqID.split(',');
    var arrPricing = [];
    for (let j = 0; j < temp.length; j++) {
        arrPricing.push({
            rfq: (temp[j].split('-'))[1],
            lp: (temp[j].split('-'))[0],
            price: '-',
            clientyield: '-',
            maxnotional: '',
            minnotional: '',
            timer: '-',
            pricerflag: 'false',
            priceforsorting: 0,
            clientprice: '-',
            totalTime: 0
        });
    }

    lpArr = arrPricing;
    document.getElementById('tblLP').innerHTML = "";
    var solveFor = $('#ctl00_MainContent_ctl11_hdnUCPPricingSolveFor').val();

    var tblMain = document.createElement('table');
    var trMain = document.createElement('tr');
    tblMain.id = "tblPostCardPricer";
    tblMain.className = "cardTD"
    //var arrPricing = JSON.parse(strPricing);
    for (var i = 0; i < arrPricing.length; i++) {

        var table = document.createElement('table');
        table.className = "cardTD"

        if (i==0){
       
            addSolveFor(solveFor, tblMain, trMain);
        }
        //if (arrPricing[i]['EP_BestPrice_YN'] === "Y") {
        //    table.className = "tblLPBox priceContainer best-price-container";
        //} else {
        //    table.className = "tblLPBox priceContainer";
        //}




        addControl(table, 'label', arrPricing[i]['lp'], "lpHeaderLabel", "LP_" + arrPricing[i]['rfq']);

        addControl(table, 'label', "", "", "TIME_" + arrPricing[i]['rfq']);
        //addControl(table, 'empty', '', "");

        //if (arrPricing[i]['EP_BestPrice_YN'] === "Y") {
        //    addControl(table, 'label', arrPricing[i]['EP_price'], "price lpBestPrice");
        //} else {
        addControl(table, 'label', arrPricing[i]['price'], "price", "PRICE_" + arrPricing[i]['rfq']);
        //}


        //addControl(table, 'empty', '', "");

        //addControl(table, 'label', '11.55', "lpHeaderLabel");

        //addControl(table, 'empty', '', "");
        //addControl(table, 'empty', '', "");
        //addControl(table, 'empty', '', "");
        //addControl(table, 'empty', '', "");
        //alert(arrPricing[i]['rfq']);
        addControl(table, 'hidden', arrPricing[i]['rfq'], "");
        //addControl(table, 'empty', '', "");

        //if (arrPricing[i]['EP_BestPrice_YN'] === "Y") {
        //    addControl(table, 'button', 'ORDER', "btn FinIQ_MenuBG order-button best-price");
        //} else {
        addControl(table, 'button', 'Order', "btn", "ORDERBTN_" + arrPricing[i]['rfq']);
        //}
        addControl(table, 'label', '', "", "FORMATMINMAX_" + arrPricing[i]['rfq']);


        //addControl(table, 'label', '200.0K/3.0M', "");

        var td = document.createElement('td');
        td.className = "cardTD"
        td.appendChild(table);
        trMain.appendChild(td);

        tblMain.appendChild(trMain);
    }

    document.getElementById('tblLP').appendChild(tblMain);
    callHubCore($('#ctl00_MainContent_ctl11_hdnUCPPricingArray').val(), $('#ctl00_MainContent_ctl11_hdnUCPPricingToken').val())
}



function addControl(table, controlType, value, cssClass, rfqid) {

    var control;
    var tr = document.createElement('tr');
    var td = document.createElement('td');
    td.className = "cardTD"
    //control.className = cssClass;
    switch (controlType) {
        case 'label':
            control = document.createElement('label');
            control.innerHTML = value;
            control.id = rfqid;

            break;
        case 'button':
            control = document.createElement('button');
            control.innerHTML = value;
            $(control).bind("click", function () { GetPrice(this, event) });
          
            $(control).prop('disabled', true);

            control.id = rfqid;

            break;
        case 'link':
            control = document.createElement('anchor');
            control.innerHTML = value;

            break;
        case 'empty':
            control = document.createTextNode('');
            if (rfqid != 0) {
                td.style.height = 15;
            }
            
            break;
        case 'hidden':
            control = document.createElement('hidden');
            control.value = value;
            td.style.display = "none";
            break;
        default:
    }

    control.className =cssClass;
    td.appendChild(control);
    tr.appendChild(td);
    table.appendChild(tr);
}

function GetPrice(cntrl, event) {
    try {
        var id = $(cntrl).closest('table').parent()[0].cellIndex + 1;
        var bookOrderReq = "PR_RFQ_ID:" + lpArr[id].rfq + "~lp:" + lpArr[id].lp + "~PR_Client_Price:" + lpArr[id].price + "~PR_Client_Yeild:" + lpArr[id].clientyield
       // $('#ctl00_MainContent_ctl11_hdnUCPPriceResponse').val(bookOrderReq);
        document.getElementById("ctl00_MainContent_ctl11_hdnUCPPriceResponseString").value = bookOrderReq;
        document.getElementById("ctl00_MainContent_ctl11_hdnUCPPricingArray").value = "";
        document.getElementById('ctl00_MainContent_ctl11_btnTimerLapsedUCP').click();

    }
    catch (er) { }

}
function UCPPricingStartCountDown(sec, index,ctlid) {
    let counter = sec;

    const interval1 = setInterval(() => {
        //console.log( counter);  
        if (lpArr.length <= 0) {
            clearInterval(interval1);
        }
        if (counter < 0) {

            clearInterval(interval1);

        };

        if (lpArr.length > 0 && counter == 0) {
            lpArr[index].timer = '-';
            $("#" + ctlid).html('-');
            if (ctlid != null) {
                var rfq = "#ORDERBTN_" + ctlid.replace("TIME_", "");
                $(rfq).prop('disabled', true);
            }
            clearInterval(interval1);
            //counter--;
        }

        if (lpArr.length > 0 && counter > 0) {
            lpArr[index].timer = counter;
            $("#" + ctlid).html(counter);
            counter--;
        }



    }, 1000);

}

function UCPPricingFormatter(num) {
    console.log("Num is: ", num)
    if (num >= 1000000000) {
        return (num / 1000000000).toFixed(1).replace(/\.0$/, '') + 'B';
    }
    if (num >= 1000000) {
        return (num / 1000000).toFixed(1).replace(/\.0$/, '') + 'M';
    }
    if (num >= 1000) {
        return (num / 1000).toFixed(1).replace(/\.0$/, '') + 'K';
    }
    return num;
}

function FCNSortBy(p) {
    try {
        if (this !== undefined) {
            if (this.length > 0) {
                if (this[0].solvefor !== 'COUPON') {
                    return this.slice(0).sort(function (a, b) {
                        return (Number(a[p]) > Number(b[p])) ? 1 : (Number(a[p]) < Number(b[p])) ? -1 : 0;
                    });

                }
                else {
                    return this.slice(0).sort(function (a, b) {
                        return (Number(a[p]) < Number(b[p])) ? 1 : (Number(a[p]) > Number(b[p])) ? -1 : 0;
                    });
                }
            }
        }

    }
    catch (error) {
        //console.log("Error:", error);
    }
};

function addSolveFor(solveFor,tblMain, trMain) {
    var table = document.createElement('table');
    table.className = "cardTD"
    addControl(table, 'empty', '', "",'0');
    addControl(table, 'empty', '', "", '0');
    addControl(table, 'label', solveFor, "", '0');
    addControl(table, 'empty', '', "", '0');
    addControl(table, 'empty', '', "", '0');
    addControl(table, 'empty', '', "", '0');
    var td = document.createElement('td');
    td.className = "cardTD"
    td.appendChild(table);
    trMain.appendChild(td);

    tblMain.appendChild(trMain);
}

////////////for email pricing////////////


intervalID = 0;
emailPriceArr = [];
function startPricing() {
    try {
       
        clearInterval(intervalID);

        intervalID = setInterval(updatePrices, 2000); // Changed by OnkarE JIRA:UWI-301

    } catch (e) {

    }
}

function stopPricing() {
    try {
        
        clearInterval(intervalID);
        If(document.getElementById('tblLP') != null)    
            document.getElementById('tblLP').innerHTML = "";
    } catch (e) {

    }
}


function updatePrices() {
    var pricingModeId = document.querySelector('[id*="hdnPricingMode"]').id; // Changed by OnkarE on 03-Mar-2022 JIRA:UWI-303
    var pricingMode = document.getElementById(pricingModeId).value; // Changed by OnkarE on 03-Mar-2022 JIRA:UWI-303
    if (pricingMode != undefined) { // Added condition by OnkarE on 03-Mar-2022 JIRA:UWI-303
    switch (pricingMode.toUpperCase()) {
        case "EMAIL":
            getEmailPrice();
            break;
        case "FX":
            // getEmailPrice();
            break;
        default:
        // code block
        }
    }
}

function getEmailPrice() {
    $.support.cors = true;
    //" + $('#ctl00_MainContent_ctl11_hdnNoteMasterId').val() + "
    $.ajax({
        type: "POST",
        url: "../FinIQ_User_Controls/UCP_PricingControl/UCP_PricingControlWebMethod.aspx/getEmailPrice",
        cache: false,
    data: "{'noteMasterID':" + $('#ctl00_MainContent_ctl11_hdnNoteMasterId').val() + ", 'callFrom':'DEALER'}",
              // data: "{'noteMasterID': '286311', 'callFrom':'DEALER'}",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        crossDomain: true,
        async: true,
        complete: function (XMLHttpRequest, textStatus, errorThrown) {
        },
        success: function (data) {
            objData = jQuery.parseJSON(data.d);
            
            for (j = 0; j < objData.length; j++) {
                if (objData.indexOf(objData[j].PP_CODE) === -1) {
                    if (emailPriceArr.some(e => e.PP_CODE == objData[j].PP_CODE)) {

                    }
                    else {
                        emailPriceArr.push(objData[j])
                        console.log("Email Price Data is: ", objData, emailPriceArr);
                    }
                }
            }
            
            var pricingArrayeId = document.querySelector('[id*="hdnUCPPricingArray"]').id; // Changed by OnkarE on 03-Mar-2022 JIRA: UWI-303
            document.getElementById(pricingArrayeId).value = data.d // Changed by OnkarE on 03-Mar-2022 JIRA: UWI-303
            //document.getElementById("ctl00_MainContent_ctl11_hdnUCPPricingArray").value = data.d;

            var tableLP = document.getElementById('pricingTr');
            if (tableLP == null) //OmkarE-26-Oct-2021  UWI-191
                createLPTable();
            else
                updateLPTable();
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            try {
            } catch (e) {
            }
        }
    });
}

function updateLPTable() {
    console.log("Updating table: ")
    var pricingArrayeId = document.querySelector('[id*="hdnUCPPricingArray"]').id; // Changed by OnkarE on 03-Mar-2022 JIRA: UWI-303
    var strPricing = document.getElementById(pricingArrayeId).value; // Changed by OnkarE on 03-Mar-2022 JIRA: UWI-303
    var arrPricing = JSON.parse(strPricing);
    var tempArr = [];
    $('#pricingTr').each(function () {
        $(this).find('td').each(function () {
            if (this.id.includes("RFQ_")) { tempArr.push(this.id.replace("RFQ_", "")) }  //OnkarE-26-Oct-2021  UWI-191
        })
    })

//OnkarE-26-Oct-2021  UWI-191
    for (let i = 0; i < arrPricing.length; i++) { 
        if (tempArr.some(e => e == arrPricing[i].ER_QuoteRequestId)) {
            $('#pricingTr').each(function () {
                $(this).find('td').each(function () {
                    if (this.id.includes("RFQ_")) {
                        if (this.id.replace("RFQ_", "") == arrPricing[i].ER_QuoteRequestId)
                            $(this).find('td').each(function () {
                                if (this.id.includes("PRICE_")) {
                                    if (this.id.replace("PRICE_", "") != arrPricing[i].EP_price) {
                                        $(this).find('label').each(function () {
                                            this.id = "PRICE_" + arrPricing[i].EP_price;
                                            this.innerHTML = arrPricing[i].EP_price;
                                        })
                                    }
                                }
                            })
                    }
                })
            })
        }
        else {
            BindUpdatedTd(arrPricing[i].ER_QuoteRequestId)
        }
    }
    for (j = 0; j < arrPricing.length; j++) {
        for (k = 0; k < emailPriceArr.length; k++) {
            if (arrPricing[j].ER_QuoteRequestId === emailPriceArr[k].ER_QuoteRequestId && (emailPriceArr[k].EP_price != arrPricing[j].EP_price)) {
                emailPriceArr[k].EP_price = arrPricing[j].EP_price;
                $("#PRICE_" + arrPricing[j].ER_QuoteRequestId).html(arrPricing[j].EP_price);
            }
        }
//OnkarE-26-Oct-2021  UWI-191
        var td = document.getElementById("RFQ_" + arrPricing[j]['ER_QuoteRequestId']);
        td.className = '';
        if (arrPricing[j].EP_BestPrice_YN == 'Y') {
            td.className = "cardTD highlightBest"
        }
        else {
            td.className = "cardTD whitebg tdUCPPricing" // Added class by OnkarE on 09-Mar-2022 JIRA:UWI-301
        }
    }
}

function BindUpdatedTd(rfqId) {
    var priceObj = emailPriceArr.filter(e => e.ER_QuoteRequestId == rfqId)[0];
    var table = document.createElement('table');
    if (priceObj['EP_BestPrice_YN'] === "Y") { // Changed by OnkarE on 11-Mar-2022 UWI-303
        addEmailPriceControl(table, 'label', priceObj['PP_CODE'], "lpBestPriceLabel", "", "LP_" + priceObj['PP_CODE']);
    } else {
    addEmailPriceControl(table, 'label', priceObj['PP_CODE'], "lpHeaderLabel", "", "LP_" + priceObj['PP_CODE']);
    }
    if (priceObj['EP_BestPrice_YN'] === "Y") {
        addEmailPriceControl(table, 'label', priceObj['EP_price'], "bestPrice", "", "PRICE_" + priceObj['EP_price']); // Changed by OnkarE on 11-Mar-2022 UWI-303
    } else {
        addEmailPriceControl(table, 'label', priceObj['EP_price'], "price", "", "PRICE_" + priceObj['EP_price']);
    }
    addEmailPriceControl(table, 'label', priceObj['ER_QuoteRequestId'], "", "", "RFQ_" + priceObj['ER_QuoteRequestId']);
    addEmailPriceControl(table, 'empty', '', "");
    if (priceObj['EP_BestPrice_YN'] === "Y") {
        addEmailPriceControl(table, 'button', 'Order', "btn bestPriceBtn", "", priceObj["ER_QuoteRequestId"]); // Changed by OnkarE on 11-Mar-2022 UWI-303
    } else {
        addEmailPriceControl(table, 'button', 'Order', "btn", "", priceObj["ER_QuoteRequestId"]); 
    }
    var td = document.createElement('td');
    td.id = "RFQ_" + priceObj['ER_QuoteRequestId'];
    if (priceObj.EP_BestPrice_YN == 'Y') {
        td.className = "cardTD highlightBest"
    }
    else {
        td.className = "cardTD tdUCPPricing whitebg"  //OnkarE-26-Oct-2021  UWI-191
    }
    td.appendChild(table);
    var trMain = document.getElementById("pricingTr");
    trMain.appendChild(td);
}

function createLPTable() {

    if (document.getElementById('tblLP') != null)   
        document.getElementById('tblLP').innerHTML = "";
    var tblMain = document.createElement('table');
    var trMain = document.createElement('tr');
    trMain.id = "pricingTr"
    tblMain.className = "cardTD"

    var pricingArrayeId = document.querySelector('[id*="hdnUCPPricingArray"]').id; // Changed by OnkarE on 03-Mar-2022 JIRA: UWI-303
    var strPricing = document.getElementById(pricingArrayeId).value; // Changed by OnkarE on 03-Mar-2022 JIRA: UWI-303
    //var strPricing = document.getElementById("ctl00_MainContent_ctl11_hdnUCPPricingArray").value;
    var arrPricing = JSON.parse(strPricing);
    for (var i = 0; i < arrPricing.length; i++) {

        if (i == 0) {

            addSolveForEmail(tblMain, trMain);
        }

        var table = document.createElement('table');

        if (arrPricing[i]['EP_BestPrice_YN'] === "Y") { // Changed by OnkarE on 11-Mar-2022 UWI-303
            addEmailPriceControl(table, 'label', arrPricing[i]['PP_CODE'], "lpBestPriceLabel", "", "LP_" + arrPricing[i]['PP_CODE']);
        } else {
        addEmailPriceControl(table, 'label', arrPricing[i]['PP_CODE'], "lpHeaderLabel", "", "LP_" + arrPricing[i]['PP_CODE']);
        }


        if (arrPricing[i]['EP_BestPrice_YN'] === "Y") {
            addEmailPriceControl(table, 'label', arrPricing[i]['EP_price'], "bestPrice", "", "PRICE_" + arrPricing[i]['EP_price']); // Changed by OnkarE on 11-Mar-2022 UWI-303
        } else {
            addEmailPriceControl(table, 'label', arrPricing[i]['EP_price'], "price", "", "PRICE_" + arrPricing[i]['EP_price']);
        }

        addEmailPriceControl(table, 'label', arrPricing[i]['ER_QuoteRequestId'], "", "", "RFQ_" + arrPricing[i]['ER_QuoteRequestId']);
        addEmailPriceControl(table, 'empty', '', "");

        if (arrPricing[i]['EP_BestPrice_YN'] === "Y") {
            addEmailPriceControl(table, 'button', 'Order', "btn bestPriceBtn ", "", arrPricing[i]["ER_QuoteRequestId"]); // Changed by OnkarE on 11-Mar-2022 UWI-303
        } else {
            addEmailPriceControl(table, 'button', 'Order', "btn", "", arrPricing[i]["ER_QuoteRequestId"]);
        }



        //addControl(table, 'label', '200.0K/3.0M', "");

        var td = document.createElement('td');
        //td.id = "td_" + arrPricing[i]['ER_QuoteRequestId'];
        td.appendChild(table);
        trMain.appendChild(td);
        td.id = "RFQ_" + arrPricing[i]['ER_QuoteRequestId'];
        // td.className = "cardTD"
        if (arrPricing[i].EP_BestPrice_YN == 'Y') {
            td.className = "cardTD highlightBest"
        }
        else {
            td.className = "cardTD tdUCPPricing whitebg"  //OmkarE-26-Oct-2021  UWI-191
        }
        tblMain.appendChild(trMain);
    }

    document.getElementById('tblLP').appendChild(tblMain);
}



function addEmailPriceControl(table, controlType, value, cssClass, height, rfqid) {
    var control;
    var tr = document.createElement('tr');
    var td = document.createElement('td');
    td.className = "cardTD";   //OmkarE-26-Oct-2021  UWI-191
    if (rfqid && rfqid.includes("PRICE_")) {
        td.id = "PRICE_" + value;
    }
    switch (controlType) {
        case 'label':
            control = document.createElement('label');
            control.innerHTML = value;
            control.id = rfqid;
            break;
        case 'button':
            control = document.createElement('button');
            control.innerHTML = value;
            $(control).bind("click", function () { SetUCPPricingIntersections(this, event) }); // Added by OnkarE on 05-Mar-2022 JIRA: UWI-303
            control.id = rfqid;
            break;
        case 'link':
            control = document.createElement('anchor');
            control.innerHTML = value;
            break;
        case 'empty':
            control = document.createTextNode('');
            td.style.height = height;
            break;
        default:
    }

    control.className = cssClass;
    td.appendChild(control);
    tr.appendChild(td);
    table.appendChild(tr);
}

function addSolveForEmail(tblMain, trMain) {
    var table = document.createElement('table');
    table.className = "cardTD"
    addEmailPriceControl(table, 'label', 'Counterparty', "", '');
    addEmailPriceControl(table, 'label', 'Price', "", '');
    addEmailPriceControl(table, 'label', 'RFQ ID', '', '');
    addEmailPriceControl(table, 'empty', '', '25');
    addEmailPriceControl(table, 'empty', '', '', '35');
    
    var td = document.createElement('td');
    td.className = "cardTD"
    td.appendChild(table);
    trMain.appendChild(td);

    tblMain.appendChild(trMain);
}
function SetUCPPricingIntersections(cntrl, event) { /// Added by OnkarE on 03-Mar-2022 JIRA: UWI-303
    try {
        console.log(cntrl)
        var id = $(cntrl).closest('table').parent()[0].cellIndex - 1;
        var pricingArrayeId = document.querySelector('[id*="hdnUCPPricingArray"]').id; // Changed by OnkarE on 03-Mar-2022
        var strPricing = document.getElementById(pricingArrayeId).value; // Changed by OnkarE on 03-Mar-2022
        var arrPricing = JSON.parse(strPricing);
        var bestprice = arrPricing[id].EP_price;
        console.log(bestprice)
        var bookOrderReq = "PR_RFQ_ID:" + arrPricing[id].ER_QuoteRequestId + "~lp:" + arrPricing[id].PP_CODE + "~PR_Client_Price:" + bestprice + "~PR_Client_Yeild:" + bestprice
        var priceRespId = document.querySelector('[id*="hdnUCPPriceResponseString"]').id; 
        document.getElementById(priceRespId).value = bookOrderReq;
        var UCPBestPrice = document.querySelector('[id*="hdnUCPBestPrice"]').id; // Added by OnkarE on 05-Mar-2022
        document.getElementById(UCPBestPrice).value = bestprice // Added by OnkarE on 05-Mar-2022
        var UCPBestPriceBtn = document.querySelector('[id*="btnSetPricingIntersection"]').id;
        document.getElementById(UCPBestPriceBtn).click();
    }
    catch (e) { }
}
//UCP pricing control <end>
//Start by SwatiP || Aditya B on 25-11-2021 HSBCELINT-160
function RMWReload(TotalNominalAmt,rowIndex) {  
   // debugger;
     $(window.parent.document).find("#ctl00_MainContent_dlProductPriceDetails_ctl" + rowIndex + "_lblInfoField1").text('Orders Placed ' + FormatAmount(Number(FormatNotional(TotalNominalAmt)).toFixed(Number(2))));
}
//End by SwatiP || Aditya B on 25-11-2021
function arrowKey_FundSearch(that) {
    var tbody = $(".tblFundSearch").find("tbody").last();
    var selected;
    selected = tbody.find(".selected");
    if (event.keyCode == 38) {
        selected.removeClass("selected");
        if (selected.prev().length == 0) {
            tbody.find("tr:last").addClass("selected");
        } else {
            selected.prev().addClass("selected");
            var scrollTP = $(".tbl_cust").scrollTop();
            $(".tbl_cust").scrollTop(scrollTP - 10);
        }
    }
    else if (event.keyCode == 40) {
        selected.removeClass("selected");
        if (selected.next().length == 0) {
            tbody.find("tr:nth-child(2)").addClass("selected");
            $(".tbl_cust").scrollTop(0);
        } else {
            selected.next().addClass("selected");
            var scrollTP = $(".tbl_cust").scrollTop() + $(".tbl_cust").height();
            $(".tbl_cust").scrollTop(scrollTP + 10);
        }
    }
    else if (event.keyCode == 13) {
        if (selected == undefined || selected.length != 0) {
            $(".selected").click();
            $(".tbl_cust").hide();
        }
        else
            document.getElementById('btnSelectFC').click();
    }
    else if (event.keyCode == 27) {
        $(".tbl_cust").hide();
    }
    else if (event.keyCode == 16 && event.keyCode == 9) {
        $(".tbl_cust").hide();
    }
    else if (event.keyCode == 9) {
        $(".tbl_cust").hide();

        if (selected == undefined || selected.length != 0) {
            $(".selected").click();
            $(".tbl_cust").hide();
        }
        else
            document.getElementById('btnSelectFC').click();
    }
    else if (event.keyCode == 17 || event.keyCode == 45) {
        arrowKeyFundSearch(that);
    }
}
function RefreshUCPAfterTokenPush(tokenID, noteMasterID) {
    try {
        $(document).ready(function () {
        
        //alert('Inside RefreshUCPAfterTokenPush...with Token:'+tokenid+' and NoteMasterId:'+noteMasterID');
      //  debugger;
        console.log('In RefreshUCPAfterTokenPush ');
        if (tokenID != undefined) {
            console.log('TokenID: ' + tokenID);
        } else {
            console.log('TokenID not provided/undefined.' );
        }
        if (noteMasterID != undefined) {
            console.log('NoteMasterID: ' + noteMasterID);
        } else {
            console.log('NoteMasterID not provided/undefined.');

        }
            //debugger;
            if ($(document).find('[id *= "hdnTokenID"]') != null || $(document).find('[id *= "hdnTokenID"]') != 'undefined') {
              //  document.getElementById("ctl00_MainContent_oUCPCtrl_hdnTokenID").value = tokenID;
                $(document).find('[id *= "hdnTokenID"]').val(tokenID);
            }
        //var sTokenID = document.querySelector('[id*="hdnTokenID"]').id;

            if ($(document).find('[id *= "hdnNoteMasterId"]') != null || $(document).find('[id *= "hdnNoteMasterId"]') != 'undefined') {
                //alert(1);
                //var sNoteMasterID = document.querySelector('[id*="hdnNoteMasterId"]').id;
               // document.getElementById("ctl00_MainContent_oUCPCtrl_hdnNoteMasterId").value = noteMasterID;
                $(document).find('[id *= "hdnNoteMasterId"]').val(noteMasterID);
            }
            if ($(document).find('[id *= "btnRefreshUCPAfterTokenPush"]') != null || $(document).find('[id *= "btnRefreshUCPAfterTokenPush"]') != 'undefined') {
                $(document).find('[id *= "btnRefreshUCPAfterTokenPush"]').click();
            }

        //var RefreshUCPAfterTokenPush = document.querySelector('[id*="btnRefreshUCPAfterTokenPush"]').id;
           // document.getElementById("ctl00_MainContent_oUCPCtrl_btnRefreshUCPAfterTokenPush").click();
        });

    } catch (er) {
        console.log('Error while calling RefreshUCPAfterTokenPush method :' + er);
    }
}
//swatiP 20-Apr-2022 UWI-332 start //02-May-2022 AKshayD UWI-343 Added parameter for north south row.
function ShowZonedata(btnid,start,end,state,NorthSouth) {
    try {
        
        var i = parseInt(start);
        while (i <= parseInt(end)) {
            var element = document.getElementById("ctl00_MainContent_oUCPCtrl_MSRow_" + i)
       
            //if (element.classList.contains('displayNone')) {
            if (state == "Y") {
                if (element != null) {
                    element.classList.remove('displayNone');
                    $(document).find('input[type="submit"][id$="' + btnid + '"].btnUCPZone').removeClass('UCParrowRighticon').addClass('UCParrowdnicon');
                 
                }
            
           // btnelement.classList.remove('arrowdnicon');
                //btnelement.classList.add('arrowupicon');               
                

                //if (NorthSouth == "Y") {
                //    var elementNS = document.getElementById("ctl00_MainContent_oUCPCtrl_MSRow_" + i)
                //    if (element != null) {
                //        elementNS.classList.remove('displayNone');
                //    }
                   
                //}

            } else {
                if (element != null) {
                    element.classList.add('displayNone');
                }
                
           // btnelement.classList.remove('arrowupicon');
               // btnelement.classList.add('arrowdnicon');
               // $(document).find('[id$="' + btnid + '"]').removeClass('UCParrowdnicon').addClass('UCParrowRighticon');
                $(document).find('input[type="submit"][id$="' + btnid + '"].btnUCPZone').removeClass('UCParrowdnicon').addClass('UCParrowRighticon');
               //input[type="submit"].btnUCPZone
                //if (NorthSouth == "Y") {
                //    var elementNS = document.getElementById("ctl00_MainContent_oUCPCtrl_MSRow_" + i)
                //    if (element != null) {
                //        elementNS.classList.add('displayNone');
                //    }
                    
                //}

            }
            i++;
        }
        

    } catch (error) {
        throw (error)
    }
}
//End uwi-332

 //Added by ShekharL on 05-May-2022 on Tabout set focus on next control or select share and Customer autocomplete serach
function onTab_ShareSearch(event, txtSearch) {
    var keyCode;
    var event = event || window.event;

    if (window.event.keyCode == 9 || window.event.key === 'Tab') {
        var tbody = $(".TableShareSearchResult").find("tbody");
        selected = tbody.find(".selected");
        $(".TableShareSearchResult").find(".selected").click();
        $(".sharePopup").hide(); 
        return true;
    };

}

//Added by Shubham Podhade/ ShekharL on 06-May-2022 for setting tab name of a newly opened browser tab. BBVAORINT-327
function setBrowserTabName() {
    $('document').ready(function () {
        window.setTimeout(function () {
            var PopUpPath = window.location.search;  //$("#ctl00_Hdn_Popup_Path").val();
            if (PopUpPath.indexOf("Master_Popup=POPUP") > -1 || (window.location.pathname.indexOf("FinIQ_UCPDealEntry.aspx") > -1)) {
                //alert('inside true condition');
                if (($("#ctl00_Hdn_Popup_Path").val().replace('?', '').split('&')[2].split('N:')[1] != undefined && $("#ctl00_Hdn_Popup_Path").val().replace('?', '').split('&')[2].split('N:')[1] != '' && $("#ctl00_MainContent_lblProductDisplayName").text().trim()!=''))
                    window.self.document.title = $("#ctl00_Hdn_Popup_Path").val().replace('?', '').split('&')[2].split('N:')[1] +
                        " | " + $("#ctl00_MainContent_lblProductDisplayName").text().trim();
				else{
					if($("#ctl00_MainContent_divWarning ol").text().trim().includes('locked'))
					window.self.document.title = $("#ctl00_Hdn_Popup_Path").val().replace('?', '').split('&')[2].split('N:')[1] +
                        " | " + $("#ctl00_MainContent_divWarning ol").text().trim().replace(' has been','') + ", all operations restricted.";
				}
					
            }
        }, 1);


    });
}
function hookFileClick(event, cntrl) {
    // Initiate the File Upload Click Event  
    document.getElementById('ctl00_MainContent_oUCP_ProdcutSchedule_fileuploadExcel').click();
}

function fnOnChange(event, obj) {
    document.getElementById("ctl00_MainContent_oUCP_ProdcutSchedule_txtUploadFile").value = obj.files[0].name;
}
function EnableDisableAllWFLbtns(value,yesnoDisable) {  //Added by SwatiP to enable/disable new wfl buttons 
    if (yesnoDisable == true) {
        $('#ctl00_MainContent_oUCPCtrl_dlWorkflows').find('input[type="submit"]:not([id$="btndealno"], [id$="btnWorkflow"])').removeAttr("disabled");
        $('#ctl00_MainContent_oUCPCtrl_dlWorkflows').find('input[type="submit"]:not([id$="btndealno"], [id$="btnWorkflow"])').prop("disabled", value)
    }
    else {
        $('#ctl00_MainContent_oUCPCtrl_dlWorkflows').find('input[type="submit"]:not([id$="btnNo"], [id$="btnYes"], [id$="btndealno"], [id$="btnWorkflow"])').removeAttr("disabled");
        $('#ctl00_MainContent_oUCPCtrl_dlWorkflows').find('input[type="submit"]:not([id$="btnNo"], [id$="btnYes"], [id$="btndealno"], [id$="btnWorkflow"])').prop("disabled", value)
    }
  
   
}
