let pubrowtotal = 0;
$(document).ready(function () {





    try {
        $("#MainContent_Panel1").css('height', $(window).height() - 20);
    } catch (err) { }




    $("#MainContent_txt_SeqNo_0").html("1");

    try {
        $("#g2").css('height', $(window).height() - 180);
    } catch (err) { }


    $("#tbldt tr").find('input[type="text"]').each(function () {

        try {

            $(this).css('border-style', 'none');
        } catch (err) { };

    });

    pubcurrentpagestock = 1;
    pubirow = 0;
    pubfilter = '';
    getdata(1, 0, '', 0);

    setTimeout(function () {
        try {
            let rowCount = $('#tbldt tr').length;
            rowCount = rowCount - 1;




            let totalpage = Math.ceil(rowCount / 20.00);
            let strpage = "Page 1 of " + totalpage.toString() + " (" + rowCount.toString() + " record)";

            $("#amtrowpage").html(strpage);
        } catch (err) { };
    }, 2000);





});



function getnext() {


    var elmnt = document.getElementById("tbdy");

    var y = elmnt.scrollTop;
    var x = elmnt.scrollHeight;
    var n = elmnt.clientHeight;
    //$("#MainContent_txt_docno").val(parseInt(y, 0).toString() + "," + (x - n).toString());
    if (parseInt(y, 0) == (x - n) - 1 || parseInt(y, 0) == (x - n)) {

        pubcurrentpagestock = pubcurrentpagestock + 1;
        try {

            setTimeout(
              function () {
                  getdata(pubcurrentpagestock, pubirow, pubfilter, parseInt(y, 0));



              }, 500);



        } catch (err) { };



    }

}




let pubirow = 0;
let pubcurrentpagestock = 1;
let pubfilter = "";


function getdata(currentpage, i, filterstring, scposstock) {

    pubfilter = filterstring;

    let userid = $('#lbluserdetail').html();
    $.ajax({
        type: "POST",
        url: "ApproveList.aspx/getDataApprove",
        data: '{currentpage:"' + currentpage + '",filterstring:"' + filterstring + '",userid:"'+userid+'"}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {

            var xmlDoc = $.parseXML(response.d);
            var xml = $(xmlDoc);
            var customers = xml.find("Table");

            if (response.d == "<NewDataSet />") {


                if (currentpage == '1') {
                    alert("Data not found.");
                    $("#amtrowpage").html("");
                    setTimeout(function () {
                        $("#amtrowpage").html("");
                        //location.reload();
                    }, 1000);
                }

                //currentpagegv = 1;

                controlpage();
                var iseq = 1;

                setTimeout(function () {

                    $('#tbldt tbody>tr span').each(function () {
                        var ctl = $(this).attr('id');
                        if (ctl.indexOf("Seq") != -1) {

                            $(this).html(iseq.toString());
                            iseq++;

                        }
                        if (ctl.indexOf("DocNo") != -1) {
                            var arr = ctl.split('_');
                            if (arr[3] != "0" && $(this).html() == "") {

                                $(this).closest('tr').remove();


                            }


                        }

                    });
                }, 500);



                response = "";
                xmlDoc = "";
                xml = "";
                customers = "";

            } else {



                $.each(customers, function () {
                    var customer = $(this);

                    try {
                        addrow("N");
                        $('#MainContent_txt_DocNo_' + i.toString()).html($(this).find("DocNo").text());
                        $('#MainContent_txt_Section_' + i.toString()).html($(this).find("Section").text());
                        $('#MainContent_txt_Shop_' + i.toString()).html($(this).find("Shop").text());
                        $('#MainContent_txt_ScrapType_' + i.toString()).html($(this).find("ScrapType").text());
                        $('#MainContent_txt_NGFrom_' + i.toString()).html($(this).find("NGFrom").text());
                        $('#MainContent_txt_DocStatus_' + i.toString()).html($(this).find("DocStatus").text());
                        let strremark = $(this).find("ApproveRemark").text();
                        document.getElementById("MainContent_txt_Remark_" + i.toString()).title = $(this).find("ApproveRemark").text();

                        if ($(this).find("ApproveRemark").text().length > 15) {
                            strremark = $(this).find("ApproveRemark").text().substring(0, 15);

                        }
                        $('#MainContent_txt_Remark_' + i.toString()).html(strremark);
                        $('#MainContent_txt_DocStatus_' + i.toString()).css({ 'font-size': '8px', 'line-height': '10px' });
                        var d = $(this).find("DocDate").text().slice(0, 10).split('-');
                        if ($(this).find("DocStatus").text().indexOf('slip') != -1) {
                            $('#MainContent_txt_DocStatus_' + i.toString()).css({ 'font-size': '8px', 'line-height': '10px', 'color': '#098E19 ' });
                        }
                        else if ($(this).find("DocStatus").text().indexOf('Reject') != -1) {
                            $('#MainContent_txt_DocStatus_' + i.toString()).css({ 'font-size': '8px', 'line-height': '10px', 'color': 'red' });
                        }
                        else {
                            $('#MainContent_txt_DocStatus_' + i.toString()).css({ 'font-size': '8px', 'line-height': '10px', 'color': '#F5790B', });

                        }
                        var year = parseInt(d[0].toString());
                        $('#MainContent_txt_DocDate_' + i.toString()).html(year + '-' + d[1].toString() + '-' + d[2].toString());



                        i++;
                        pubirow = i;
                    } catch (err) { } finally { };

                });

             

                response = "";
                xmlDoc = "";
                xml = "";
                customers = "";
                setTimeout(function () {
                    var iseq = 1;
                    $('#tbldt tbody>tr span').each(function () {
                        var ctl = $(this).attr('id');

                        if (ctl.indexOf("Seq") != -1) {

                            $(this).html(iseq.toString());
                            iseq++;

                        }
                        if (ctl.indexOf("DocNo") != -1) {
                            if ($(this).html() == "") {

                                $(this).closest('tr').remove();
                            }


                        }

                    });
                    if (currentpage > 1) {
                        $("#tbdy").animate({ scrollTop: (scposstock + 100) }, "fast");
                    }

                  


                }, 500);

            }
        },
        failure: function (response) {

        },
        error: function (response) {

        }
    });


}


