$(document).ready(function () {

    $("#loader").hide();
    getdataheader();




});
let publink = "";
let pubdayvalue = "";
let pubitemvalue = "";
let pubmonth = "";
let pubyear = "";

function getdataheader() {


    let str_para = getUrlVars()["para"];
    publink = 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 linegroup = arr_para[0];
        let linename = arr_para[1];
        let partnumber = arr_para[2];
        let machinename = arr_para[3];
        pubmonth = arr_para[4];
        pubyear = arr_para[5];
        pubdayvalue = arr_para[6];
        pubitemvalue = arr_para[7];

        $("#MainContent_txt_linegroup").html(linegroup);
        $("#MainContent_txt_linename").html(linename);
        $("#MainContent_txt_partnumber").html(partnumber);

        getdata_tbl_header(pubyear, pubmonth);



    }


}




function newrows(ctl) {

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


        if ($(this).attr('id').indexOf('Seq') != -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 = 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[1].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>");


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

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

            }
        }
    });






}


let tbl0 = "";
let tbl1 = "";
let tbl2 = "";
function getdata_tbl_header() {

    $("#loader").show();
    tbl0 = "<table class='tbl' id='tbldt' style='width:100%;'>";


    tbl1 = "<thead><tr><th style='width:15%;'><span style='font-size:12px;' id='machinename'>Machine</span><br><input type='button' id='btnselectall' class='button' value='Select All'  style='width:100px;max-height:30px;color:white;background-color:#C8CDC7;padding:0.1em;' onclick=\"javascript:selectall();return false;\"  /></th>";
    tbl2 = "<tbody id='tbdy'><tr><td id='machinename_0'></td>";


    let equid = "1";
    $.ajax({
        type: "POST",
        url: "XR_inspection_approval.aspx/GetRoot",
        data: '{equid: "' + equid + '"}',
        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 (customers.length == 0) {



            }

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


                tbl1 = tbl1 + "<th id='approvelisthd_" + $(this).find("approveid").text() + "' style='width:20px;'><span style='font-size:12px;' id='hdapprove_" + $(this).find("approveid").text() + "'>" + $(this).find("approveid").text() + "</span><br> " +
                     "<input type='button' id='btnapprove_" + $(this).find("approveid").text() + "' class='button' value='Approve'  style='width:100px;max-height:60px;color:white;margin-top:2px;background-color:#E3BC08;padding:1em;' onclick=\"javascript:confirm(this,'Y');return false;\"  />" +
                     "<input type='button' id='btnreject_" + $(this).find("approveid").text() + "' class='button' value='Reject'  style='width:100px;max-height:60px;color:white;margin-top:2px;background-color:#E3BC08;padding:1em;' onclick=\"javascript:confirm(this,'N');return false;\"  /></th>";

                tbl2 = tbl2 + "<td id='approvelist" + $(this).find("approveid").text() + "_0'></td>";


            });


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


    setTimeout(function () {
        tbl1 = tbl1 + "</tr></thead>";
        let strtbl = tbl0 + tbl1 + tbl2 + "</tr></tbody></table>";

        $("#g2").html(strtbl);





    }, 1500);

    setTimeout(function () {

        getinspectionmaster(1, 0, 0, '');
        $("#loader").hide();

    }, 1800);

}

let pubirow = 0;
let pubfilter = "";
let pubiseqno = 1;
let pubcurrentpage_checkitem = 1;

function getnext_item() {


    var elmnt = document.getElementById("g2");
    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)) {


        try {

            setTimeout(
              function () {
                  let len = $("#tbldt tbody").find('tr').length;
                  pubcurrentpage_checkitem = Math.ceil((len - 1) / 10);
                  pubcurrentpage_checkitem = pubcurrentpage_checkitem + 1;
                  getinspectionmaster(pubcurrentpage_checkitem, pubirow, parseInt(y, 0), pubfilter);



              }, 500);



        } catch (err) { };



    }

}

