var xPos, yPos;
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_beginRequest(function (s, e) {
    if ($("#ctl00_MainContent_workflowControl_pnlSetting")[0] != undefined) {
        //Modified by Jyoti Kulkarni on 14-Jun-2021 for MASCLI 667 
        if ($("#ctl00_MainContent_workflowControl_pnlSetting")[0].offsetLeft != 0) {
            xPos = $("#ctl00_MainContent_workflowControl_pnlSetting")[0].offsetLeft;
        }
        if ($("#ctl00_MainContent_workflowControl_pnlSetting")[0].offsetTop != 0) {
            yPos = $("#ctl00_MainContent_workflowControl_pnlSetting")[0].offsetTop;
        }
    }
});
prm.add_endRequest(function (s, e)
{
    $('#ctl00_MainContent_workflowControl_ddlMultiQueue_txtSelectedOptions').css('width', '220');
    $('#ctl00_MainContent_workflowControl_ddlMultiQueue_divMultiSelectOptions').css('width', '220');
    // Added by Shubham Podhade on 27-May-2022 for Custom View BBVAORINT-484----- START
    ActiveTab = $('[id$="hdntabs"]').val();
    if (ActiveTab != '') {
        $('#' + ActiveTab).addClass('active');
    }
    // Added by Shubham Podhade on 27-May-2022 for Custom View BBVAORINT-484----- END
    $(document).ready(function () {


        if (workflowFiltersVisible) {
            $('#ctl00_MainContent_workflowControl_pnlWorkflowFilters').hide();
            if (document.querySelector("svg > path:nth-of-type(1)") != null) {
                document.querySelector("svg > path:nth-of-type(2)").style.visibility = 'hidden';
                document.querySelector("svg > path:nth-of-type(1)").style.visibility = 'visible';
        }
    }
    else if (!workflowFiltersVisible) {
        $('#ctl00_MainContent_workflowControl_pnlWorkflowFilters').show();
        //Added by Shubham Podhade on 01-Apr-2022 for Overlay on workflow blotter | INT1FIN47-445
        document.getElementById("overlayDiv").style.display = "block";
        if (document.querySelector("svg > path:nth-of-type(1)") != null) {
            document.querySelector("svg > path:nth-of-type(1)").style.visibility = 'hidden';
            document.querySelector("svg > path:nth-of-type(2)").style.visibility = 'visible';
        }
        //if (personlSettingPanelVisibility) {
    }
        if (personlSettingPanelVisibility) {
            $('#ctl00_MainContent_workflowControl_pnlSetting').hide();
        }
        else if (!personlSettingPanelVisibility) {
            document.getElementById("overlayDiv").style.display = "block";
            $('#ctl00_MainContent_workflowControl_pnlSetting').show();
        }
        // Added by Shubham Podhade on 27-May-2022 for Custom View BBVAORINT-484----- START
        if (createViewsPanelVisibility) {
            $('#ctl00_MainContent_workflowControl_pnlCreateViews').hide();
        }
        else if (!createViewsPanelVisibility) {
            document.getElementById("overlayDiv").style.display = "block";
            $('#ctl00_MainContent_workflowControl_pnlCreateViews').show();
        }
        // Added by Shubham Podhade on 27-May-2022 for Custom View BBVAORINT-484----- END
        if (quickFiltersVisible) {
            $('#ctl00_MainContent_workflowControl_pnlQuickFilters').hide();// return void (0);
        $('#ctl00_MainContent_workflowControl_btnQuickFilters').html("+ Quick Filters")
    }
    else {
        $('#ctl00_MainContent_workflowControl_pnlQuickFilters').show();// return void (0);
        $('#ctl00_MainContent_workflowControl_btnQuickFilters').html("- Quick Filters")
    }
    if (displaypriorityVisibility) {
        $('#ctl00_MainContent_workflowControl_UPanelWF_Seq_Settings').hide();
    }
    else if (!displaypriorityVisibility) {
        $('#ctl00_MainContent_workflowControl_UPanelWF_Seq_Settings').show();
    }

    if (wffindVisibility) {
        $('#ctl00_MainContent_workflowControl_pnlAdvSearch').hide();
    }
    else if (!wffindVisibility) {
        $('#ctl00_MainContent_workflowControl_pnlAdvSearch').show();
    }
        if ($("#ctl00_MainContent_workflowControl_pnlSetting")[0] != undefined) {
            if (yPos != 0 && xPos != 0) {
                $("#ctl00_MainContent_workflowControl_pnlSetting").css({ top: yPos + 'px', left: xPos + 'px' });
            } else {
                
                yPos=$("#ctl00_MainContent_workflowControl_pnlSetting").offset().top;
                xPos =  $("#ctl00_MainContent_workflowControl_pnlSetting").offset().left;


                $("#ctl00_MainContent_workflowControl_pnlSetting").css({ top: yPos + 'px', left: xPos + 'px' });
            }
        
    }

    //Added by Shubham Podhade on 24-May-2021 | MASINT-1985 | Clear Accordion Data on specific clicks || START
    if (s._activeElement.id != undefined) {
        if (arrAccordionRows != undefined && arrAccordionRows.length > 0) {

            if (s._activeElement.id == 'ctl00_MainContent_workflowControl_btnProductSearch' ||
                s._activeElement.id == 'ctl00_MainContent_workflowControl_btnPrev' ||
                s._activeElement.id == 'ctl00_MainContent_workflowControl_btnPrev_Grid' ||
                s._activeElement.id == 'ctl00_MainContent_workflowControl_btnNext' ||
                s._activeElement.id == 'ctl00_MainContent_workflowControl_btnNext_Grid' ||
                s._activeElement.id == 'ctl00_MainContent_workflowControl_ddlWorkFlow' ||
                s._activeElement.id.includes("ctl00_MainContent_workflowControl_Queues_ctl") ||
                s._activeElement.id == 'btnYear' || s._activeElement.id == 'btnMonth' ||
                s._activeElement.id == 'btnWeek' || s._activeElement.id == 'btnDay'
            ) {
                arrAccordionRows = [];
            }
        }
    }
    //Added by Shubham Podhade on 24-May-2021 | MASINT-1985 | Clear Accordion Data on specific clicks || END
        ////Added by Arati Kulkarni|| 14-May-2022||  To show/hide queue on postback
        //if (!QtoggleDisable && $("#ctl00_MainContent_workflowControl_Queues").is(':visible')) {

        //    var gridrows = $("#ctl00_MainContent_workflowControl_Queues  tbody tr");
        //    if (gridrows != "undefined" && gridrows.length > 0) {
        //        if (Qtoggle == true) {
        //            for (var i = 0; i < gridrows.length; i++) {
        //                gridrows[i].cells[0].style.display = "none";
        //                gridrows[i].cells[1].style.display = "none";
        //            }
        //            //gridrows[0].cells[0].style.display = "revert"; // Commented by Shubham Podhade on 27-May-2022 
        //            $("#ctl00_MainContent_workflowControl_Queues").css('width', '0px');
        //            Qtoggle = false;
        //            return;
        //        }
        //        if (Qtoggle == false) {
        //            for (var i = 0; i < gridrows.length; i++) {
        //                gridrows[i].cells[0].style.display = "revert";
        //                gridrows[i].cells[1].style.display = "revert";
        //            }
        //            $("#ctl00_MainContent_workflowControl_Queues").css('width', '308px');
        //            Qtoggle = true;
        //            return;
        //        }
        //    }
        //}
        if (!Qtoggle) {
            $("table.Queues tbody tr").find("td, th").css({ "display": "none" });
            $("table.Queues").css('width', '0px');
            $("#ctl00_MainContent_workflowControl_btnQueue").css('display', 'none')
            $("#ctl00_MainContent_workflowControl_btnView").css('display', 'none')
        }
        if (!showHideQueueViewTabVisibility) {
            $('.tabView1').css({ 'display': 'none' });
            $('#ctl00_MainContent_workflowControl_btnQueueTab').css({ 'display': 'none' });
            $('#ctl00_MainContent_workflowControl_btnViewTab').css({ 'display': 'none' });
        }
        //setFavWorkflowWidth(); //Added by Shubham Podhade on 24-Jun-2021 for dyanamic widths to Fav Workflows
        notificationcounter = 0;
        // Added by Shubham Podhade on 27-May-2022 for Custom View BBVAORINT-484----- START
        ActiveTab = $('[id$="hdntabs"]').val();
        if (ActiveTab != '') {
            $('#' + ActiveTab).addClass('active');
        }
       // Added by Shubham Podhade on 27-May-2022 for Custom View BBVAORINT-484----- END

        return void (0);
    });

});

