//Designed and Developed by Shekhar L. Copyright 2021 @FinIQ consulting (India) Private Ltd.

//Updated by Shekhar L. @28-Aug-2021 JIRA ID:MASCLI-1162 : blotter order by is not working assigned By Parikshit K.
var arrColIndex = [];
var SortColIndex;
var rowsFound = 0;
var arrGridHeaderText = [];
var searchString = "";
function SetSorting_Filter1() {
    // return true;
}
(function () {
    if (typeof SetSorting_Filter == 'function') {
        SetSorting_Filter();
    }
})();
function SetSorting_Filter() {
    try {
        arrColIndex = []; 

        $(document).ready(function () {
            try {
              
                if (window.top != window.self) { 
                    if ($(window.self.document).find('.Grid').attr('id') == "ctl00_MainContent_workflowControl_queue_data_grid") {
                        $(window.self.document).find('table.Grid[id$="queue_data_grid"]').addClass('noFilter');
                        return false;
                    }
                } 
                window.onbeforeunload = function () {
                    localStorage.removeItem("arrColIndex");
                    localStorage.removeItem("SortColIndex");
                    window.arrGridHeaderText = [];
                    arrColIndex = [];
                    SortColIndex = '';
                    rowsFound = 0;
                    arrGridHeaderText = [];
                };

                if (window.arrGridHeaderText.length > 0) {
                    if ($(".Grid:not(.noFilter)").find(".Grid th, .GridHeader td, .GridHeader th, .gridCol th").text() != (window.arrGridHeaderText.toString()).replace(/,/g, "")) {
                        localStorage.removeItem("arrColIndex");
                        localStorage.removeItem("SortColIndex");
                        window.arrGridHeaderText = [];
                        arrColIndex = [];
                        SortColIndex = '';
                        rowsFound = 0;
                        arrGridHeaderText = [];
                    }
                }


                if ($(document).find('#tblWfFilters').find('select[id$="ddlWorkFlow"]').length > 0) {
                    if (localStorage.getItem("arrColIndex") != null) {
                        arrColIndex = JSON.parse(localStorage.getItem("arrColIndex"));
                    }

                    if (localStorage.getItem("SortColIndex") != null) {
                        SortColIndex = JSON.parse(localStorage.getItem("SortColIndex")).split(":");
                    }
                }
                else if (window.useDT_Enum == 'Y') {
                    if (localStorage.getItem("arrColIndex") != null) {
                        arrColIndex = JSON.parse(localStorage.getItem("arrColIndex"));
                    }

                    if (localStorage.getItem("SortColIndex") != null) {
                        SortColIndex = JSON.parse(localStorage.getItem("SortColIndex")).split(":");
                    }
                }
                if ($('.Grid:not(.noFilter)').find('td[rowspan]').length <= 0) {
                    arrGridHeaderText = [];
                    $(".Grid:not(.noFilter)").find(".Grid th, .GridHeader td, .GridHeader th, .gridCol th").each(function (i, j) {
                        var sTableID;
                        var iTHindex;

                        $(j).removeClass("filter_0").addClass("filter_1");

                        arrGridHeaderText.push($(j).text());
                        if ($(j).find('input[type="checkbox"]').length > 0) {
                            $(this).removeClass("filter_0").removeClass("filter_1");
                        }
                        else if (($(this).find('input[type="checkbox"]').length == 0) && ($(this).children.length > 0)) {

                            if ($(this).find('div.dropdown-filter-content').length == 0) {
                                if (j.innerText == '') {
                                     $(this).removeClass("filter_0").removeClass("filter_1");
                                    //return
                                }
                                else if (j.innerText == " ") {
                                     $(this).removeClass("filter_0").removeClass("filter_1");
                                    //return
                                }
                                else if (j.innerHTML == "&nbsp;") {
                                     $(this).removeClass("filter_0").removeClass("filter_1");
                                    //return
                                }
                                else {
                                    // $(this).removeClass("filter_0").addClass("filter_1");
                                    if ($(j).closest('Table').find('tr').length > 2) {
                                        $(j).append('<div class="dropdown-filter-content" style="display: none;position:absolute !important;"><div class="dropdown-filter-sort" onclick="clickOnSort1(this,\'1\');"><span class="a-to-z asc" data-column="1"> Ascending Order</span></div> <div class="dropdown-filter-sort" onclick="clickOnSort1(this,\'-1\');"><span class="z-to-a desc" data-column="1"> Descending Order</span></div><div class="dropdown-filter-search"><input type="text" class="txtTHFilter"  value="" /></div><div class="ClearFilters"  onclick="ClearFilters1(this,\'1\');">Clear this filter</div><div class="ClearFilters"  onclick="ClearFilters1(this,\'All\');">Clear all filter</div></div>')

                                    } else {
                                        $(j).append('<div class="dropdown-filter-content" style="display: none;position:fixed !important;"><div class="dropdown-filter-sort" onclick="clickOnSort1(this,\'1\');"><span class="a-to-z asc" data-column="1"> Ascending Order</span></div> <div class="dropdown-filter-sort" onclick="clickOnSort1(this,\'-1\');"><span class="z-to-a desc" data-column="1"> Descending Order</span></div><div class="dropdown-filter-search"><input type="text" class="txtTHFilter"  value="" /></div><div class="ClearFilters"  onclick="ClearFilters1(this,\'1\');">Clear this filter</div><div class="ClearFilters"  onclick="ClearFilters1(this,\'All\');">Clear all filter</div></div>')

                                    }
                                    $(j).click(function (event) {
                                        SortFilter_DialogBox1(this);
                                        event.preventDefault(); 
                                        return true;
                                    });
                                }
                            }

                            if (arrColIndex.length > 0) {
                                searchString = "";
                                $(arrColIndex).each(function (iTemp, Obj) {
                                    if (Obj.colIndex == i) {
                                        searchString = JSON.parse(Obj.searchString);

                                        $(j).find('input[type="text"]').val(searchString);
                                        if (searchString != "") {
                                            $(j).removeClass("filter_1").addClass("filter_0");
                                        }

                                        if (($(j).html() == "" || $(j).html() == " " || $(j).html() == "&nbsp;")) {
                                            $(j).removeClass("filter_0").removeClass("filter_1");
                                        }
                                        if (arrColIndex.length > 0 && $('#ctl00_MainContent_dgvWfSetupRpt').length == 1) {
                                            SearchTable1("ctl00_MainContent_dgvWfSetupRpt", arrColIndex[0].colIndex, arrColIndex[0].searchString);
                                        }
                                        else if ($(document).find('#tblWfFilters').find('select[id$="ddlWorkFlow"]').length <= 0 && arrColIndex.length > 0) {
                                            sTableID = j.offsetParent.offsetParent.id;
                                            iTHindex = j.cellIndex;
                                            SearchTable1(sTableID, j.cellIndex, searchString);
                                        } else if (window.useDT_Enum == 'Y' && arrColIndex.length > 0) {
                                            sTableID = j.offsetParent.offsetParent.id;
                                            iTHindex = j.cellIndex;
                                            SearchTable1(sTableID, j.cellIndex, searchString);

                                        }
                                    }
                                });
                            }
                        }
                    });
                    $('.Grid:not(.noFilter) tr th input[type="text"]').each(function (iTHInput, inputBox) {
                        $(inputBox).focus(function () {
                            sTableID = $(this).closest('Table').attr('id');
                            iTHindex = $(this).parent().parent().index($(this).parent());
                        });

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

                                strFilter = $(event.currentTarget).val();
                                if (strFilter != "") {
                                    $(inputBox).closest('th').removeClass("filter_1").addClass("filter_0");
                                    window.arrColIndex = jQuery.grep(window.arrColIndex, function (n, i) {
                                        return (n.colIndex != iTHindex);
                                    });
                                    arrColIndex.push({ "colIndex": iTHindex, "searchString": JSON.stringify(strFilter.toUpperCase()) });

                                }
                                if ($(document).find('#tblWfFilters').find('select[id$="ddlWorkFlow"]').length > 0) {
                                    if (strFilter != "") {
                                        if (typeof arrColIndex != "string" && arrColIndex.length > 0) {
                                            localStorage.removeItem('arrColIndex');
                                            localStorage.setItem('arrColIndex', JSON.stringify(arrColIndex));
                                        }
                                    }
                                    GetWFLMetaData();

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

                                   SearchTable1(sTableID, iTHindex, strFilter); 
                                }
                                //if ($('#' + sTableID).find('.GridItem, .GridItemSelect, .AlternatItemStyle').get().length == rowsFound) {
                                //    $.each(arrData, function (index, row) {
                                //        $(row).css("display", "");
                                //    });
                                //    localStorage.removeItem("arrColIndex");
                                //    localStorage.removeItem("SortColIndex");
                                //    window.arrGridHeaderText = [];
                                //    arrColIndex = [];
                                //    SortColIndex = '';
                                //    rowsFound = 0;
                                //    arrGridHeaderText = [];
                                //    //alert("No data found for applied filter(s)."); 
                                //    return true;
                                //}  
                                
                            }
                            return true;
                        });
                    });

                    //if (SortColIndex.length == 3) {
                    //    if ($(document).find('#' + SortColIndex[2]).length > 0) {
                    //        sortTable1(SortColIndex[2], SortColIndex[0], SortColIndex[1]);
                    //    }
                    //}
                }

                Sys.WebForms.PageRequestManager.getInstance().remove_endRequest(SetSorting_Filter);
                Sys.WebForms.PageRequestManager.getInstance().add_endRequest(SetSorting_Filter);

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


function sortTable1(sTableID, iColumnIndex, sortOrder) {
    try {
        $('#' + sTableID).find('.Grid th, .GridHeader td, .GridHeader th, .gridCol th').eq(iColumnIndex).removeClass("filter_1").addClass("filter_0");
        var arrData = $('#' + sTableID).find('.GridItem, .GridItemSelect, .AlternatItemStyle').get();  //updated by Shekhar @07-Oct-2020 

        arrData.sort(function (a, b) {
            if ($(a).children('td:not("table")').eq(iColumnIndex).children().length > 0) {
                val1 = $(a).children('td:not("table")').eq(iColumnIndex).children().val().toUpperCase() || $(a).children('td:not("table")').eq(iColumnIndex).children().text().toUpperCase() || $(a).children('td:not("table")').eq(iColumnIndex).children().html().toUpperCase();
            } else {
                val1 = $(a).children('td:not("table")').eq(iColumnIndex).text().toUpperCase();
            }

            if ($(b).children('td:not("table")').eq(iColumnIndex).children().length > 0) {
                val2 = $(b).children('td:not("table")').eq(iColumnIndex).children().val().toUpperCase() || $(b).children('td:not("table")').eq(iColumnIndex).children().text().toUpperCase() || $(b).children('td:not("table")').eq(iColumnIndex).children().html().toUpperCase();
            } else {
                val2 = $(b).children('td:not("table")').eq(iColumnIndex).text().toUpperCase();
            }

            str1 = val1;
            str2 = val2;

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

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

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

            }
            else if (str1.indexOf('-') > -1 && str2.indexOf('-') > -1) {
                str1 = isDateForSort1(str1);
                str2 = isDateForSort1(str2);
            }
            else {
                str1 = val1;
                str2 = val2;
            }
            val1 = str1;
            val2 = str2;

            if ($.isNumeric(val1) && $.isNumeric(val2)) {
                return sortOrder == 1 ? val1 - val2 : val2 - val1;
            }

            else {
                return (val1 < val2) ? -sortOrder : (val1 > val2) ? sortOrder : 0;
            }
        });

        $.each(arrData, function (index, row) {
            if ($('#' + sTableID).find('.GridPager').length > 0) {
                $('#' + sTableID).find('.GridPager').hide();
            }
            $('#' + sTableID).find('tbody:first').append(row);
            if ((arrData.length - 1) == index) {

                if ($('#' + sTableID).find('.GridPager').length > 0) {
                    $('#' + sTableID).find('.GridPager').show();
                    $('#' + sTableID).find('tbody:first').append($('#' + sTableID).find('.GridPager').get());
                }
            }
        });
    }
    catch (er) { console.log(er.message); }
}



function SearchTable1(sTableID, iColumnIndex, strFilter) {
    try {
        var sfilter;
        var arrData = $('#' + sTableID).find('.GridItem, .GridItemSelect, .AlternatItemStyle, tr.GridItem:not(.AccGrid) ').get(); //updated by Shekhar @07-Oct-2020 
        //arrColIndex = [];
        $("#" + sTableID).find(".Grid th, .GridHeader th, .GridHeader td, .gridCol th").each(function (colIndex, cell) {
            if ($(this).find('input[type="checkbox"]').length == 0) {
                $(cell).find('input[type="text"]').each(function (iIndex, CellInput) {
                    sfilter = $(CellInput).val() || $(CellInput).text();
                });
                if (sfilter == " ") {
                    sfilter = '';
                    $(cell).find('input[type="text"]').val(sfilter) || $(cell).find('span').text(sfilter);
                    return true
                }
            }
        });

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

        var trDisplay = 0;
        $.each(arrData, function (index, row) {
            if (arrColIndex.length > 0) {
                var displayFlag = 1;
                $(arrColIndex).each(function (icol) {
                    ColumnIndex = JSON.parse(arrColIndex[icol].colIndex);
                    sFilter = JSON.parse(arrColIndex[icol].searchString).toUpperCase();

                    if ($(row).children('td:not("table")').eq(ColumnIndex).children().length > 0) {
                        iTDIndex = $(row).children('td:not("table")').eq(ColumnIndex).children().val().toUpperCase() || $(row).children('td:not("table")').eq(ColumnIndex).children().text().toUpperCase() || $(row).children('td:not("table")').eq(ColumnIndex).children().html().toUpperCase();
                    } else {
                        iTDIndex = $(row).children('td:not("table")').eq(ColumnIndex).text().toUpperCase();
                    }

                    if (iTDIndex.indexOf(sFilter) > -1) {
                        if (displayFlag == 1) {
                            $(row).css("display", "");
                        }
                    } else { 
                        if ($(row).css('AccGrid')!=undefined && $(row).css('AccGrid').length>0) {
                            //Added by Shekhar L. @24-Sep-2021 Mashreq:for Workflow blotter nested accordian not working on "View Client Trades" action Link. 
                        } else {
                            $(row).css("display", "none");
                        }
                        
                        rowsFound++
                        displayFlag = 0;
                    }
                    $('#' + sTableID).find('tbody:first').append(row);
                    if ((arrData.length - 1) == index) {
                        $('#' + sTableID).find('tbody:first').append($('#' + sTableID).find('.GridPager').get());
                    }
                });
            }
            else {
                $(row).css("display", "");
                $('#' + sTableID).find('tbody:first').append(row);
                if ((arrData.length - 1) == index) {
                    $('#' + sTableID).find('tbody:first').append($('#' + sTableID).find('.GridPager').get());
                }
            }
        });
    }
    catch (er) { console.log(er.message); }
    finally {
        //added by Shekhar @16-Sep-2020 
        if (sTableID != undefined) {
            //$('#' + sTableID).css({ 'overflow': 'auto' });
        }
    }
}

function SortFilter_DialogBox1(GridTH) {
    try {
        $($(GridTH)[0].offsetParent).parent().css({ 'overflow': 'auto' });  //added by Shekhar @16-Sep-2020     

        $('.dropdown-filter-content').css("display", "none");
        if ($(GridTH).find('input[type="checkbox"]').length == 0) {
            if ($(GridTH).find(".dropdown-filter-content").css("display") == "none") {
                $(GridTH).find(".dropdown-filter-content").toggle();
                $(GridTH).find('input[type="text"]').focus();
            }
            //if ($(GridTH).find(".dropdown-filter-content").find('input[type="text"]').val() != "") {
            //    $(GridTH).removeClass("filter_1").addClass("filter_0");
            //} else { $(GridTH).removeClass("filter_0").addClass("filter_1"); }
        }
        $(document).off('click keyup').on('click keyup', function (event) {
            try {
                e = event;
                var code = (e.keyCode ? e.keyCode : e.which); 
                popup = $(".dropdown-filter-content:visible");
                if (popup.length > 0) {
                    if (!$('.Grid th, .GridHeader td, .gridCol th, .filter_1, .filter_0').is(e.target) && !popup.is(e.target) && popup.has(e.target).length == 0) {
                        popup.hide(150);
                        return true;
                    }
                    if (code == 27) {
                        popup.hide(150);
                        return true;
                    }
                    else {
                        $(e.target).find('input[type="text"]').focus();
                    }
                }
                return true;

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

function ClearFilters1(cFilters, clrFor) {
    try {
        thatTH = $(cFilters).parent().parent('td, th');
        var sTableID = $(thatTH).closest('Table');
        var iTHindex = $(sTableID).find(".Grid th, .GridHeader td,.GridHeader th, .gridCol th").index(thatTH);
         if (clrFor == '1') {
            $(thatTH).find('input[type="text"]').val('');
            $(thatTH).removeClass("filter_0").addClass("filter_1"); 
            if (localStorage.getItem("SortColIndex") != null) {
                SortColIndex = JSON.parse(localStorage.getItem("SortColIndex")).split(":");
                if (iTHindex == Number(SortColIndex[0])) {
                    localStorage.removeItem("SortColIndex");
                    SortColIndex = '';
                }
            }
            window.arrColIndex = jQuery.grep(window.arrColIndex, function (n, i) {
                return (n.colIndex != iTHindex);
            });
            if (window.arrColIndex.length == 0) {
                localStorage.removeItem('arrColIndex');
                if ($(document).find('#tblWfFilters').find('select[id$="ddlWorkFlow"]').length > 0) { 
                    $(document).find('#ctl00_MainContent_workflowControl_HdnSearchString').val('');
                    $(document).find('#ctl00_MainContent_workflowControl_btnProductSearch').click(); 
                   // GetWFLMetaData();
                }
                else if (window.useDT_Enum == 'Y') {
                    $(document).find('input[id$="HdnSearchString"]').val('');
                    $(document).find('input[id$="btnLoad"]').click();
                }

                else {
                    SearchTable1(sTableID.attr('id'), "", "");
                } 
                
            } else {
                localStorage.setItem('arrColIndex', JSON.stringify(window.arrColIndex));
                if ($(document).find('#tblWfFilters').find('select[id$="ddlWorkFlow"]').length > 0) {
                    GetWFLMetaData();
                }
                else if (window.useDT_Enum == 'Y') { 
                    GenFilterBy_DT();
                }
                else {
                        SearchTable1(sTableID.attr('id'), iTHindex, searchString);
                } 
            }
        }
        else {
            localStorage.removeItem("arrColIndex");
            localStorage.removeItem("SortColIndex");
            window.arrGridHeaderText = [];
            arrColIndex = [];
            SortColIndex = '';
            rowsFound = 0;
            arrGridHeaderText = [];
            $(".Grid th, .GridHeader td,.GridHeader th, .gridCol th").find('input[type="text"]').val('');
            $(".filter_0").addClass("filter_1").removeClass("filter_0");
            if ($(document).find('#tblWfFilters').find('select[id$="ddlWorkFlow"]').length > 0) {
                $(document).find('#ctl00_MainContent_workflowControl_HdnSearchString').val('');
                $(document).find('#ctl00_MainContent_workflowControl_btnProductSearch').click();  
            }
            else if (window.useDT_Enum == 'Y') {
                    $(document).find('input[id$="HdnSearchString"]').val('');
                    $(document).find('input[id$="btnLoad"]').click();
            }
            else {
                SearchTable1(sTableID.attr('id'), "", "");
            }
            return true;
        }  
    } catch (er) { console.log(er.message); }
}

function clickOnSort1(sortIcon, sortOrder) {
    try {
        that = $(sortIcon).parent().parent('td, th');
        sTableID = $(that).closest('Table');
        iTHindex = $(sTableID).find(".Grid th, .GridHeader td, .GridHeader th, .gridCol th").index(that);

        $(sTableID).find(".Grid th, .GridHeader td, .GridHeader th, .gridCol th").each(function () {
            jTHindex = $(sTableID).find(".Grid th, .GridHeader td, .GridHeader th, .gridCol th").index(this);
            if (iTHindex != jTHindex) {
                $(this).find('.sortIco').removeClass('asc desc selected');
                $(this).find('.sortIco').addClass('asc');
            }
        });

        if (localStorage.getItem("SortColIndex") != null) {
            SortColIndex = JSON.parse(localStorage.getItem("SortColIndex")).split(":");
            if ($(sTableID).find(".Grid th, .GridHeader td,.GridHeader th, .gridCol th").eq(SortColIndex[0]).find('input[type="text"]').val() == "") {
                $(sTableID).find('.Grid th, .GridHeader td, .GridHeader th, .gridCol th').eq(SortColIndex[0]).removeClass("filter_0").addClass("filter_1");
            }
        }
        localStorage.removeItem('SortColIndex');
        localStorage.setItem('SortColIndex', JSON.stringify(iTHindex + ":" + sortOrder + ":" + $(sTableID).attr('id')));

        if ($(document).find('#tblWfFilters').find('select[id$="ddlWorkFlow"]').length > 0) {
            GetWFLMetaData(); 
        }
        else if (window.useDT_Enum == 'Y') { 
            GenFilterBy_DT();
        }
        else {
            sortTable1($(sTableID).attr('id'), iTHindex, sortOrder);
            return false;
        } 
    } catch (er) { console.log(er.message); }
}

function getUrlParameter(name) {
    name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
    var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
    var results = regex.exec(location.search);
    return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
};

function isDateForSort1(sDate) {
    try {
        //Change done by Shekhar L on 13-Feb-2020 UCP-136
        matches = sDate.match(/^((([0-9])|([0-2][0-9])|([3][0-1]))\-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\-\d{4})$/i) || sDate.match(/^((([0-9])|([0-2][0-9])|([3][0-1]))\-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\-\d{4}) ([0]?[1-9]|1[0-2]):([0-5]\d):([0-5]\d)\s?(AM|PM)$/i);

        if (matches != null) {
            sDate = Date.parse(new Date(sDate.replace(/-/g, " ")));
        }
        return sDate;
    } catch (er) { console.log(er.message); }
}

var SearchString = '';
var OrderByString = '';
var sWBM_Target_Value = [];

function GetWFLMetaData() {
    try {
        OrderByString = '';
        SearchString = '';

        if ($(document).find('#tblWfFilters').find('select[id$="ddlWorkFlow"]').length > 0) {
            wflID = $(document).find('#tblWfFilters').find('select[id$="ddlWorkFlow"] option:selected').val();
            if (localStorage.getItem("SortColIndex") != null) {
                SortColIndex = JSON.parse(localStorage.getItem("SortColIndex")).split(":");
            }
            if (localStorage.getItem("arrColIndex") != null) {
                arrColIndex = JSON.parse(localStorage.getItem("arrColIndex"));
            }
            if (SortColIndex.length <= 0 && arrColIndex.length <= 0) {
                return false;
            }
            var servIP = window.location.origin + '/FinIQService';
            var UserID = document.getElementById("ctl00_hdnUserNameForNotification").value;

            $.ajax({
                type: 'POST',
                url: servIP + '/RestAPIWorkflowWrapper.svc/getWorkflowBlotterMetaData',
                data: JSON.stringify({ "workflowId": wflID, "loginid": UserID }),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                crossDomain: true,
                async: false,//(navigator.vendor == "") ? false : true,
                success: function (data) {
                    if (data != null) {
                        data.getWorkflowBlotterMetaDataResult.push({
                              "Size": "1"
                            , "WBM_Blotter_Header": "FinIQ Ref No"
                            , "WBM_Column_Data_type": "TEXT"
                            , "WBM_Misc1": ""
                            , "WBM_Misc2": ""
                            , "WBM_Sequence": "1"
                            , "WBM_Target_Value": "TI_DealNo"
                            , "WBM_UseForFilter": ""
                            , "WSS_Active_YN": ""
                            , "WSS_Misc1": ""
                            , "WSS_Misc2": ""
                            , "WSS_Misc3": ""
                            , "WSS_Misc4": ""
                            , "WSS_Misc5": ""
                            , "WSS_UseForFilter": "N"
                            , "WSS_Visible_YN": ""
                            , "WSS_WBM_Blotter_Header": ""
                            , "WSS_WBM_Column_Data_type": ""
                        });
                        $(window.arrColIndex).each(function (index, objCol) {
                            colHText = $(".Grid:not(.noFilter)").find(".Grid th, .GridHeader td, .GridHeader th, .gridCol th").eq(parseInt(objCol.colIndex))[0].innerText;

                            colHText = colHText.substring(0, (colHText.indexOf('\n') == -1 ? colHText.length : colHText.indexOf('\n')));
                            sWBM_Target_Value = jQuery.grep($(data.getWorkflowBlotterMetaDataResult), function (wbm) {
                                return (wbm.WBM_Blotter_Header == colHText);
                            });
                            
                            if (sWBM_Target_Value.length > 0) {
                                if (SearchString != '') {
                                    SearchString = SearchString + ' AND '
                                }
                                SearchString = SearchString + '[' + sWBM_Target_Value[0].WBM_Target_Value.trim() + "] LIKE " + "'%" + JSON.parse(objCol.searchString.trim()) + "%' ";
                            }
                        });

                        if (SortColIndex.length >= 3) {
                            OrderByString = '';
                            colHText = $(".Grid:not(.noFilter)").find(".Grid th, .GridHeader td, .GridHeader th, .gridCol th").eq(parseInt(SortColIndex[0]))[0].innerText;
                            colHText = colHText.substring(0, (colHText.indexOf('\n') == -1 ? colHText.length : colHText.indexOf('\n')));

                            sWBM_Target_Value = jQuery.grep($(data.getWorkflowBlotterMetaDataResult), function (wbm) {
                                return (wbm.WBM_Blotter_Header == colHText);
                            });
                            if (sWBM_Target_Value != '') {
                                OrderByString = sWBM_Target_Value[0].WBM_Target_Value.trim() + ' ' + (SortColIndex[1] == '-1' ? 'DESC' : 'ASC');
                            }
                        }
                        $(document).find('#ctl00_MainContent_workflowControl_HdnSearchString').val('');
                        if (OrderByString != '') {
                            $(document).find('#ctl00_MainContent_workflowControl_HdnSearchString').val(SearchString + ':' + OrderByString);
                        } else {
                            $(document).find('#ctl00_MainContent_workflowControl_HdnSearchString').val(SearchString);
                        } 
                        $.ajax({
                            type: 'POST',
                            url: '../FinIQ_User_Controls/FinIQ_WebMethods.aspx/Clear_SessionVariable',
                            data: JSON.stringify({"VariableID": "MoreFiltersApplied" }),
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",
                            crossDomain: true,
                            async: false,//(navigator.vendor == "") ? false : true,
                            success: function (data) { },
                            error: function (xhr, ajaxOptions, thrownError) {
                                console.log(thrownError); 
                            }
                        });
                     
                        $(document).find('#ctl00_MainContent_workflowControl_btnProductSearch').click();
                        
                        return true;
                    }
                    //return false;
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    console.log(thrownError);
                    OrderByString = '';
                    SearchString = '';
                    return true;
                }
            });
        }

    } catch (er) {
        console.log(er.message);
        return false;
        OrderByString = '';
        SearchString = '';
        return true;
    } 

}



function GenFilterBy_DT(){
    try {
        OrderByString = '';
        SearchString = '';
        data = window.GridColumns;
        if (data != null) {
            $(window.arrColIndex).each(function (index, objCol) { 
                 
                    if (SearchString != '') {
                        SearchString = SearchString + ' AND '
                    }
                    SearchString = SearchString + window.GridColumns[objCol.colIndex].trim() + " LIKE " + "'%" + JSON.parse(objCol.searchString.trim()) + "%' ";
            });

            if (SortColIndex.length >= 3) {
                OrderByString = ''; 
                OrderByString = window.GridColumns[parseInt(SortColIndex[0])].trim() + ' ' + (SortColIndex[1] == '-1' ? 'DESC' : 'ASC'); 
            }
            $(document).find('input[id$="HdnSearchString"]').val('');
            if (OrderByString != '') {
                $(document).find('input[id$="HdnSearchString"]').val(SearchString + ':' + OrderByString);
            } else {
                $(document).find('input[id$="HdnSearchString"]').val(SearchString);
            }

            $.ajax({
                type: 'POST',
                url: '../FinIQ_User_Controls/FinIQ_WebMethods.aspx/Clear_SessionVariable',
                data: JSON.stringify({ "VariableID": "MoreFiltersApplied" }),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                crossDomain: true,
                async: false, 
                success: function (data) { },
                error: function (xhr, ajaxOptions, thrownError) {
                    console.log(thrownError);
                }
            });

            $(document).find('input[id$="btnLoad"]').click();

            return true;
        }
    } catch (er) {
        console.log(er.message);
        return false;
        OrderByString = '';
        SearchString = '';
        return true;
    }
}