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



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

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

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

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

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

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

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

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


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

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

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

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

        });


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

            HideDialogBox();

            arrColIndex = [];


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

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

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

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

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


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

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

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


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

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

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

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

        });

        // RemovePagination();


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



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

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

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

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

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

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


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

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

            str1 = val1;
            str2 = val2;


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



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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

                });

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

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


function SortFilter_DialogBox(GridTH) {
    try {

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




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

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


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

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

function isDateForSort(sDate) {

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

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

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

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

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