//07042021
$(document).mouseup(function (e) {
    try {
        
        if ($(e.target)[0].id === 'btnTriangleFilter' || $(e.target)[0].id === 'ctl00_MainContent_workflowControl_btnQuickFilters' || $(e.target)[0].id === 'ctl00_MainContent_workflowControl_btnApplyQuickFilters' || $(e.target)[0].id === 'svgDown' || $(e.target)[0].id === 'svgUP' || $(e.target)[0].nodeName === 'path') {
        }
        else if ($(e.target).closest(".pnlWorkflowFiltersDiv").length === 0) {
            if ($(e.target).closest(".pnlSetting").length === 0 && $(e.target).closest(".ui-dialog").length === 0 && $(e.target).closest(".PopupAdvSearch").length === 0 && $(e.target).closest(".PopupWSS").length === 0) {
                $('#ctl00_MainContent_workflowControl_pnlWorkflowFilters').hide();
                workflowFiltersVisible = true;
                if (document.querySelector("svg > path:nth-of-type(1)") != null) {
                    //document.querySelector("svg > path:nth-of-type(2)").style.visibility = 'hidden';
                    if (document.querySelector("svg > path:nth-of-type(1)").style.visibility = 'hidden') {
                        document.querySelector("svg > path:nth-of-type(2)").style.visibility = 'hidden';
                        document.querySelector("svg > path:nth-of-type(1)").style.visibility = 'visible';
                    }
                }
            }
        }
        //Added by Shubham Podhade on 01-Apr-2022 for Overlay on workflow blotter | INT1FIN47-445
        else if ($(e.target)[0].id === 'overlayDiv') {
        // Modified By  by Shubham Podhade on 27-May-2022 for Custom View BBVAORINT-484
            if (personlSettingPanelVisibility == false || createViewsPanelVisibility== false) { 
                return true;
            }
            document.getElementById("overlayDiv").style.display = "none";
            $('#ctl00_MainContent_workflowControl_pnlWorkflowFilters').hide();
            workflowFiltersVisible = true;
            if (document.querySelector("svg > path:nth-of-type(1)") != null) {
                //document.querySelector("svg > path:nth-of-type(2)").style.visibility = 'hidden';
                if (document.querySelector("svg > path:nth-of-type(1)").style.visibility = 'hidden') {
                    document.querySelector("svg > path:nth-of-type(2)").style.visibility = 'hidden';
                    document.querySelector("svg > path:nth-of-type(1)").style.visibility = 'visible';
                }
            }
        }

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


if (window.captureEvents) {
    window.captureEvents(Event.KeyUp);
    window.onkeyup = executeCode;
}
else if (window.attachEvent) {
    document.attachEvent('onkeyup', executeCode);

}


function executeCode(evt) {
    if (evt == null) {
        evt = window.event;
    }
    var theKey = parseInt(evt.keyCode, 10);
    //console.log("My Key:" + theKey);
    switch (theKey) {

        case 116: // F5
            //document.getElementById("<%=btnProductSearch.ClientID%>").click();
            $("#ctl00_MainContent_workflowControl_btnProductSearch").click();
            //document.getElementById('ctl00_ContentPlaceHolder1_btnHome').click(); 
            break;
        case 13: // Enter
          //Modified by Shubham P on 10-May-2022 | BBVAORINT-341
            if (evt.srcElement.id == "ctl00_MainContent_workflowControl_txtSearch" || evt.srcElement.id == "ctl00_MainContent_workflowControl_btnProductSearch") {
                //document.getElementById("<%=btnProductSearch.ClientID%>").click();
                $("#ctl00_MainContent_workflowControl_btnProductSearch").click();
            }
            //<START> Added By Shubham Podhade on 23-Jan-2020 for Enter Event on WF Look up Search
            else if (evt.srcElement.id == "ctl00_MainContent_workflowControl_txtAdvrefID") {
                //document.getElementById("<%=btnHiddenForAdvRef.ClientID%>").click();
                $("#ctl00_MainContent_workflowControl_btnHiddenForAdvRef").click();

            }
            else if ($('div#ctl00_MainContent_workflowControl_pnlQuickFilters').has(evt.target).length > 0) {
                //document.getElementById("<%=btnApplyQuickFilters.ClientID%>").click();
                $("$ctl00_MainContent_workflowControl_btnApplyQuickFilters").click();

            }


            break;
        case 9: //TAB 
            
            if (evt.srcElement.id == "ctl00_MainContent_workflowControl_btnAdvrefApply" ) {
                //document.getElementById("<%=btnHiddenForAdvRef.ClientID%>").click();
                $("#ctl00_MainContent_workflowControl_btnProductSearch").click();
            }
            break;
        //<END> Added By Shubham Podhade on 23-Jan-2020 for Enter Event on WF Look up Search

        case 27:
            $('#ctl00_MainContent_workflowControl_pnlWorkflowFilters').hide();
            //Added by Shubham Podhade on 01-Apr-2022 for Overlay on workflow blotter | INT1FIN47-445
            $('#ctl00_MainContent_workflowControl_pnlSetting').hide();
            workflowFiltersVisible = true;
            personlSettingPanelVisibility = true;
            document.getElementById("overlayDiv").style.display = "none";
            if (document.querySelector("svg > path:nth-of-type(1)") != null) {
                document.querySelector("svg > path:nth-of-type(1)").classList.toggle("invisible");
                document.querySelector("svg > path:nth-of-type(2)").classList.toggle("invisible");
            }
            break;
            //Added by Shubham P on 10-May-2022 | BBVAORINT-341
        case 32:
            if (evt.srcElement.id == "ctl00_MainContent_workflowControl_btnProductSearch") {
                //document.getElementById("<%=btnProductSearch.ClientID%>").click();
                $("#ctl00_MainContent_workflowControl_btnProductSearch").click();
            }
            break;

    }
    evt.returnValue = false;
    return false;
}

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

    SetSorting_Filter1();
    //setFavWorkflowWidth(); //Added by Shubham Podhade on 24-Jun-2021 for dyanamic widths to Fav Workflows 
    $('#ctl00_MainContent_workflowControl_ddlMultiQueue_txtSelectedOptions').css('width', '220');
    $('#ctl00_MainContent_workflowControl_ddlMultiQueue_divMultiSelectOptions').css('width', '220');
    // Added by Shubham Podhade on 27-May-2022 for Custom View BBVAORINT-484----- START
    ActiveTab = $('[id$="hdntabs"]').val();
    if (ActiveTab != '') {
        $('#' + ActiveTab).addClass('active');
    } else {
        $('[id$="hdntabs"]').val($('.tabContainerCR').find('.tabs').eq(0)[0].id);
        ActiveTab = $('[id$="hdntabs"]').val();
        $('#' + ActiveTab).addClass('active');
    }
    // Added by Shubham Podhade on 27-May-2022 for Custom View BBVAORINT-484----- END
});

window.onload = function () {
    //
    //Nikhil Pakhale, 13th Oct 2020, no need for subscribe
    //SubScribBonds_WF(document.getElementById("ctl00_MainContent_workflowControl_hdn_WebsocketIP").value, document.getElementById("ctl00_hdnUserNameForNotification").value);
}

$(document).on("click", function () {
    $("#ctl00_MainContent_workflowControl_pnlSetting").find(".finiq_Cal").each(function () {
        $(this).prop('style').removeProperty('left');
        $(this).prop('style').removeProperty('top');
    });
});


//<START>------ JS Functions for visibility toggle ---------
var personlSettingPanelVisibility = true;
function OpenPersonalSetting() {
    try {
        showHideWorkflowFilters(); //Added by Shubham Podhade on 01-Apr-2022 for Overlay on workflow blotter | INT1FIN47-445
        $('#ctl00_MainContent_workflowControl_pnlSetting').show();
        personlSettingPanelVisibility = false;
    }
    catch (err) {
        console.log('Error in OpenPersonalSetting panel');
    }
}
// Added by Pratik S on 30-Aug-2021  INT1FIN47-62 - Reset Workflow Personal settings
function ClosePersonalSetting() {
    try {
        var span = $('#ctl00_MainContent_workflowControl_lblMsgSetting')[0];
        if (span != undefined)
            span.parentNode.removeChild(span);
        $('#ctl00_MainContent_workflowControl_pnlSetting').hide();
        personlSettingPanelVisibility = true;
        document.getElementById("overlayDiv").style.display = "none"; //Added by Shubham Podhade on 01-Apr-2022 for Overlay on workflow blotter | INT1FIN47-445
    }
    catch (err) {
        console.log('Error in ClosePersonalSetting panel');
    }
}

var displaypriorityVisibility = true;
var dvScroll = 'ctl00_MainContent_workflowControl_panel11';
function OpenDisplayPriority() {
    // 
    try {
        $('#ctl00_MainContent_workflowControl_UPanelWF_Seq_Settings').show();
        //$('#ctl00_MainContent_workflowControl_panel11').scrollTop = yPos;

        var prm = Sys.WebForms.PageRequestManager.getInstance();
        prm.remove_beginRequest(BeginRequestHandler);
        prm.remove_endRequest(EndRequestHandler);
        prm.add_beginRequest(BeginRequestHandler);
        prm.add_endRequest(EndRequestHandler);

        function BeginRequestHandler(sender, args) {
            xPos = $get(dvScroll).scrollLeft;
            yPos = $get(dvScroll).scrollTop;
            return true;
        }
        function EndRequestHandler(sender, args) {
            $get(dvScroll).scrollLeft = xPos;
            $get(dvScroll).scrollTop = yPos + 50;
            return true;
        }
        displaypriorityVisibility = false;
    }
    catch (err) {
        console.log('Error in OpenDisplayPriority panel');
    }
}
//function OpenDisplayPriority() {
//   // 
//    try {
//        $('#ctl00_MainContent_workflowControl_UPanelWF_Seq_Settings').show();
//        displaypriorityVisibility = false;
//    }
//    catch (err) {
//        console.log('Error in OpenDisplayPriority panel');
//    }
//}

function CloseDisplayPriority() {
    try {
        $('#ctl00_MainContent_workflowControl_UPanelWF_Seq_Settings').hide();
        displaypriorityVisibility = true;
    }
    catch (err) {
        console.log('Error in CloseDisplayPriority panel');
    }
}

var wffindVisibility = true;
function OpenWfFind() {

    try {
        $('#ctl00_MainContent_workflowControl_pnlAdvSearch').show()
        wffindVisibility = false;
    }

    catch (err) {
        console.log('Error in OpenWfFind panel');
    }
}

function CloseWfFind() {
    try {
        $('#ctl00_MainContent_workflowControl_pnlAdvSearch').hide()
        wffindVisibility = true;
    }

    catch (err) {
        console.log('Error in CloseWfFind panel');
    }
}
function wffindcheck() {

    try {
        $('#ctl00_MainContent_workflowControl_pnlAdvSearch').hide()
        wffindVisibility = true;
    }

    catch (err) {
        console.log('Error in wffindcheck panel');
    }
}
var workflowFiltersVisible = true;
function showHideWorkflowFilters() {
    
    try {
        
        if (workflowFiltersVisible) {
            $('#ctl00_MainContent_workflowControl_pnlWorkflowFilters').show();
            document.getElementById("overlayDiv").style.display = "block"; //Added by Shubham Podhade on 01-Apr-2022 for Overlay on workflow blotter | INT1FIN47-445
            workflowFiltersVisible = false;
            if (document.querySelector("svg > path:nth-of-type(1)") != null) {
                document.querySelector("svg > path:nth-of-type(1)").style.visibility = 'hidden';
                document.querySelector("svg > path:nth-of-type(2)").style.visibility = 'visible';
            }
        }
        else {
            $('#ctl00_MainContent_workflowControl_pnlWorkflowFilters').hide();
            workflowFiltersVisible = true;
            if (document.querySelector("svg > path:nth-of-type(1)") != null) {
                document.querySelector("svg > path:nth-of-type(2)").style.visibility = 'hidden';
                document.querySelector("svg > path:nth-of-type(1)").style.visibility = 'visible';
            }
        }
    }
    catch (err) {
        console.log('Error in showHideWorkflowFilters panel');
    }
}


var Qtoggle = true;
var QtoggleDisable = false;

function disableQueueToggle() {
    try {
        //alert('inside disableQueueToggle');
        QtoggleDisable = true;
        var gridrows = $("#ctl00_MainContent_workflowControl_Queues  tbody tr");
        for (var i = 0; i < gridrows.length; i++) {
            gridrows[i].cells[0].style.display = "none";
            gridrows[i].cells[1].style.display = "none";
        }
        $("#ctl00_MainContent_workflowControl_Queues").css('width', '0px');
        //document.getElementById('ctl00_MainContent_workflowControl_ddlWorkFlow').setAttribute("disabled", "disabled");
        //document.getElementById('btnTriangleFilter').setAttribute("disabled", "disabled");
        //document.getElementById('ctl00_MainContent_workflowControl_txtSearch').setAttribute("disabled", "disabled");
        //document.getElementById('ctl00_MainContent_workflowControl_ddlWorkFlow').style.display = "none";
        //document.getElementById('btnTriangleFilter').style.display = "none";
        //document.getElementById('ctl00_MainContent_workflowControl_txtSearch').style.display = "none";
        //document.getElementById('ctl00_MainContent_workflowControl_btnQuickFilters').style.display = "none";
        //document.getElementById('ctl00_MainContent_workflowControl_btnQuickFilters').style.display = "none";
        document.getElementById('tblWfFilters').style.display = "none";
        document.getElementById('tblQuickFilters1').style.display = "none";
        document.getElementById('tblQuickFilters2').style.display = "none";
        document.getElementById('ctl00_MainContent_workflowControl_lblPagecount_Grid').style.display = "none"; /*added by Arati K || 9 sep 2021 || MASCLI 1032*/
    } catch (err) {
        console.log('Error in disableQueueToggle function: ' + err);
    }
}
function showHideQueueList() {
    try {
        if (QtoggleDisable)
            return;
        if (Qtoggle == true) {
            $("table.Queues tbody tr").find("td, th").css({ "display": "none" });
            $("table.Queues").css('width', '0px');
            $("#ctl00_MainContent_workflowControl_btnQueue").css('display', 'none')
            $("#ctl00_MainContent_workflowControl_btnView").css('display', 'none')
            Qtoggle = false;
            return;
        }
        if (Qtoggle == false) {
            $("table.Queues tbody tr").find("td, th").css({ "display": "revert" });
            $("table.Queues").css({ 'width': '308px' });
            $("#ctl00_MainContent_workflowControl_btnQueue").css({ 'display': 'revert' });
            $("#ctl00_MainContent_workflowControl_btnView").css({ 'display': 'revert' });
            Qtoggle = true;
            return;
        }
    }
    catch (err) {
        console.log('Error in showHideQueueList function');
    }
}


var quickFiltersVisible = true;
function showHideQuickFilters() {

    try {

        if (quickFiltersVisible) {
            $('#ctl00_MainContent_workflowControl_pnlQuickFilters').show();
            quickFiltersVisible = false;
            $('#ctl00_MainContent_workflowControl_btnQuickFilters').html("- Quick Filters")
        }
        else {
            $('#ctl00_MainContent_workflowControl_pnlQuickFilters').hide();
            quickFiltersVisible = true;
            $('#ctl00_MainContent_workflowControl_btnQuickFilters').html("+ Quick Filters")
        }
    }
    catch (err) {
        console.log('Error in Quick filters show/hide');
    }
}

function HideQuickFiltersOnLoadBtnClick() {

    try {
        $('#ctl00_MainContent_workflowControl_pnlQuickFilters').hide();
        quickFiltersVisible = true;
        $('#ctl00_MainContent_workflowControl_btnQuickFilters').html("+ Quick Filters")
    }
    catch (err) {
        console.log('Error in Quick filters hide');
    }
}
//Added by Shubham Podhade on 18-Dec-2020 || for date range selector shortcuts.
function dateRangeValueSelector(dateRangeValue, pageName) {
    try {
        if (dateRangeValue == 'Year') {
            manipulateDates(dateRangeValue, pageName);
            //document.getElementById("ctl00_MainContent_workflowControl_hdnDateRangeSelectedValue").value = 'Year';
        } else if (dateRangeValue == 'Month') {
            manipulateDates(dateRangeValue, pageName);
            //document.getElementById("ctl00_MainContent_workflowControl_hdnDateRangeSelectedValue").value = 'Month';
        } else if (dateRangeValue == 'Week') {
            manipulateDates(dateRangeValue, pageName);
            //document.getElementById("ctl00_MainContent_workflowControl_hdnDateRangeSelectedValue").value = 'Week';
        } else if (dateRangeValue == 'Day') {
            manipulateDates(dateRangeValue, pageName);
            //document.getElementById("ctl00_MainContent_workflowControl_hdnDateRangeSelectedValue").value = 'Day';
        }
        //document.getElementById('<%=hdnDateRangeSelector.ClientID%>').click();
        //$("#ctl00_MainContent_workflowControl_hdnDateRangeSelector").click();
        if (pageName == 'blotter')
            $("#ctl00_MainContent_workflowControl_btnProductSearch").click();
        else if (pageName == 'navigator')
            $("#ctl00_MainContent_btnLoad").click();
    } catch (err) {
        console.log('Error in daterangeValueSelector function')
    }
}
var sToDate;
var sFromDate;
var sDay;
var sMonth;
var sYear;
var monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
    "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
];//Changed month name by Arati K || MASINT-2105 
function manipulateDates(dateRangeSelectorKey, pageName) {
    try {
        if (pageName == 'blotter')
            sToDate = $("#ctl00_MainContent_workflowControl_txtToDate_txtDate").val();
        else if (pageName == 'navigator')
            sToDate = $("#ctl00_MainContent_txtToDateQ_txtDate").val();
        sToDate = new Date(sToDate);
        if (dateRangeSelectorKey == 'Year') {

            sYear = (parseInt(sToDate.getFullYear()));
            if (((sYear % 4 == 0) && (sYear % 100 != 0)) || (sYear % 400 == 0)) {
                //year is leap
                sToDate.setDate(sToDate.getDate() + (-366));
            }
            else {
                sToDate.setDate(sToDate.getDate() + (-365));
            }
            sYear = (parseInt(sToDate.getFullYear()));
            sMonth = (parseInt(sToDate.getMonth()));
            sDay = (parseInt(sToDate.getDate()));
            sFromDate = addZero(parseInt(sDay)) + "-" + monthNames[sMonth] + "-" + sYear;

        }
        else if (dateRangeSelectorKey == 'Month') {
            sDay = (parseInt(sToDate.getDate()));
            sMonth = (parseInt(sToDate.getMonth()));
            sYear = (parseInt(sToDate.getFullYear()));

            if (sMonth == 0) {
                sMonth = 11;
                sYear = (parseInt(sToDate.getFullYear()) - 1);
            }
            else {
                sMonth = sMonth - 1;
            }
            if (sDay >= 28) {
                if (sMonth == 3 || sMonth == 5 || sMonth == 8 || sMonth == 10) {
                    sDay = 30;
                }
                if (((sYear % 4 == 0) && (sYear % 100 != 0)) || (sYear % 400 == 0)) {
                    //year is leap
                    if (sMonth == 1)
                        sDay = 29;
                }
                else {
                    if (sMonth == 1)
                        sDay = 28;
                }
            }
            sFromDate = addZero(parseInt(sDay)) + "-" + monthNames[sMonth] + "-" + sYear;
        }
        else if (dateRangeSelectorKey == 'Day') {
            //sToDate = new Date();
            sFromDate = addZero(parseInt(sToDate.getDate())) + "-" + monthNames[sToDate.getMonth()] + "-" + sToDate.getFullYear();
            // $("#ctl00_MainContent_workflowControl_txtToDate_txtDate").val(sToDate)
        }
        else if (dateRangeSelectorKey == 'Week') {
            sToDate.setDate(sToDate.getDate() + (-7));
            sDay = (parseInt(sToDate.getDate()));
            sMonth = (parseInt(sToDate.getMonth()));
            sYear = (parseInt(sToDate.getFullYear()));

            sFromDate = addZero(parseInt(sDay)) + "-" + monthNames[sMonth] + "-" + sYear;
        }
        if (pageName == 'blotter')
            $("#ctl00_MainContent_workflowControl_txtFromDate_txtDate").val(sFromDate);
        else if (pageName == 'navigator')
            $("#ctl00_MainContent_txtFromDateQ_txtDate").val(sFromDate);


    } catch (err) {
        console.log("Error in manipulateDates :" + err)
    }

}
function addZero(day) {
    try {
        if (day <= 9) {
            return "0" + day.toString();
        }
        return day.toString();
    } catch (err) {
        console.log("Error in addZero :" + err)
    }
}
//<END>------ JS Functions for visibility toggle ---------