function newrows(ctl) {
    inputrow = 0;
    var resindex = ctl.id.split("_");
    var irow = resindex[2].toString();

    irow = irow + 1;
    if (irow >= inputrow) {

        addrow("Y");

    }
}

let inputrow = 0;
function addrow(news) {



    $('#tbldt tr').find('span').each(function () {


        if ($(this).attr('id').indexOf('Seq') != -1) {

            var ctlname = $(this).attr('id');
            var arrctl = ctlname.split('_');

            inputrow = parseFloat(arrctl[3].toString());



        }
    });

    var aClone = $('#tbldt tbody>tr:last').clone(true)
    var regex = new RegExp("_" + inputrow.toString(), "g");
    var newrow = aClone.html().replace(regex, "_" + (inputrow + 1).toString());
    inputrow++;
    $("#tbldt > tbody:last").append("<tr id='rowd_" + inputrow.toString() + "'>" + newrow + "</tr>");

    controlpage();




    let iseq = 1;
    $('#tbldt tbody>tr span').each(function () {
        let ctl = $(this).attr('id');
        if (ctl.indexOf("Seq") != -1) {
            if ($(this).is(':hidden')) {

            } else {
                $(this).html(iseq.toString());
                iseq++;

            }
        }
    });
}


function search() {
    let filter = "";
    let docno = $("#MainContent_txt_docno").val();
    let section = $('#MainContent_ddl_section option:selected').text();
    let sectionno = $('#MainContent_ddl_section').val();
    if (docno.length > 0) {
        filter = " and hd.DocNo='" + docno + "'";

    }
    else if (sectionno != "" && section != "ALL") {
        filter = " and hd.Section='" + section + "'";

    }

    let dstart = $('#d_RDate').val();
    let mstart = $('#m_RDate').val();
    let ystart = $('#y_RDate').val();

    let dend = $('#d_RDate1').val();
    let mend = $('#m_RDate1').val();
    let yend = $('#y_RDate1').val();

    let startdate = '';
    if (dstart == '') {

        startdate = '';

    } else {

        if (parseFloat(ystart.replace(/,/g, '')) >= 2500) {
            ystart = parseFloat(ystart.replace(/,/g, '')) - 543;
        }

        startdate = ystart.toString() + "-" + mstart.toString() + "-" + dstart.toString();

    }

    let enddate = '';
    if (dend == '') {

        enddate = '';

    } else {

        if (parseFloat(yend.replace(/,/g, '')) >= 2500) {
            yend = parseFloat(yend.replace(/,/g, '')) - 543;
        }

        enddate = yend.toString() + "-" + mend.toString() + "-" + dend.toString();

    }

    let filtedate = ''
    if (dstart != '' && dend != '') {

        filtedate = " and hd.DocDate between '" + startdate + "' and '" + enddate + " 23:59:59'";

    } else if (dstart.length > 0) {
        filtedate = " and hd.DocDate = '" + startdate + "'";

    }

    else {

        filtedate = "";
    }

    filter = filter + filtedate;
    cleartbl();
    pubcurrentpagestock = 1;
    pubirow = 0;
    pubfilter = "";
    setTimeout(function () {
        getdata(1, 0, filter, 0);
    }, 500);

    setTimeout(function () {
        try {
            let rowCount = $('#tbldt tr').length;
            rowCount = rowCount - 1;

            if (filter == "") {
                rowCount = pubrowtotal;

            }



            let totalpage = Math.ceil(rowCount / 20.00);
            let strpage = "Page 1 of " + totalpage.toString() + " (" + rowCount + " record)";

            $("#amtrowpage").html(strpage);
        } catch (err) { };
    }, 2000);


}



