let pubpartnumber = "";
let pubmachineid = "";
let pubpara = "";
//
$(document).ready(function () {


    getdataheader();


});
function gettotalitem()
{

    $.ajax({
        type: "POST",
        url: "Machine_check_item.aspx/totalitem",
        data: '{partnumber:"' + pubpartnumber + '",machineid:"' + pubmachineid + '"}',
        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 />") {


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



            } else {



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

                    try {
                       
                        let totalnum = $(this).find("totalitem").text();
                        $("#totalrow").html(totalnum +" items.")
                       


                    } catch (err) { } finally { };
                
                });



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

            }
        },
        failure: function (response) {

        },
        error: function (response) {

        }
    });



}

function getdataheader()
{

    const today = new Date();
    let day = String(today.getDate()).padStart(2, '0');
    let month = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
    let year = today.getFullYear();
    

    let currentDate = year + '/' + month + '/' + day;
    
    let str_para = getUrlVars()["para"];
    pubpara = str_para;
    let 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(/rn/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 } }
    let de_para = Base64.decode(str_para);
    if(de_para.indexOf("|")!=-1)
    {
        let arr_para = de_para.split('|');
        let ddate = arr_para[0];
        let partnumber = arr_para[1];
        let empid = arr_para[2];
        let empname = arr_para[3];
        let machineid = arr_para[4];
        let machinename = arr_para[5];
        let model = arr_para[6];

        pubpartnumber = partnumber;
        pubmachineid = machineid;


        $("#MainContent_txt_checkdate").html(ddate);
        $("#MainContent_txt_partnumber").html(partnumber);
        $("#MainContent_txt_model").html(model);
        $("#MainContent_txt_machine").html(machineid + ":" + machinename);
        $("#MainContent_txt_inspector").html(empid + ":" + empname);



        pubcurrentpage_checkitem = 1;
        pubirow = 0;
        pubfilter = "";
        getdata_checkitem(1, 0, '', 0);
        gettotalitem();



    }

   




}

function newrows(ctl) {

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


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

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

            let irow = parseFloat(arrctl[3].toString());
            irow = irow + 1;
            addrow("Y");
            return false;



        }
    });

}

let inputrow_checkitem = 0;
function addrow(news) {



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


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

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

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



        }
    });

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






}
function getnext_checkitem() {


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

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

        let amtrow = $('#tbldt tbody>tr').length;
        amtrow = amtrow - 1;
        let pagenumber = Math.ceil(amtrow / 10);
        if (pubcurrentpage_checkitem == pagenumber) {
            pubcurrentpage_checkitem = pubcurrentpage_checkitem + 1;
            try {

                setTimeout(
                  function () {
                      getdata_checkitem(pubcurrentpage_checkitem, pubirow_checkitem, pubfilter_checkitem, parseInt(y, 0));




                  }, 500);



            } catch (err) { };
        }

       


    }

}


let pubirow_checkitem = 0;
let pubcurrentpage_checkitem = 1;
let pubfilter_checkitem = "";


function getdata_checkitem(currentpage, i, filterstring, scposstock) {
    $("#loader").show();
    $.ajax({
        type: "POST",
        url: "Machine_check_item.aspx/getItem",
        data: '{currentpage:"' + currentpage + '",filterstring:"' + filterstring + '",partnumber:"'+pubpartnumber+'",machineid:"'+pubmachineid+'"}',
        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 />") {

                $("#loader").hide();
                if (currentpage == '1') {
                    alert("Data not found.");
                    //setTimeout(function () {
                    //    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("item_") != -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");
                        let status = $(this).find("input_type").text();
                        let itemname = $(this).find("itemname").text();
                        let inspectionid = $(this).find("inspectid").text();
                        let equid = $(this).find("equid").text();
                        let item_color = $(this).find("item_color").text();
                        if (item_color.indexOf('#') != -1)
                        {
                            $("#MainContent_txt_item_" + i.toString()).html("<a href='#' onclick='javascript:openinputresult(" + status + "," + equid + "," + inspectionid + ");return false;'  style='text-decoration:none;font-size:14px;line-height:20px;'>" + itemname + " </a>");
                            $("#MainContent_txt_item_" + i.toString()).parents('td').css('background', item_color);

                        }
                        else
                        {
                            $("#MainContent_txt_item_" + i.toString()).html("<a href='#' onclick='javascript:openinputresult(" + status + "," + equid + "," + inspectionid + ");return false;'  style='text-decoration:none;font-size:14px;line-height:20px;'>" + itemname + " </a>");
                            $("#MainContent_txt_item_" + i.toString()).parents('td').css('background', '#DCDCDC');

                        }


                        i++;
                        pubirow_checkitem = i;
                    } catch (err) { } finally { };
                    $("#loader").hide();
                });



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


                        if (ctl.indexOf("item_") != -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 openinputresult(status, equid, inspectionid) {

    let para = equid + "|" + inspectionid + "|";
    let 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(/rn/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 } }
    let str_para = Base64.encode(para);
    if (status == "1")
    {
        window.location.href = "Machine_input_check_status?para=" + str_para + "&link=" + pubpara;

    }
    else
    {

        window.location.href = "Machine_input_check_number?para=" + str_para + "&link=" + pubpara;

    }


}



function requestapprove() {
    let reqstatus = "";

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


        if ($(this).css('background-color') == "rgb(248, 24, 61)" || $(this).css('background-color') == "rgb(119, 169, 249)") {

            reqstatus = "Y";

        }

        
    });


    setTimeout(function () {
        if (reqstatus == "") {

            swal(
              'Warning',
              'Please check status.',
              'warning'
            );


        }
        else {

            swal({
                title: 'Are you sure?',
                text: "Do you want request apporve!",
                type: 'question',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: 'Yes, request it!'
            }).then(function (result) {
                if (result.value) {



                    $.ajax({
                        type: "POST",
                        url: "Machine_check_item.aspx/sendrequest",
                        data: '{partnumber: "' + pubpartnumber + '"}',
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (response) {

                            if (response.d.length == 0) {


                                swal({
                                    title: "Success",
                                    type: 'success',
                                    text: "Data saved successfully",
                                    timer: 1000,
                                    showConfirmButton: false,
                                    timerProgressBar: true
                                })

    .then(() => {
        swal({ 
            title: 'Finished!',
            type: 'info',
            timer: 1000,
            showConfirmButton: false
        })
    })


                            }
                            else {
                                swal(
                  'Error',
                  response.d.toString(),
                  'error'
                  );


                            }


                        },
                        failure: function (response) {
                            alert(response.d);
                        },
                        error: function (response) {
                            alert(response.d);
                        }
                    });







                } else {
                    return false;
                }
            })





        }
    }, 500);

}