function parentFunc() {
    //document.getElementById('<%= hdnApplyFilterResult.ClientID%>').click();
    $("#ctl00_MainContent_workflowControl_hdnApplyFilterResult").click();

}

function SetGridAfterResetPopup() {
    //document.getElementById('<%= btnProductSearch.ClientID%>').click();
    $("#ctl00_MainContent_workflowControl_btnProductSearch").click();
}

function txtpageno_TextChanged() {
    document.getElementById('ctl00_MainContent_hdn_pagenochanged').value = "TRUE"
}

function FiltersChanged() {
    document.getElementById('ctl00_MainContent_hdn_filterschanged').value = "TRUE"
}


function ShowSettingDia() {
    $(function () {
        $('.pnlSetting').dialog();
    });
}

window.onbeforeunload = function (event) {
    FunClosePopupAndRefreshParentPage();
};

function FunClosePopupAndRefreshParentPage() {
    window.opener.document.getElementById("ctl00_MainContent_workflowControl_btnProductSearch").click();
    if (window.opener.progressWindow) {
        window.opener.progressWindow.close();
    }
    window.close();
}

var Counter;
var blinkerCount = 0;

/*-----Added by Shubham Podhade on 22-Dec-2021 for workflow and queue blink ----- START*/
var notificationcounter = 0;
var newname = "";
function blinkWorkflowQueue(targetedQueue, targetedWorkflow) {
    try {
        //current selected workflow and targeted workflow are the same --> go for specific queue highlight
        if ($("#ctl00_MainContent_workflowControl_ddlWorkFlow option:selected").text().trim() == targetedWorkflow) {
            //When Queue View is List
            if ($('#ctl00_MainContent_workflowControl_Queues').length == 1) {
                if ($("#ctl00_MainContent_workflowControl_Queues tr:contains('" + targetedQueue.trim() + "')").length == 1) {
                    $("#ctl00_MainContent_workflowControl_Queues tr:contains('" + targetedQueue.trim() + "')").addClass("BlinkQueue");
                    $("#ctl00_MainContent_workflowControl_Queues tr:contains('" + targetedQueue.trim() + "')").find('td:eq(1) a').css({ 'color': 'green', 'font-size': '13px' });
                    if (targetedQueue == "All") {
                        newname = $("#ctl00_MainContent_workflowControl_Queues tr:contains('" + targetedQueue.trim() + "')").text().split("+")[0] + " +" + (++notificationcounter);
                        $("#ctl00_MainContent_workflowControl_Queues tr:contains('" + targetedQueue.trim() + "')").find('td:eq(1) a').text("").append(newname.trim()).css('color', 'green');
                    }
                }
            }
            //When Queue View is Tab
            else if ($('#ctl00_MainContent_workflowControl_Repeater1_ctl00_Queue_Name').length == 1) {
                if ($(".buttonLinkTab:contains('" + targetedQueue.trim() + "')").length == 1) {
                    //queue is present
                    $(".buttonLinkTab:contains('" + targetedQueue.trim() + "')").addClass("BlinkQueue");
                    if (targetedQueue == "All") {
                        newname = $(".buttonLinkTab:contains('" + targetedQueue.trim() + "')").text().split("+")[0] + " +" + (++notificationcounter);
                        $(".buttonLinkTab:contains('" + targetedQueue.trim() + "')").text("").append(newname.trim());
                    }
                }
            }
        }
        //Check fav workflow list with received WTM title if YES then blink that fav workflow
        else if ($('#tblFavWorkflow').length == 1) {
            for (var favWorfklowCount = 0; favWorfklowCount <= (($('#tblFavWorkflow tr').eq(1).find('td:eq(0) a').length) - 1); favWorfklowCount++) {
                if (($('#tblFavWorkflow tr').eq(1).find('td:eq(0) a')[favWorfklowCount].text) == targetedWorkflow) {
                    $('#tblFavWorkflow tr').eq(1).find('td:eq(0) a').eq(favWorfklowCount).addClass("BlinkQueue");
                    newname = targetedWorkflow + " +" + (++notificationcounter);
                    // $('#tblFavWorkflow tr').eq(1).find('td:eq(0) a').eq(favWorfklowCount).text("").append(newname.trim()).css('color', 'green');

                }
            }
        }
    } catch (err) {
        console.log('Error in blinkWorkflowQueue :', err);
    }
}
/*-----Added by Shubham Podhade on 22-Dec-2021 for workflow and queue blink ----- END*/


