var arrColIndex = [];
function ClearFilters1(cFilters, clrFor) {
    try {
        thatTH = $(cFilters).parent().parent('td, th');
        var sTableID = $(thatTH).closest('Table').attr('id');
        var iTHindex = $(".Grid th, .GridHeader td,.GridHeader th, .gridCol th").index(thatTH);
        
        if (clrFor == '1') {
            $(thatTH).find('input[type="text"]').val('');
            $(thatTH).removeClass("filter_0").addClass("filter_1");
        }
        else {
            arrColIndex = [];
            localStorage.removeItem('arrColIndex');
            $(".Grid th, .GridHeader td,.GridHeader th, .gridCol th").find('input[type="text"]').val('');

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

        }
        SearchTable1(sTableID, "", "");

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

function clickOnSort1(sortIcon, sortOrder) {
    
    that = $(sortIcon).parent().parent('td, th');
    var sTableID = $(that).closest('Table');
    var 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 () {
        var 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');
        }

    });
    sortTable1($(sTableID).attr('id'), iTHindex, sortOrder);
}

// sample sorting code

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

//    if (typeof SetSorting_Filter1 == "function") {
//        SetSorting_Filter1();
//    }
//});
function SetSorting_Filter1() {
   // return true;
}
(function SetSorting_Filter() {

    arrColIndex = [];
   
    $(document).on("click keyup", function (event) {
        try {
             e = event;
              popup = $(".dropdown-filter-content");
            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 (e.keyCode == 27) {
                popup.hide(150);
                return true;
            }
            else {
                $(e.target).find('input[type="text"]').focus();
            }
        } catch (er) {
            console.log(er.message);
        }
    });


    $(document).ready(function () {
        try {
           // console.log("SetSorting_Filter1");
            arrColIndex = [];
            if (localStorage.getItem("arrColIndex") != null) {
                // arrColIndex = JSON.parse(localStorage.getItem("arrColIndex"));
            }

            if ($('.Grid:not(.noFilter)').find('td[rowspan]').length <= 0) {
                $(".Grid:not(.noFilter)").find(".Grid th, .GridHeader td, .GridHeader th, .gridCol th").each(function (i, j) {
                var sTableID;
                var iTHindex;
                var SortColIndex;
                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");
                            $(this).append('<div class="dropdown-filter-content" style="display: none;"><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();
                                event.stopPropagation();
                            });
                        }
                    }

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

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

                        $(this).find('input[type="text"]').val(searchString);

                        if (searchString != "") {
                            // $(this).removeClass("filter_1").addClass("filter_0");
                        }

                    }
                }

                if (($(this).html() == "" || $(this).html() == " " || $(this).html() == "&nbsp;")) {
                    $(this).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);
            }
                $('.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().toUpperCase();
                       // console.log(strFilter);
                        SearchTable1(sTableID, iTHindex, strFilter);

                        
                        return false;

                    }
                });
            });
            }

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

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


function sortTable1(sTableID, iColumnIndex, sortOrder) {
    try {

        // $('.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());
                }
            }
        });
        // $("#" + sTableID).find(".Grid th, .GridHeader td, .GridHeader th, .gridCol th").eq(iColumnIndex).addClass("filter_1").removeClass("filter_0");

        //localStorage.removeItem('SortColIndex');
        //localStorage.setItem('SortColIndex', JSON.stringify(iColumnIndex + ":" + sortOrder));
    }

    catch (er) { alert(er.message); }
}

function isDateForSort1(sDate) {
    //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;
}
var rowsFound = 0;
function SearchTable1(sTableID, iColumnIndex, strFilter) {
    try {
        var sfilter;
        var arrData = $('#' + sTableID).find('.GridItem, .GridItemSelect, .AlternatItemStyle').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();
                    //console.log(sfilter);
                });

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

                if (sfilter != "") {
                    if (($(cell).html() != "&nbsp;" || $(cell).html() != undefined)) {
                        // $(cell).removeClass("filter_1").addClass("filter_0");
                    }

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

                }

            }
        });

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

        
        $.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();
                  //  console.log(sfilter);
                    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 {
                        $(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") {
                //Added by Shekhar L. @24-Dec-2021 for single row filter popup visibility issue resolved, MASCLI-2273 work flow blotter - Grid level filter is not working
                if ($(GridTH).offsetParent().parent().find('tbody > tr.gridItem:visible').length > 1) {
                    $(GridTH).find('.dropdown-filter-content').css({ "position":"absolute"});

                } else {
                    $(GridTH).find('.dropdown-filter-content').css({ "position": "fixed" });

                }
                $(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"); }
        }

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