let iseqno = 1;
let ipub = 0;
function getinspectionmaster(currentpage, irow, scposstock, filter) {

    let iseqno = irow + 1;
    pubfilter = filter;
    let userid = $("#lbluserid").html();

    $.ajax({

        type: "POST",
        url: "XR_inspection_approval.aspx/getinspection",
        data: '{parahd:"' + filter + '",currentpage:"' + currentpage + '",dayvalue:"' + pubdayvalue + '",itemvalue:"' + pubitemvalue + '",month:"' + pubmonth + '",year:"' + pubyear + '",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 (customers.length == 0) {



            }

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

                addrow("Y");
                $('#machinename_' + irow.toString()).html("<a href='#' style='width:20px;cursor:pointer;text-decoration: none;' onclick='javascript:selectitems(" + irow + ");return false;'>" + $(this).find("machinename").text() + "</a><span id='machid_" + irow.toString() + "' style='font-size:1px;color:white;'>" + $(this).find("machineid").text() + '</span>');
                $('#approvelistCheck1_' + irow.toString()).html($(this).find("recdate1").text() + "<br/>" + $(this).find("check1_userid").text() + "<br/><a href='#' onclick=\"javascript:showdetail(\'" + $(this).find("check1_notice").text() + "\');return false;\"  style='text-decoration:none;font-size:16px;'>" + $(this).find("check1_noticeshort").text() + "</a>");
                $('#approvelistCheck2_' + irow.toString()).html($(this).find("recdate3").text() + "<br/>" + $(this).find("check2_userid").text() + "<br/><a href='#' onclick=\"javascript:showdetail(\'" + $(this).find("check2_notice").text() + "\');return false;\"  style='text-decoration:none;font-size:16px;'>" + $(this).find("check2_noticeshort").text() + "</a>");
                $('#approvelistApprove1_' + irow.toString()).html($(this).find("recdate2").text() + "<br/>" + $(this).find("approve1_userid").text() + "<br/><a href='#' onclick=\"javascript:showdetail(\'" + $(this).find("approve1_notice").text() + "\');return false;\"  style='text-decoration:none;font-size:16px;'>" + $(this).find("approve1_noticeshort").text() + "</a>");
                $('#approvelistApprove2_' + irow.toString()).html($(this).find("recdate4").text() + "<br/>" + $(this).find("approve2_userid").text() + "<br/><a href='#' onclick=\"javascript:showdetail(\'" + $(this).find("approve2_notice").text() + "\');return false;\"  style='text-decoration:none;font-size:16px;'>" + $(this).find("approve2_noticeshort").text() + "</a>");


                if ($(this).find("check1_status").text() == "Y") {
                    $("#btnapprove_Check1").css({ 'background-color': '#77A9F9' });

                }
                else if ($(this).find("check1_status").text() == "N") {
                    $("#btnreject_Check1").css({ 'background-color': '#F8183D' });

                }
                if ($(this).find("check2_status").text() == "Y") {
                    $("#btnapprove_Check2").css({ 'background-color': '#77A9F9' });

                }
                else if ($(this).find("check2_status").text() == "N") {
                    $("#btnreject_Check2").css({ 'background-color': '#F8183D' });

                }


                if ($(this).find("approve1_status").text() == "Y") {
                    $("#btnapprove_Approve1").css({ 'background-color': '#77A9F9' });

                }
                else if ($(this).find("approve1_status").text() == "N") {
                    $("#btnreject_Approve1").css({ 'background-color': '#F8183D' });

                }

                if ($(this).find("approve2_status").text() == "Y") {
                    $("#btnapprove_Approve2").css({ 'background-color': '#77A9F9' });

                }
                else if ($(this).find("approve2_status").text() == "N") {
                    $("#btnreject_Approve2").css({ 'background-color': '#F8183D' });

                }

                if ($(this).find("level").text() == "1" && $(this).find("approve_seq").text() == "1") {


                    $("#btnapprove_Approve2").hide();
                    $("#btnreject_Approve2").hide();
                    $("#btnapprove_Approve1").hide();
                    $("#btnreject_Approve1").hide();
                    $("#btnapprove_Check2").hide();
                    $("#btnreject_Check2").hide();


                }
                if ($(this).find("level").text() == "1" && $(this).find("approve_seq").text() == "2") {


                    $("#btnapprove_Approve2").hide();
                    $("#btnreject_Approve2").hide();
                    $("#btnapprove_Approve1").hide();
                    $("#btnreject_Approve1").hide();
                    $("#btnapprove_Check1").hide();
                    $("#btnreject_Check1").hide();


                }

                if ($(this).find("level").text() == "2" && $(this).find("approve_seq").text() == "1") {

                    $("#btnapprove_Approve2").hide();
                    $("#btnreject_Approve2").hide();
                    $("#btnapprove_Check1").hide();
                    $("#btnreject_Check1").hide();
                    $("#btnapprove_Check2").hide();
                    $("#btnreject_Check2").hide();


                }

                if ($(this).find("level").text() == "2" && $(this).find("approve_seq").text() == "2") {
                    $("#btnapprove_Approve1").hide();
                    $("#btnreject_Approve1").hide();
                    $("#btnapprove_Check1").hide();
                    $("#btnreject_Check1").hide();
                    $("#btnapprove_Check2").hide();
                    $("#btnreject_Check2").hide();


                }








                irow++;
                iseqno++;
            });

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



            setTimeout(function () {

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

                        if ($(this).html() == "") {

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

                    }


                });
            }, 500);


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


}