function HeaderClick(CheckBox) {
    //Get target base & child control.
    var TargetBaseControl = "ctl00_MainContent_workflowControl_queue_data_grid";//document.getElementById('<%= queue_data_grid.ClientID %>');
    var TargetChildControl = "chkAllParent";

    //Get all the control of the type INPUT in the base control.
    var Inputs = TargetBaseControl.getElementsByTagName("input");

    //Checked/Unchecked all the checkBoxes in side the GridView.
    for (var n = 0; n < Inputs.length; ++n)
        if (Inputs[n].type == 'checkbox' && Inputs[n].id.indexOf(TargetChildControl, 0) >= 0)
            Inputs[n].checked = CheckBox.checked;
    //Reset Counter
    Counter = CheckBox.checked ? TotalChkBx : 0;
}

function ChildClick(CheckBox, HCheckBox) {
    //get target base & child control.
    var HeaderCheckBox = document.getElementById(HCheckBox);

    //Modifiy Counter;            
    if (CheckBox.checked && Counter < TotalChkBx)
        Counter++;
    else if (Counter > 0)
        Counter--;

    //Change state of the header CheckBox.
    if (Counter < TotalChkBx)
        HeaderCheckBox.checked = false;
    else if (Counter == TotalChkBx)
        HeaderCheckBox.checked = true;
}


function divVisibleTrueFalse(id, flag) {

    if (document.getElementById('div' + id) != null) {

        if (flag == 'Y') {
            var div = document.getElementById('div' + id).style.display = '';
        }
        else {
            var div = document.getElementById('div' + id).style.display = 'none';
        }

    }

}



function trVisibleTrueFalse(id, flag) {

    if (document.getElementById('tr' + id) != null) {

        if (flag == 'Y') {
            var div = document.getElementById('tr' + id).style.display = '';
        }
        else {
            var div = document.getElementById('tr' + id).style.display = 'none';
        }

    }

}



//Added by Arati K for show alert on button click on 10 dec 2020
function AlertFunction(message) {
    alert(message);
    //window.close();
}



function javaFun(selectedMenu) {
    //alert(param1);
    var contextVal = "ctl00_MainContent_workflowControl_contextMenuVal";//document.getElementById("<%= contextMenuVal.ClientID%>");
    //Added by Kunal C. to fire conrtext menu item selection command
    //We can get more arguments passed to this function from backend code like  javaFun(selectedMenu,selectedMenuIndex) 
    //Add hidden fields to pass value to backend.
    var btnTest = "ctl00_MainContent_workflowControl_btnHidden";//document.getElementById("<%= btnHidden.ClientID %>");
    contextVal.value = selectedMenu;
    //alert(contextVal.value);
    //call backed method as event
    btnTest.click();
}

function ApplyFliter(SearchString) {

    document.getElementById("ctl00_MainContent_workflowControl_HdnSearchString").value = SearchString;
    document.getElementById("ctl00_MainContent_workflowControl_btnProductSearch").click();
    $('body').find("#ModalBoxInside112").dialog("close"); //Shubham Podhade change for Embeded pop up 20 Jan 2020
}

// Added by Pratik S BOCISSINT-639 - Need Clear Filters button on Workflow Blotter More Filters popup
function ApplyFliterToClear(SearchString) {
    document.getElementById("ctl00_MainContent_workflowControl_HdnSearchString").value = SearchString;
    document.getElementById("ctl00_MainContent_workflowControl_lnkClearFilter").click();
}

function HideMenu() {


    var Div = document.getElementById("DivContextMenu").style.display = "none";
    //alert("Hi");

    return false;
}

function ShowMenu(control) {
    var e = window.event;
    var posx = e.clientX + window.pageXOffset + 'px'; //Left Position of Mouse Pointer
    var posy = e.clientY + window.pageYOffset + 'px'; //Top Position of Mouse Pointer
    document.getElementById(control).style.position = 'absolute';
    document.getElementById(control).style.display = 'inline';
    document.getElementById(control).style.left = posx;
    document.getElementById(control).style.top = posy;
}
function HideMenu(control) {

    document.getElementById(control).style.display = 'none';
}
function isNumberKey(evt) {
    var charCode = (evt.which) ? evt.which : evt.keyCode;

    if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;
    return true;
}

//Commented By Arati Kulkarni on 23-Mar-2021 | START
//<Arati K|| 19-Sep-2019 || To UncheckAll Checkbox on Postback|| Start>
//function UnCheckAll(event) {
//    if (event.target.id == "chkAll" || event.target.id == "") {
//        return;
//    }
//    $(" .Grid [id*='chk']").each(function () {
//        document.getElementById(this.id).checked = false;
//    });
//}
//$(document).click(function () {
//    UnCheckAll(event);
//});
//<Arati K|| 19-Sep-2019 || To UncheckAll Checkbox on Postback|| End>
//function populatetextpageno() {
//    document.getElementById('ctl00_MainContent_workflowControl_txtpageno_Grid').value = document.getElementById('ctl00_MainContent_workflowControl_txtpageno').value;
//}
//Commented By Arati Kulkarni on 23-Mar-2021 | END
function CloseWindow(stokenID) {
    try {
        $.support.cors = true;
        $.ajax({
            type: "POST",
            url: "../FinIQ_User_Controls/ShareSearch/WebMethod.aspx/CloseWorkflowBlotterPopUP",
            cache: false,
            data: "{'stokenID':'" + stokenID + "'}",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            crossDomain: true,
            async: true,
            complete: function (XMLHttpRequest, textStatus, errorThrown) {
            },
            //success: function (data) {
            //    alert('success');
            //    alert(data);
            //    objData = jQuery.parseJSON(data.d);
            //    $('.tbl_cust1').hide();
            //    var objData = jQuery.parseJSON(data.d);
            //    if (objData != null) {
            //        if (objData.length === 0) {
            //        }
            //    }
            //},
            //error: function (XMLHttpRequest, textStatus, errorThrown) {
            //    try {
            //        alert('error');
            //        console.log(textStatus);

            //    } catch (er) {
            //        console.log(er.message);
            //    }
            //}
        });
    } catch (er) {
        console.log(er.message);
    }
}
//Start|Added by Mitali on 11-May-2020| load click on popup close for FI | as asked by DJ
function Embedded_PopUp_Open_WF(PageName, POPUPWidth, POPUPHeight) {
    try {
        /* 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 05 may 2020
        var bondsPopup = GetSizesForBonds(PageName, POPUPWidth, POPUPHeight)
        POPUPHeight = bondsPopup.popupheight;
        POPUPWidth = bondsPopup.popupwidth;
        //added by shreyasv for popup size default 05 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*/

        //Added below line by Shekhar L on 15-Jun-2021
        $('body').find("#ModalBoxInside112").find('iframe').remove();
        $('body').find("#ModalBoxInside112").dialog('destroy').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=""></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) {
                //DrishtyR for FXC 23Jun2021
                // commented and added by sushmita.h on 20 Aug 2021|| Mascli-1081||Popup /oad issue on older chrome version || start
                if (PageName.includes('&nbsp;'))
                    //    PageName = PageName.replaceAll('&nbsp;', '%C2%A0');
                    PageName = PageName.replace(/&nbsp;/g, '%C2%A0');
                // commented and added by sushmita.h on 20 Aug 2021 || Popup oad issue on older chrome version ||end
                //Added below line by Shekhar L on 15-Jun-2021
                $(this).find('iframe').attr("Src", PageName + "&Master_Popup=POPUP")
                chkdigopen = 1;
                $(".ui-widget-overlay").css({
                    background: "rgb(50, 50, 50) !important",
                    opacity: ".50 !important",
                    filter: "Alpha(Opacity=50) !important",
                    overflow: "scroll",

                });
                // || 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%"
                });

                $('iframe').on("load", function () {
                    //debugger
                    $($('iframe')[0].contentDocument).find('link').each(function (i, elem) {
                        if ($(elem).attr('href').split("/")[$(elem).attr('href').split("/").length - 1].split(".")[0].toUpperCase() === 'STYLE1' || $(elem).attr('href').split("/")[$(elem).attr('href').split("/").length - 1].split(".")[0].toUpperCase() === 'ALL_BLACK') {
                            $(elem).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();
                    }
                });
                /* Added By Arati K|| 7 sep 2021 || INT1FIN47-59 || start */
                if (POPUPWidth == 0 && POPUPHeight == 0) {
                    chkInterval = setInterval(function () {
                        if ($(document).find('iframe')[0].contentDocument.body != undefined) {
                            if ($(document).find('iframe')[0].contentDocument.body.text == "" && (POPUPWidth == 0 && POPUPHeight == 0)) {
                                $('body').find("#ModalBoxInside112").dialog("close");
                                clearInterval(chkInterval);
                            } else {
                                clearInterval(chkInterval);
                            }
                        }

                    }, 5000);
                }


                else {
                    chkInterval = setInterval(function () {
                        if ($(document).find('iframe')[0].contentDocument.body != undefined) {
                            if ($(document).find('iframe')[0].contentDocument.body.text == "" && (POPUPWidth == 0 && POPUPHeight == 0)) {
                                $('body').find("#ModalBoxInside112").dialog("close");
                                clearInterval(chkInterval);
                            } else {
                                clearInterval(chkInterval);
                            }
                        }

                    }, 100);
                }

                /* Added By Arati K|| 7 sep 2021 || INT1FIN47-59 || end */

            }
            , 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') {
                    //Umcommented By Samruddhi Wani|On 14-Jan-2021 |Asked By Naman C | to load workflow blotter on popup close | Start
                    $('[id$="btnProductSearch"]').click(); //This is implemented to load workflow blotter on popup close
                    //Umcommented By Samruddhi Wani|On 14-Jan-2021 |Asked By Naman C | to load workflow blotter on popup close | End
                    //Added by Mitali on 30-Apr-2020||for load click on popup close||fi pages, webcket based refresh changes
                    //
                    //if (window.parent.location.pathname == "/FinIQWebApp/Workflow/Trade_Workflow_Blotter.aspx") {
                    //    SubScribBonds_WF(document.getElementById("ctl00_MainContent_workflowControl_hdn_WebsocketIP").value, document.getElementById("ctl00_hdnUserNameForNotification").value);
                    //}
                    if (window.parent.location.pathname == "/FinIQWebApp/Workflow/Trade_Workflow_Blotter.aspx") {
                        //Akshika B | 11-Mar-2021 | Added EQ_Order_Entry to list of pages
                        if (PageName.toUpperCase().indexOf("FINIQ_BOND_ENTRY") > -1 || PageName.indexOf("Bonds_RFQResponseAction") > -1 || PageName.indexOf("Multi_Blotter_Hedge_Entry") > -1 || PageName.indexOf("FinIQ_TradeView") > -1 || PageName.indexOf("EQ_Order_Entry") > -1) {
                            //document.getElementById('<%= btnProductSearch.ClientID%>').click();
                            //alert('before load refresh');
                            $('[id$="btnProductSearch"]').click();
                            //Jassim AR | 20-Jan-2021 | To remove record from lockstatus after dialog box is closed | START
                            var ROID = parseQueryString('DealNum', PageName)
                            $.ajax({
                                type: "POST",
                                url: '../FinIQ_Bond_Entry/FinIQ_Bond_Entry.aspx/UnlockOrders',
                                data: "{'strROID':'" + ROID + "','strObjectCode':'MULTBTL'}",
                                contentType: "application/json; charset=utf-8",
                                dataType: "json",
                                cache: false,
                                async: false,
                                crossDomain: true,
                                success: function (data) {
                                },
                                error: function (request, status, error) {
                                    console.log("error");
                                }
                            });
                            //Jassim AR | 20-Jan-2021 | To remove record from lockstatus after dialog box is closed | END


                        }
                    }

                    //'Added by AkshayD on 30Aug2021 for JIRA ID BOCISSINT-671 Deal Lock Changes START
                    var stokenID = parseQueryString('TokenID', PageName)
                    $.support.cors = true;
                    $.ajax({
                        type: "POST",
                        url: "../FinIQ_User_Controls/ShareSearch/WebMethod.aspx/CloseWorkflowBlotterPopUP",
                        cache: false,
                        data: "{'stokenID':'" + stokenID + "'}",
                        dataType: "json",
                        contentType: "application/json; charset=utf-8",
                        crossDomain: true,
                        async: true,
                        complete: function (XMLHttpRequest, textStatus, errorThrown) {
                        },

                    });
                    //''Added by AkshayD on 30Aug2021 for JIRA ID BOCISSINT-671 Deal Lock Changes END
                    // 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();
                    }

                }
                //
                $("#ifrm11").get(0).contentWindow.postMessage('CloseMe', window.location.origin); //added by Devesh J on 12-Jan-2021 as told by Shekhar Sir
                //<Deepesh.B on 10-Jun-2021 for removing old iframe after closing (as if old pop-up remains causing issue on opening new pop-up window like calling old query string first on page load)>
                var frame = document.getElementById("ifrm11");
                frame.parentNode.removeChild(frame);
                //return false;
                //$('[id$="btnclose"]').click();
            }
        });
    } catch (error) { console.log(error.message); }
}
//End|Added by Mitali on 11-May-2020| load click on popup close for FI | as asked by DJ
//''Added by AkshayD on 30Aug2021 for JIRA ID BOCISSINT-671 Deal Lock Changes
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 AkshayD on 30Aug2021 for JIRA ID BOCISSINT-671 Deal Lock Changes