function cleartbl() {


    $('#tbldt tbody>tr input[type="text"]').each(function () {


        var ctl = $(this).attr('id');
        if (ctl.indexOf("SeqNo") != -1) {
            var arr = ctl.split('_');

            if (arr[3] != "0") {

                $("#" + ctl).parents("tr").remove();


            }


        }

    });

    setTimeout(function () {
        $('#tbldt tbody>tr span').each(function () {

            $(this).html("");

        });

        $("#amtrowpage").html("");
    }, 500);



}
function openedit(ctl) {
    let resindex = ctl.id.split("_");
    let irow = resindex[2].toString();
    let docno = $("#MainContent_txt_DocNo_" + irow.toString()).html();
    let detpid = $('#lblDept').html();
    let userid = $('#lbluserdetail').html();
    var Base64 = { _keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=", encode: function (e) { var t = ""; var n, r, i, s, o, u, a; var f = 0; e = Base64._utf8_encode(e); while (f < e.length) { n = e.charCodeAt(f++); r = e.charCodeAt(f++); i = e.charCodeAt(f++); s = n >> 2; o = (n & 3) << 4 | r >> 4; u = (r & 15) << 2 | i >> 6; a = i & 63; if (isNaN(r)) { u = a = 64 } else if (isNaN(i)) { a = 64 } t = t + this._keyStr.charAt(s) + this._keyStr.charAt(o) + this._keyStr.charAt(u) + this._keyStr.charAt(a) } return t }, decode: function (e) { var t = ""; var n, r, i; var s, o, u, a; var f = 0; e = e.replace(/[^A-Za-z0-9\+\/\=]/g, ""); while (f < e.length) { s = this._keyStr.indexOf(e.charAt(f++)); o = this._keyStr.indexOf(e.charAt(f++)); u = this._keyStr.indexOf(e.charAt(f++)); a = this._keyStr.indexOf(e.charAt(f++)); n = s << 2 | o >> 4; r = (o & 15) << 4 | u >> 2; i = (u & 3) << 6 | a; t = t + String.fromCharCode(n); if (u != 64) { t = t + String.fromCharCode(r) } if (a != 64) { t = t + String.fromCharCode(i) } } t = Base64._utf8_decode(t); return t }, _utf8_encode: function (e) { e = e.replace(/\r\n/g, "\n"); var t = ""; for (var n = 0; n < e.length; n++) { var r = e.charCodeAt(n); if (r < 128) { t += String.fromCharCode(r) } else if (r > 127 && r < 2048) { t += String.fromCharCode(r >> 6 | 192); t += String.fromCharCode(r & 63 | 128) } else { t += String.fromCharCode(r >> 12 | 224); t += String.fromCharCode(r >> 6 & 63 | 128); t += String.fromCharCode(r & 63 | 128) } } return t }, _utf8_decode: function (e) { var t = ""; var n = 0; var r = c1 = c2 = 0; while (n < e.length) { r = e.charCodeAt(n); if (r < 128) { t += String.fromCharCode(r); n++ } else if (r > 191 && r < 224) { c2 = e.charCodeAt(n + 1); t += String.fromCharCode((r & 31) << 6 | c2 & 63); n += 2 } else { c2 = e.charCodeAt(n + 1); c3 = e.charCodeAt(n + 2); t += String.fromCharCode((r & 15) << 12 | (c2 & 63) << 6 | c3 & 63); n += 3 } } return t } }
    var encodedString = Base64.encode(userid);

    window.location = "Approve?user=" + encodedString;

   





}
function openreport(ctl) {
    let resindex = ctl.id.split("_");
    let irow = resindex[2].toString();
    let docno = $("#MainContent_txt_DocNo_" + irow.toString()).html();

    window.open(
     "rptScrapReportFlow?docno=" + docno,
     '_blank' // <- This is what makes it open in a new window.
    );



}