let itemvalue = "";
let selectirow = "";
function selectall() {





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

        let ctltdid = $(this).attr('id');

        if (ctltdid.indexOf("achinename_") != -1) {

            let arr = ctltdid.split('_');


            if ($("#" + ctltdid).css('background-color') == "rgba(0, 0, 0, 0)") {


                $("#" + ctltdid).css({ 'background-color': '#94EEB6' });
                $("#approvelistCheck1_" + arr[1]).css({ 'background-color': '#94EEB6' });
                $("#approvelistCheck2_" + arr[1]).css({ 'background-color': '#94EEB6' });
                $("#approvelistApprove1_" + arr[1]).css({ 'background-color': '#94EEB6' });
                $("#approvelistApprove2_" + arr[1]).css({ 'background-color': '#94EEB6' });

                itemvalue = itemvalue + $("#machid_" + arr[1]).html() + "*";

            }
            else if ($("#" + ctltdid).css('background-color') == "rgb(148, 238, 182)") {


                $("#" + ctltdid).css({ 'background-color': 'rgba(0, 0, 0, 0)' });
                $("#approvelistCheck1_" + arr[1]).css({ 'background-color': 'rgba(0, 0, 0, 0)' });
                $("#approvelistCheck2_" + arr[1]).css({ 'background-color': 'rgba(0, 0, 0, 0)' });
                $("#approvelistApprove1_" + arr[1]).css({ 'background-color': 'rgba(0, 0, 0, 0)' });
                $("#approvelistApprove2_" + arr[1]).css({ 'background-color': 'rgba(0, 0, 0, 0)' });

            }



        }



    });

}
function selectitems(irow) {


    selectirow = irow;
    let ctlhdid = "machid_" + irow.toString();
    if ($("#" + ctlhdid).css('background-color') == "rgba(0, 0, 0, 0)") {


        old_hd_css = $("#" + ctlhdid).css('background-color');
        $("#" + ctlhdid).css({ 'background-color': '#94EEB6' });

    }
    else {

        $("#" + ctlhdid).css({ 'background-color': old_hd_css });
    }



    itemvalue = itemvalue + $("#machid_" + irow).html() + "*";



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

        let ctltdid = $(this).attr('id');

        if (ctltdid.indexOf("_" + irow.toString()) != -1 && ctltdid.indexOf("seqno_") == -1) {

            if ($("#" + ctltdid).css('background-color') == "rgba(0, 0, 0, 0)") {

                old_dt_css = $("#" + ctltdid).css('background-color');
                $("#" + ctltdid).css({ 'background-color': '#94EEB6' });


            }
            else if ($("#" + ctltdid).css('background-color') == "rgb(148, 238, 182)") {


                $("#" + ctltdid).css({ 'background-color': old_dt_css });


            }



        }



    });


}

function confirm(ctl, resultconfirm) {

    if (itemvalue.length == 0) {

        swal(
         'Warning',
         'Please select information for approval.',
         'warning'
         );

    }
    else {

        let ctlid = $(ctl).attr('id');
        let arr = ctlid.split('_');
        let irow = arr[1];

        if ($("#btnapprove_" + irow).css('background-color') == 'rgb(119, 169, 249)' || $("#btnreject_" + irow).css('background-color') == 'rgb(248, 24, 61)') {

            swal(
               'Error',
               'You cannot reapprove.',
               'error'
               );


        }
        else {



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


                    if (resultconfirm == "N") {

                        opennotice(ctl);

                    }
                    else {
                        confirm_save(ctl);

                    }





                } else {
                    return false;
                }
            })
        }
    }
}
function confirm_save(ctl) {

    let ctlid = $(ctl).attr('id');
    let arr = ctlid.split('_');
    let irow = arr[1];
    let result = "";

    if (ctlid.indexOf("approve_") != -1) {
        $("#btnapprove_" + irow).css({ 'background-color': '#77A9F9' });
        result = "Y";
    }
    else {
        $("#btnreject_" + irow).css({ 'background-color': '#F8183D' });
        result = "N";

    }



    let machineid = itemvalue;
    let notice = $('#txt_notice').val();
    let userid = $("#lbluserid").html();

    let checktype = "";
    if (ctlid.indexOf("_Approve") != -1) {

        checktype = "1";
    }
    else {

        checktype = "0";

    }
    $.ajax({
        type: "POST",
        url: "ConfirmApprove.aspx/saveconfirm",
        data: '{id:"' + itemvalue + '",status:"' + result + '", notice:"' + notice + '",insp_type:"2",checktype:"' + checktype + '", userid:"' + userid + '"}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {

            if (response.d == "") {

                swal(
                 'Success',
                 'Data saved successfully',
                 'success'
                 );
                setTimeout(function () {
                    window.location.href = "XR_inspection_approval?para=" + publink;
                }, 1000);

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


            }


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






}
let irow_confirm = "";
function opennotice(ctl) {

    let ctlid = $(ctl).attr('id');
    let arr = ctlid.split('_');
    irow_confirm = arr[1];




    $('#txt_notice').val("");
    var modal = document.getElementById('NoticeModal');
    modal.style.display = "block";


}
function savenotice() {



    confirm_save($("#btnreject_" + irow_confirm));
    var modal = document.getElementById('NoticeModal');
    modal.style.display = "none";




}

function back() {

    window.location.href = "XR_inspection_result?para=" + publink;


}

function showdetail(detail) {


    swal(
    'Notice',
    detail,
    'info'
    );




}