//START | 16-Sep-2021 | Rajeshree K | Functions added for MASCLI-1161
function base64ToArrayBuffer(base64) {
    var binaryString = window.atob(base64);
    var binaryLen = binaryString.length;
    var bytes = new Uint8Array(binaryLen);
    for (var i = 0; i < binaryLen; i++) {
        var ascii = binaryString.charCodeAt(i);
        bytes[i] = ascii;
    }
    return bytes;
}

function GenerateDocument(Src, documentName, documentType) {
    try {
        debugger;
        console.log("Before decoding base64 string buffer");
        var arrayBuffer = base64ToArrayBuffer(Src);
        console.log("After decoding base64 string buffer");
        const a = document.createElement('a');
        var blob = new Blob([arrayBuffer], { type: documentType });
        a.href = window.URL.createObjectURL(blob);
        a.download = documentName;
        a.style.position = 'fixed';
        a.style.display = 'none';
        a.target = '_blank';
        document.body.appendChild(a);
        console.log("a element appended to Document.body");
        console.log("before a.click");
        a.click();
        console.log("after a.click");
        document.body.removeChild(a);
    } catch (error) { console.log(error.message); }
}
//END | 16-Sep-2021 | Rajeshree K | Functions added for MASCLI-1161



//End|Added by Mitali on 11-May-2020| load click on popup close for FI | as asked by DJ
//Start|Added by Mitali on 30-Apr-2020||for load click on popup close||bonds webcket based workflow refresh changes
function SubScribBonds_WF(WebSocketIP, USERID) {
    //
    try {
        var rfqid = Math.random();
        if (WebSocketIP == '' || WebSocketIP == undefined) {
            WebSocketIP = document.getElementById("ctl00_MainContent_workflowControl_hdn_WebsocketIP").value;
        }
        if (1 == 1) {
            if (rfqid == "") { }
            else {
                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");
                    ws = new WebSocket("" + wsprotocol + "//" + WebSocketIP + "/FinIQService/WorkflowCallback_Refresh.svc");
                }
                catch (error) {
                    //alert(error);
                }
                //alert(ws);
                ws.onopen = function () {
                    //
                    if (ws.readyState == WebSocket.OPEN) {
                        //alert('Subscribed to WF websocket func');
                        ws.send('MASTERSUBSCRIBE|' + USERID);
                        //console.log('MASTERSUBSCRIBE|' + USERID);
                        //ws.send('SUBSCRIBE|' + USERID);
                    }
                    else {
                        //alert('Connection is closed', 'success');
                    }
                };
                ws.onmessage = function (evt) {
                    //
                    //alert('in workflow onmessage');
                    //alert(evt.data);
                    var msg = evt.data;
                    var msgSplit = msg.toString().toUpperCase().split('|');
                    //alert(msgSplit[0]);
                    if (ws.readyState == WebSocket.OPEN && msgSplit[0].toString().toUpperCase() == "SUBSCRIBED") {
                        //alert("Routed to Treasury and " + msgSplit[1].toString() + "", 'success');
                    }
                    else if (msgSplit[0].toString() == "RFQRESPONSE") {
                        var WorkflowName;
                        var MultiWorkflow = msgSplit[3].split(',');
                        var to_referesh = false;
                        var i = 0;
                        for (i = 0; i < MultiWorkflow.length; i++) {
                            if (WorkflowName.toUpperCase() == MultiWorkflow[i].trim().toUpperCase()) {
                                to_referesh = true;
                                break;
                            }
                        }
                        //   <% -- if ('<% =oRes.LoginUserInfo.HomeEntityID%>' == msgSplit[2].trim()) {
                        //    if (to_referesh) {
                        //        setTimeout(ClickProductSearch, 3000);
                        //    }
                        //} --%>
                    }
                    else if (msgSplit[0].toString() == "ONSCREENNOTIFICATION") {
                        //
                        //alert('in WF on ONSCREENNOTIFICATION');
                        if (window.parent.location.pathname == "/FinIQWebApp/Workflow/Trade_Workflow_Blotter.aspx") {
                            var WorkflowName;
                            var EntityId;
                            WorkflowName = document.getElementById('ctl00_MainContent_workflowControl_hdnSelectWorkflowDropdownName').value;
                            EntityId = document.getElementById('ctl00_MainContent_workflowControl_hdn_ddlEntity_ID').value;
                            var MultiWorkflow = msgSplit[3].split(',');
                            var to_referesh = false;
                            var i = 0;
                            for (i = 0; i < MultiWorkflow.length; i++) {
                                if (WorkflowName.toUpperCase().indexOf(MultiWorkflow[i].trim().toUpperCase()) > -1) {
                                    to_referesh = true;
                                    break;
                                }
                            }
                            if (EntityId == msgSplit[2].trim()) {
                                //
                                if (to_referesh) {
                                    if ($('[id$="UpdateProgress1"]').css('display') == 'none') {
                                        ClickProductSearch();
                                    }
                                }
                            }
                        }
                        getBondsNotifCount(document.getElementById("ctl00_hdnUserNameForNotification").value);
                    }
                };
                ws.onerror = function (evt) {
                    //alert('Error occured..');
                    //alert("EventType " + evt.type);
                    //alert("readystate " + ws.readystate);
                    //alert('Error with code : ' + evt.code + '', 'error');
                };
                ws.onclose = function (evt) {
                    //alert('on close');
                    ws.close();
                    SubScribBonds_WF(WebSocketIP, USERID);
                };
            }
        }
    } catch (error) { console.log(error.message); }
}
function ClickProductSearch() {
    try {
        //
        if ($(".ui-widget-overlay").length == 0) {
            if ($('[id$="UpdateProgress1"]').css('display') == 'none') {
                // document.getElementById('= btnProductSearch.ClientID%>').click();
                $('[id$="btnProductSearch"]').click();
            }
            else {
                //alert("already loading"); 
            }
        }
        else {
            //alert("do not refresh");
        }
    } catch (error) { console.log(error.message); }
}
//End|Added by Mitali on 30-Apr-2020||for load click on popup close||bonds webcket based workflow refresh changes
// Added by shreyasv 22 - Dec - 2020 Workflow refresh Signalr START
function WorkflowRefreshSignalR(evt) {
    if (window.parent.location.pathname == "/FinIQWebApp/Workflow/Trade_Workflow_Blotter.aspx") {
        var WorkflowName;
        var EntityId;
        var msg = evt;
        var msgSplit = msg.toString().toUpperCase().split('|');
        WorkflowName = document.getElementById('ctl00_MainContent_workflowControl_hdnSelectWorkflowDropdownName').value;
        EntityId = document.getElementById('ctl00_MainContent_workflowControl_hdn_ddlEntity_ID').value;
        var MultiWorkflow = msgSplit[3].split(',');
        var to_referesh = false;
        var i = 0;
        for (i = 0; i < MultiWorkflow.length; i++) {
            if (WorkflowName.toUpperCase().indexOf(MultiWorkflow[i].trim().toUpperCase()) > -1) {
                to_referesh = true;
                break;
            }
        }
        if (EntityId == msgSplit[2].trim()) {
            if (to_referesh) {
                if ($('[id$="UpdateProgress1"]').css('display') == 'none') {
                    ClickProductSearch();
                }
            }
        }
    }
    getBondsNotifCount(document.getElementById("ctl00_hdnUserNameForNotification").value);
}
// Added by shreyasv 22 - Dec - 2020 Workflow refresh Signalr END
function draggableWf() {
    try {
        $(function () {
            $("#ctl00_MainContent_workflowControl_UPanelWF_Seq_Settings").draggable();
            // $("#<%=UPanelWF_Seq_Settings.ClientID%>").draggable();
            $("#ctl00_MainContent_workflowControl_pnlSetting").draggable();
            // $("#<%=pnlSetting.ClientID%>").draggable();
            $("#ctl00_MainContent_workflowControl_pnlAdvSearch").draggable();
            // $("#<%=pnlAdvSearch.ClientID%>").draggable();
            $("#ctl00_MainContent_workflowControl_pnlQueuesToHide").draggable();
            $("#ctl00_MainContent_workflowControl_pnlCreateViews").draggable(); // Modified by Shubham Podhade on 27-May-2022 for Custom View BBVAORINT-484
        });
    } catch (err) {
        console.log('Error in draggableWf: ' + err);
    }

}

//Added by Shubham Podhade on 09-Apr-2021 for accordion mode support || START
var colspan = 99;
var rowIndex = 0;
var prevHtml = "";
var arrAccordionRows = [];
var accordionRowsCount = 0;

function addAccordionDiv(pageName, selectedRowId, popupHeight, popupWidth, buttonCaption, buttonCaptionFontSize) {
    try {

        rowIndex = parseInt(selectedRowId);
        colspan = parseInt($(document).find('.Grid tr').eq((rowIndex)).find('td').length);
        if (colspan == 0 || colspan == 1 || colspan == 2) {
            colspan = 99;
        }
        prevHtml = '<tr id="trMainAccordion" class="GridItem AccGrid"><td style="width: 100vw !important;" colspan="' + colspan + '"><div style="padding-bottom: 10px;"><span class="closeMe" style="font-size: 13px;cursor: pointer;" id=' + accordionRowsCount + ' onclick="$(this).parent().parent().remove();removeFromAccArr(this.id)">X</span><span style="padding-left: 20px;font-size:' + buttonCaptionFontSize + 'px;">' + buttonCaption + '</span></div><div><iframe  id="iframe" onload = "resizeIframe(this);"  style="width: ' + popupWidth + '% !important;height:' + popupHeight + 'px !important;" scrolling="auto" frameborder="no" src="' + pageName + '"></iframe><div></td></tr>';
        arrAccordionRows = checkIfRowExists(arrAccordionRows, 'rowIndexKey', rowIndex, 'buttonCaptionKey', buttonCaption);
        arrAccordionRows.push({ 'accordionRowsCountKey': accordionRowsCount, 'rowIndexKey': rowIndex, 'prevHtmlKey': prevHtml, 'buttonCaptionKey': buttonCaption });
        accordionRowsCount++;
        for (var i = 0; i < arrAccordionRows.length; i++) {
            $(document).find('.Grid tr.GridItem:not(.AccGrid),tr.GridItemSelect:not(.AccGrid)').eq((arrAccordionRows[i].rowIndexKey)).after(arrAccordionRows[i].prevHtmlKey);
        }
        // $(document).ready(function () {
        if (window.location.href.indexOf("Master_Popup") > -1) {
            $('.Grid').each(function (i, j) {
                $(j).addClass('noFreeze');
                $(j).find('tbody:first', j).height('');
            });
        }
        // });
    } catch (err) {
        console.log("Error in addAccordianDiv :" + err.message);
    }
}
function checkIfRowExists(arr, attr1, value1, attr2, value2) {
    try {
        var ii = arr.length;
        while (ii--) {
            if (arr[ii]
                && arr[ii].hasOwnProperty(attr1)
                && arr[ii].hasOwnProperty(attr2)
                && (arguments.length > 4 && arr[ii][attr1] === value1 && arr[ii][attr2] === value2)) {
                arr.splice(ii, 1);
            }
        }
        return arr;
    } catch (err) {
        console.log('Error in checkIfRowExists:' + err.message);
    }
}

function removeFromAccArr(idToRemove) {
    try {
        arrAccordionRows = arrAccordionRows.filter((item) => item.accordionRowsCountKey != idToRemove);
        //console.log('removeFromAccArr function : ' + arrAccordionRows);
    } catch (err) {
        console.log('Error in removeFromAccArr :', err);
    }
}

(function () {
    if (window.self != window.top) {
        $('table.FinIQ_lblFormName').hide();
    }
})();

function resizeIframe(obj) {
    try {
        $(document).ready(function () {
            $(obj.contentWindow.document).find('.Grid').removeClass('frozenGrid').addClass('noFreeze');
            //Added by Shubham Podhade on 14-Jun-2021 for MASCLI 670 
            if ($(obj.contentWindow.document).find("#ctl00_MainContent_workflowControl_queue_data_grid tbody")[0] != undefined) {
                $($(obj.contentWindow.document).find("#ctl00_MainContent_workflowControl_queue_data_grid tbody")[0]).css({ 'height': 'auto' })
            }
            //DO NOT  remove this code - START
            //alert($(obj.contentWindow.document).find('.Grid').attr('class'));
            //obj.style.height = obj.contentWindow.document.documentElement.scrollHeight + 'px';
            //$('.Grid').each(function (i, j) {
            //    $(j).addClass('noFreeze');
            //    $(j).find('tbody:first', j).height('');
            //});
            //DO NOT  remove this code - END
        });
    }
    catch (err) {
        console.log('Error in resizeIframe :', err);
    }
}

//Added by Shubham Podhade on 09-Apr-2021 for accordion mode support || END
function openNewBrowserWindow(pageAddress, target, winProp) {
    try {
		//Modified Shubham Podhade on 06-May-2022 for setting tab name of a newly opened browser tab. BBVAORINT-327
        //var win = window.open(pageAddress, target, winProp);
		target = 'Loading...';
        var win = window.open(pageAddress);
        //if (typeof win.addEventListener != "undefined") {
        //    win.addEventListener("unload", refreshAccordionDiv, false);
        //}
        win.addEventListener('beforeunload', (event) => {
            console.log('beforeunload called. Now refreshing blotter');
            refreshAccordionDiv();
        });
    } catch (err) {
        console.log('Error in openNewBrowserWindow' + err);
    }
}
function refreshAccordionDiv() {
    try {
        $("#ctl00_MainContent_workflowControl_btnProductSearch").click();
    } catch (err) {
        console.log('Error in refreshAccordionDiv' + err);
    }
}


//Added by Shubham Podhade on 24-Jun-2021 for dyanamic widths to Fav Workflows
function setFavWorkflowWidth() {
    try {
        if ($('#ctl00_MainContent_workflowControl_pnlWF2016Filters').css('display') == 'none') {
            $('.favWorkflow').eq(0).css("padding-left", "5")
        }
        else {
            $('.favWorkflow').eq(0).css("padding-left", "50")
            $('.buttonLinkTab').css("margin-top", "15")
        }
        if ($('.favWorkflow')[0] != undefined) {
            if ($($($('.favWorkflow')[0]).find('a')).length != undefined) {
                for (var i = 0; i < $($($('.favWorkflow')[0]).find('a')).length; i++) {
                    if ($($($('.favWorkflow')[0]).find('a')[i]).width() < 150) {
                        $($($('.favWorkflow')[0]).find('a')[i]).width(110);
                        //Added by Shubham Podhade on 01-Apr-2022 | BBVAORINT-116 | Names of the Blotter Labels not centre aligned
                        $($($('.favWorkflow')[0]).find('a')[i]).css('min-height', '22px')
                        $($($('.favWorkflow')[0]).find('a')[i]).css('padding-top', '7px')
                    }
                    else if ($($($('.favWorkflow')[0]).find('a')[i]).width() < 270) {
                        $($($('.favWorkflow')[0]).find('a')[i]).width(160);
                    }
                    else {
                        $($($('.favWorkflow')[0]).find('a')[i]).width(200)
                    }
                }
            }
        }
    } catch (err) {
        console.log('Error in setFavWorkflowWidth' + err);
    }
}

function callNotifyBlotter() {
    try {
        var objectRefNo = "12345";
        var LoginID = "Shubhamp";
        var message = " Deal ID " + Math.floor(100000 + Math.random() * 900000) + " executed successfully.";
        var objType = "Product";
        var sourceSystem = "TESTSS";
        var entityId = "4";
        NotifyBlotterONObjectCreation(objectRefNo, LoginID, message, objType, sourceSystem,
            entityId);
    } catch (err) {
        console.log('Error while calling NotifyBlotterONObjectCreation method', err);
    }
}

/*Added by Arati k for zoom range slider */
var slider = document.getElementById("myRange");
var output = document.getElementById("demo");
/*Condition added by Rajeshree K for null ref issue*/
if (slider) {
    output.innerHTML = slider.value;

    slider.oninput = function () {
        output.innerHTML = this.value;

    }
}




function Color_Changed(sender) {

    sender.get_element().value = sender.get_selectedColor();

}
// Added by Shubham Podhade on 11-Apr-2022 for Bulk token processing || START

function ShowInfoDialog(csStrSuccDealID, cntSuccDeal, csStrfailDealID, cntFailDeal) {
    try {
        $(document).ready(function () {
            $.support.cors = true;
            $(document).find('[id$="divShowInfoDialog"]').empty();

            $(document).find('#divShowInfoDialog').dialog({
                display: 'block',
                modal: true,
                draggable: true,
                resizable: false,
                autoOpen: true,
                closeOnEscape: true,
                autoOpen: true,
                height: 180,
                width: 300,
                close: function (event, ui) {
                    $(document).find('[id$="divShowInfoDialog"]').dialog('destroy').empty();
                    $("#ctl00_MainContent_workflowControl_btnProductSearch").click();
                }, open: function (event, ui) {
                    $(this).parent().css('position', 'fixed');
                    generateTableTokenProcess(csStrSuccDealID, cntSuccDeal, csStrfailDealID, cntFailDeal);
                }
            });
        });
    } catch (err) {
        console.log('Error in ShowInfoDialog method', err);
    }
}

var arrTokens = [];
var totalTokens = 0;
var totalTokensS = 0;
var totalTokensF = 0;
var tokenHtml;
var tokenHtmlCount;
function generateTableTokenProcess(csStrSuccDealID, cntSuccDeal, csStrfailDealID, cntFailDeal) {
    try {
        $(".ui-dialog-title")[0].innerText = 'Workflow Blotter'
        totalTokens = 0;
        arrTokens = [];
        totalTokensS = 0;
        totalTokensF = 0;
        tokenHtml = ""
        
        for (var i = 0; i < csStrSuccDealID.split('|').length - 1; i++) {
            arrTokens.push({ 'refNo': csStrSuccDealID.split('|')[i], 'status': 'Success' });
            totalTokens++;
            totalTokensS++;
        }
        for (var j = 0; j < csStrfailDealID.split('|').length - 1; j++) {
            arrTokens.push({ 'refNo': csStrSuccDealID.split('|')[i], 'status': 'Failed' });
            totalTokens++;
            totalTokensF++;
        }
        tokenHtmlCount = '<span  style="width:98%;font-weight:600;padding:10px 8px;display:block; min-width:250px;">'
        if (totalTokensS > 0)
            tokenHtmlCount += "Total successfully processed records : " + totalTokensS + "/" + totalTokens;
        tokenHtmlCount += "</span>"
        if (totalTokensF > 0) {

            tokenHtmlCount += "Total records failed to process : " + totalTokensF + "/" + totalTokens;
            tokenHtmlCount += "</span>"
            tokenHtmlCount = '<span  style="width:98%;font-weight:600;padding:10px 8px;display:block; min-width:250px;">'
            tokenHtmlCount += "*For failed records please try again later or contact support."
            tokenHtmlCount += "</span>"
        }
            
        //tokenHtmlCount += "</span>"
        tokenHtml += '<table  class="GridTable"  style="width:98%; min-width:250px;" ><thead class=""><th>FinIQ Ref No</th><th>Processing Status</th></thead>';
        for (var k = 0; k < totalTokens; k++) {
            tokenHtml += "<tr class=''><td>" + arrTokens[k].refNo + "</td><td>" + arrTokens[k].status + "</td></tr>";
        }
        tokenHtml += "</table>";
        tokenHtml += tokenHtmlCount;
        $("#divShowInfoDialog").html(tokenHtml);
    } catch (err) {
        console.log('Error in generateTable method', err);
    }
}
// Added by Shubham Podhade on 11-Apr-2022 for Bulk token processing || END

// Added by Shubham Podhade on 18-May-2022 for Custom View BBVAORINT-484----- START
var blotterMetaDataArr = [];
var showHideCustomViewDiv = true;
var tbl = "";
function getWorkflowBlotterMetaData(wtmId, LoginID, callIdentifier) {
    try {
        var obj = {};
        var inputVar = '';
        obj.wtmId = wtmId;
        obj.LoginID = LoginID;
        obj.callIdentifier = callIdentifier;
        var myPageName = 'Workflow_Custom_View.aspx';
        $.support.cors = true;
        $.ajax({
            type: "POST",
            url: "Trade_Workflow_Blotter.aspx/getWorkflowBlotterMetaData",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            cache: false,
            data: "{'wtmId':'" + wtmId + "','LoginID':'" + LoginID + "','callIdentifier':'" + callIdentifier + "'}",//JSON.stringify(obj),
            crossDomain: true,
            success: function (data) {
                blotterMetaDataArr = data;
                //console.log('getWorkflowBlotterMetaData AJAX Call OK');
                tbl = '';
                tbl += '<tr><td></td></tr>';
                tbl += "<tr><td class='lblCustomView'>Custom View Setup</td><td><button type='button' id='closeCustomView' class='btn lblCloseView' style='width:30px !important;' onclick='CloseCreateViews()'>X</button ></td></tr>";
                for (var i = 0; i < blotterMetaDataArr.d.length; i++) {
                    //console.log('WBM_Blotter_Header:' + blotterMetaDataArr.d[i].WBM_Blotter_Header + ' WBM_Column_Data_type:' + blotterMetaDataArr.d[i].WBM_Column_Data_type);
                    if ((blotterMetaDataArr.d[i].WBM_Blotter_Header != "Actions") && (blotterMetaDataArr.d[i].WBM_Column_Data_type = "TEXT")) {
                        tbl += "<tr><td id='" + blotterMetaDataArr.d[i].WBM_Target_Value + "'>" + blotterMetaDataArr.d[i].WBM_Blotter_Header + "</td><td><input type='text' id='tdCustomView" + i + "' class='txt txtSearchFilter txtView'></td></tr>";
                    }
                }
                tbl += "<tr><td colspan='2' class='tdLineView'><hr class='tdHrLineView'></td></tr>"
                tbl += "<tr><td>View Name</td><td><input type='text' id='txtViewName' class='txt txtSearchFilter btnViewName'></td></tr>"
                tbl += "<tr><td align='center'  class='tdViewButtons' ><input type='button' value='Save' id='btnCreateView' onclick='saveCustomView()' class='btn btnCreateView'></td><td align='center' class='tdViewButtons'><input type='button' value='Clear' id='btnClearView' onclick='clearView()' class='btn btnClearView'><input type='button'  value='Remove' id='btnRemoveView' onclick='removeView()' class='btn txtView btnRemoveView'></td></tr>"

                $("#tblCustomView").html(tbl);
            },
            error: function (x, e) {
                console.log('Error in getWorkflowBlotterMetaData AJAX call' + e);
            }
        });
    } catch (error) {
        console.log("Error in getWorkflowBlotterMetaData method: " + error);
    }
}

var customViewlinksArr = [];
var tblviewLinks;
function getCustomViewData(wtmId, loginId) {
    try {
        $.support.cors = true;
        $.ajax({
            type: "POST",
            url: "Trade_Workflow_Blotter.aspx/getCustomViewData",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            cache: false,
            data: "{'wtmId':'" + wtmId + "','loginId':'" + loginId + "'}",
            crossDomain: true,
            success: function (data) {
                customViewlinksArr = data;
                console.log('getCustomViewData AJAX Call OK');
                //tblviewLinks = data;
                tblviewLinks = '';
                tblviewLinks += "<tr><td style='font-size: 14px;padding-bottom: 12px;'>Your View(s)</td></tr>";
                if (customViewlinksArr.d.length > 0) {
                    for (var i = 0; i < customViewlinksArr.d.length; i++) {
                        tblviewLinks += "<tr><td id='" + i + "'><input type='button'  value='" + customViewlinksArr.d[i].PCS_ViewName + "' id='btnViewLink" + i + "' onclick='linkButtonClick(this)' class='btnViewLink'></td></tr>";
                    }
                }
                else {
                    tblviewLinks += "<tr><td class='tdNoViews'>No views created.</td></tr>";
                }
                
                $("#tblCustomViewList").html(tblviewLinks);
            },
            error: function (x, e) {
                console.log('Error in getWorkflowBlotterMetaData AJAX call' + e);
            }
        });
    } catch (error) {
        console.log("Error in getCustomViewData method: " + error);
    }
}
function linkButtonClick(that) {
    try {
        var myFilterString;
        for (var i = 0; i < customViewlinksArr.d.length; i++) {

            if (that == 'default') {
                    myFilterString = customViewlinksArr.d[i].PCS_FilterString;
                SetCustomViewData(customViewlinksArr.d[i].PCS_FilterString, customViewlinksArr.d[i].PCS_ViewName);
                    break;
            }
            else {
                if (customViewlinksArr.d[i].PCS_ViewName == that.value) {
                    myFilterString = customViewlinksArr.d[i].PCS_FilterString;
                    SetCustomViewData(customViewlinksArr.d[i].PCS_FilterString, that.value);
                    break;
                }
            }
            
        }
    } catch (err) {
        console.log("Error in linkButtonClick method: " + err);
    }
}


function SetCustomViewData(customString, viewName) {
    try {
        var customStringArr = [];
        var blotterHeaderKeyFilterArr = [];
        customStringArr = customString.split("AND");
        for (var i = 2; i < (($('#tblCustomView tr').length) - 3); i++) {
            $($('#tblCustomView tr td input:text')[i-2]).val('')
        }
        for (var j = 0; j < customStringArr.length; j++) {
            if (customStringArr[j].includes('like'))
                blotterHeaderKeyFilterArr.push({ 'blotterHeader': customStringArr[j].substring(customStringArr[j].indexOf("[") + 1, customStringArr[j].lastIndexOf("]")), 'filterValue': customStringArr[j].substring(customStringArr[j].indexOf("%") + 1, customStringArr[j].lastIndexOf("%")) });
        }
        for (var k = 0; k < blotterHeaderKeyFilterArr.length; k++) {
            for (var i = 2; i < ($('#tblCustomView tr').length - 3); i++) {
                if ($($('#tblCustomView tr')[i]).children('td:first').attr('id') == blotterHeaderKeyFilterArr[k].blotterHeader) {
                    $($('#tblCustomView tr td input:text')[i-2]).val(blotterHeaderKeyFilterArr[k].filterValue)
                }
            }
        }
        $('#txtViewName').val(viewName);
    } catch (err) {
        console.log('Error in SetCustomViewData method', err);
    }
}
function clearView() {
    try {
        for (var i = 2; i < (($('#tblCustomView tr').length) - 3); i++) {
            $($('#tblCustomView tr td input:text')[i-2]).val('')
        }
    } catch (err) {
        console.log('Error in clearView method', err);
    }
}
function removeView() {
    try {
        var wtmId = $("#ctl00_MainContent_workflowControl_ddlWorkFlow option:selected").val();
        var viewName = $('#txtViewName').val();
        var loginId = $("#ctl00_hdnFinIQUserID").val();
        if ($('#txtViewName').val() == '') {
            $("#ctl00_MainContent_workflowControl_lblViewInfo").css({ 'color': '#0284e0' });
            $("#ctl00_MainContent_workflowControl_lblViewInfo").text("Please select a view to delete.");
            setTimeout(function () { $("#ctl00_MainContent_workflowControl_lblViewInfo").text('') }, 2000);
            return;
        }
        $.support.cors = true;
        $.ajax({
            type: "POST",
            url: "Trade_Workflow_Blotter.aspx/deleteCustomView",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            cache: false,
            data: '{ "wtmId": "' + wtmId + '", "ViewName": "' + viewName + '", "LoginId":  "' + loginId + '" }',
            crossDomain: true,
            success: function (data) {
                blotterMetaDataArr = data;
                $("#ctl00_MainContent_workflowControl_lblViewInfo").text("View '" + viewName + "' deleted.")
                getCustomViewData($("#ctl00_MainContent_workflowControl_ddlWorkFlow option:selected").val(), $("#ctl00_hdnFinIQUserID").val());
                $('#ctl00_MainContent_workflowControl_pnlCreateViews').show();
                $('.customViewDiv').show();
                clearView();
                $('#txtViewName').val('');
                setTimeout(function () { $("#ctl00_MainContent_workflowControl_lblViewInfo").text('') }, 2000);
                
            },
            error: function (x, e) {
                console.log('Error in setCustomSettingView AJAX call' + e);
            }
        });

        
    } catch (err) {
        console.log('Error in SetCustomViewData method', err);
    }
}
function saveCustomView() {
    try {
        $("#ctl00_MainContent_workflowControl_lblViewInfo").text("");
        debugger;
        if ($('#txtViewName').val() == '') {
            $("#ctl00_MainContent_workflowControl_lblViewInfo").css({ 'color': '#0284e0' });
            $("#ctl00_MainContent_workflowControl_lblViewInfo").text("Please enter view name.");
            return;
        }
        var filterString = "";
        var finalFilterString = "";
        var finalFilterStringA = "";
        for (var i = 2; i < ($('#tblCustomView tr').length - 3); i++) {
            if ($($('#tblCustomView tr td input:text')[i-2]).val().length > 0) {
                filterString = "";
                filterString = "[" + $($('#tblCustomView tr')[i]).children('td:first').attr('id') + "] like " + "\'" + "%" + $($('#tblCustomView tr td input:text')[i-2]).val() + "%" + "\'";
                finalFilterString += filterString + " AND ";
            }
        }
        finalFilterStringA = finalFilterString.split(" ").reverse().slice(2).reverse().join(" ");
        var wtmId = $("#ctl00_MainContent_workflowControl_ddlWorkFlow option:selected").val();
        var viewName = $('#txtViewName').val();
        var loginId = $("#ctl00_hdnFinIQUserID").val();
        var filterString = finalFilterString;
        $.support.cors = true;
        $.ajax({
            type: "POST",
            url: "Trade_Workflow_Blotter.aspx/setCustomSettingView",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            cache: false,
            data: '{ "wtmId": "' + wtmId + '", "ViewName": "' + viewName + '", "LoginId":  "' + loginId + '"  , "filterString":  "' + finalFilterStringA + '"  }',
            crossDomain: true,
            success: function (data) {
                blotterMetaDataArr = data;
                //$("#ctl00_MainContent_workflowControl_lblViewInfo").text("View '" + viewName + "' created successfully.")
                $("#ctl00_MainContent_workflowControl_lblViewInfo").text("View '" + viewName + "' created successfully.");

                getCustomViewData($("#ctl00_MainContent_workflowControl_ddlWorkFlow option:selected").val(), $("#ctl00_hdnFinIQUserID").val());
                $('#ctl00_MainContent_workflowControl_pnlCreateViews').show();
                $('.customViewDiv').show();
                setTimeout(function () { $("#ctl00_MainContent_workflowControl_lblViewInfo").text('') }, 2000);
            },
            error: function (x, e) {
                console.log('Error in setCustomSettingView AJAX call' + e);
            }
        });
    } catch (err) {
        console.log('Error in saveCustomView method', err);
    }
}

function tabIndexChanged(tab) {
    try {
        $('.tabContainerCR .tabs').removeClass('active');
        $('[id$="hdntabs"]').val(tab.id);
    } catch (er) {
        console.log(er.message);
    }
}

var createViewsPanelVisibility = true;
function OpenCreateViews() {
    try {
        $("#ctl00_MainContent_workflowControl_lblViewInfo").text('');
        getCustomViewData($("#ctl00_MainContent_workflowControl_ddlWorkFlow option:selected").val(), $("#ctl00_hdnFinIQUserID").val());
        getWorkflowBlotterMetaData($("#ctl00_MainContent_workflowControl_ddlWorkFlow option:selected").val(), $("#ctl00_hdnFinIQUserID").val(), "");
        createViewsPanelVisibility = false;
        showHideWorkflowFilters();
        $('#ctl00_MainContent_workflowControl_pnlCreateViews').show();
        $('.customViewDiv').show();
        linkButtonClick('default');
    }
    catch (err) {
        console.log('Error in OpenCreateViews panel');
    }
}
function CloseCreateViews() {
    try {
        var span = $('#ctl00_MainContent_workflowControl_lblMsgSetting')[0];
        if (span != undefined)
            span.parentNode.removeChild(span);
        $('#ctl00_MainContent_workflowControl_pnlCreateViews').hide();
        $('.customViewDiv').hide();
        createViewsPanelVisibility = true;
        document.getElementById("overlayDiv").style.display = "none";
    }
    catch (err) {
        console.log('Error in CloseCreateViews panel');
    }
}
var showHideQueueViewTabVisibility = true;
function showHideQueueViewTab() {
    try {
        if (showHideQueueViewTabVisibility) {
            showHideQueueViewTabVisibility = !showHideQueueViewTabVisibility;
            $('.tabView1').css({ 'display': 'none' });
            $('#ctl00_MainContent_workflowControl_btnQueueTab').css({ 'display': 'none' });
            $('#ctl00_MainContent_workflowControl_btnViewTab').css({ 'display': 'none' });
        }
        else {
            showHideQueueViewTabVisibility = !showHideQueueViewTabVisibility;
            $('.tabView1').css({ 'display': 'block' });
            $('#ctl00_MainContent_workflowControl_btnQueueTab').css({ 'display': 'inherit' });
            $('#ctl00_MainContent_workflowControl_btnViewTab').css({ 'display': 'inherit' });
        }

    } catch (err) {
        console.log('Error in showHideQueueViewTab');
    }
}
// Added by Shubham Podhade on 18-May-2022 for Custom View BBVAORINT-484----- END

//Added by Arati K || 23-May-2022 || Queues To Hide accoedian design || Start
var OriginalObj = [];
function OpenQueuesToHide() {

    try {

        var LoginId = document.getElementById('ctl00_MainContent_workflowControl_hdnLoginId').value;
        var Operation = "S";
        var queueIds = "";

        //debugger;
        $('#ctl00_MainContent_workflowControl_pnlQueuesToHide').toggle();

        if ($('#ctl00_MainContent_workflowControl_pnlQueuesToHide').is(":visible")) {
            $('#ctl00_MainContent_workflowControl_pnlQueuesToHide div.pnlQueuesAccList').empty();
            $.support.cors = true;
            $.ajax({
                type: 'POST',
                url: 'Trade_Workflow_Blotter.aspx/GetSetWFQueuesToHide',
                contentType: "application/json; charset=utf-8",
                data: '{ "LoginId": "' + LoginId + '", "Operation": "' + Operation + '", "queueIds":  "' + queueIds + '" }',
                dataType: "json",
                crossDomain: true,
                async: true,
                success: function (data) {
                    if (data != null) {
                        //alert((data.d));
                        OriginalObj = data.d;
                        var flags = [], WFNameArr = [], l = OriginalObj.length, i;
                        $.each(OriginalObj, function (index, value) {
                            if (WFNameArr.indexOf(value.WTM_Title) === -1) {
                                WFNameArr.push(value.WTM_Title);
                            }
                        });
                       //// $(document).find(".pnlQueuesToHide").accordion("destroy");    // Removes the accordion bits
                       // $(document).find(".pnlQueuesToHide").empty();                // Clears the contents
                        $(WFNameArr).each(function (j, WTM_Title) {
                            grepArr = jQuery.grep(OriginalObj, function (n, i) {
                                return (n.WTM_Title.trim() === WTM_Title.trim());
                            });
                            $('.pnlQueuesAccList').append($('<h3>' + WTM_Title.trim() + ' (' + grepArr.length + ')</h3>'));
                            $('.pnlQueuesAccList').append($('<div></div>'));

                            $(grepArr).each(function (i, subItem) {
                                if ($(subItem)[0].WTM_Title.trim() == WTM_Title.trim()) {
                                    if ($(subItem)[0].QueueVisibility == 'Hidden') {
                                        $('.pnlQueuesAccList div:last-child').append($('<span><a title="' + $(subItem)[0].QM_Name.trim() + '" >' + $(subItem)[0].QM_Name.trim() + '</a><input type="checkbox" checked="checked" value="" onchange="javascript:Update_QueuesToHide(this);"/><input id="hdnQMId" type="hidden" value="' + $(subItem)[0].QM_ID + '" /></span>'));
                                    } else {
                                        $('.pnlQueuesAccList div:last-child').append($('<span><a title="' + $(subItem)[0].QM_Name.trim() + '" >' + $(subItem)[0].QM_Name.trim() + '</a><input type="checkbox" value="" onchange="javascript:Update_QueuesToHide(this); "/><input id="hdnQMId" type="hidden" value="' + $(subItem)[0].QM_ID + '" /></span>'));
                                    }
                                }
                            });
                        });
                        //$('.pnlQueuesToHide  .ui-accordion-header').next().slideDown("fast"); 
                        createAccordion();
            
                    }
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    console.log(thrownError);
                }
            });
        }
    }
    catch (err) {
        console.log('Error in OpenQueuesTo hide');
    }
}


function createAccordion() {

  //  $(document).ready(function () {
       
    $(document).find('#ctl00_MainContent_workflowControl_pnlQueuesToHide').find("div.pnlQueuesAccList").accordion({
            header: "h3",
            collapsible: true,
            heightStyle: "content",
            navigation: false,
            active: false,
            event: "click"
    }).accordion("refresh");
       // var prm = Sys.WebForms.PageRequestManager.getInstance();
        //prm.add_endRequest(createAccordion);
    //});
}

//function EC(btn) {
//    if ($(btn).val() == 'Expand All') {
//        $('.pnlQueuesToHide  .ui-accordion-header').next().slideDown("fast");
//    } else {
//        $('.pnlQueuesToHide  .ui-accordion-header').next().slideUp("fast");
//    }
//    $(btn).val($(btn).val() == 'Expand All' ? 'Collapse All' : 'Expand All');
//    return false;
//}

function closeQueuesToHidepanel() {
    try {

        $('#ctl00_MainContent_workflowControl_pnlQueuesToHide').toggle();
        return true;
    }

    catch (err) {
        console.log('Error in closeQueuesToHidepanel hide');
    }
}

function SearchScenario(that, event) {
    try {
        var filter = that.value.toUpperCase();

        $(document).find(".pnlQueuesToHide label").each(function (index, li) {
            var txtValue = $(li).find("a").text();
            if (txtValue.toUpperCase().indexOf(filter) > -1) {
                li.style.display = "";
            } else {
                li.style.display = "none";
            }
        });
        if (filter != '') {
            $('.pnlQueuesToHide  .ui-accordion-header').next().slideDown("fast");
            $(btn).val('Collapse All');
        } else {
            $('.pnlQueuesToHide  .ui-accordion-header').next().slideUp("fast");
            $(btn).val('Expand All');
        }

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



function Update_QueuesToHide(capsuleVal) {
    try {
        // debugger;
        var LoginId = document.getElementById('ctl00_MainContent_workflowControl_hdnLoginId').value;
        var Operation = "U";
        var queueIds = "";
        $('#lblQueuesMsg').empty();


        if ($(capsuleVal).is(':checked')) {
            lblQMId = $(capsuleVal).parent().find('[id$="hdnQMId"]').val();
            lblQMId = lblQMId + ':Mapped'
        }
        else {
            lblQMId = $(capsuleVal).parent().find('[id$="hdnQMId"]').val();
            lblQMId = lblQMId + ':Unmapped'
        }


        $.ajax({
            type: "POST",
            url: 'Trade_Workflow_Blotter.aspx/GetSetWFQueuesToHide',
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            crossDomain: true,
            async: true,
            data: JSON.stringify({ "LoginId": LoginId, "queueIds": lblQMId, "Operation": Operation }),
            success: function (data) {
                if (data != null) {
                    $('#lblQueuesMsg').text('Updated successfully.').fadeIn(1).fadeOut(5000);
                }
            }, error: function (xhr, ajaxOptions, thrownError) {
                $('#lblQueuesMsg').text('Please check logs, data not updated.').fadeIn(1).fadeOut(5000);
                console.log(thrownError);
                return false;
            }
        });

    } catch (er) {
        $('#lblQueuesMsg').text('Please check logs, data not updated.').fadeIn(1).fadeOut(5000);
        console.log(er.message);
        return false;
    }
}

//Added by Arati K || 23-May-2022 || Queues To Hide accoedian design || End


//Added by Arati K || 04-Jun-2022 || Oper personal settings on icon click || START
function OpenPersonalSettingfromIcon() {
    try {
        document.getElementById("overlayDiv").style.display = "block";
        $('#ctl00_MainContent_workflowControl_pnlSetting').show();
        personlSettingPanelVisibility = false;
    }
    catch (err) {
        console.log('Error in OpenPersonalSettingfromIcon');
    }
}
//Added by Arati K || 04-Jun-2022 || Oper personal settings on icon click || END


