$(document).ready(function () {


    $("#dataload").hide();

    $("#MainContent_Panel1  .form-row").each(function () {


        try {

            var sp = $(this).html().split('<div class="form-row"');
            $.each(sp, function (index, value) {

                var spsub0 = value.toString().replace(/,,/g, ',0,').trim().split('<div class="formrow"');
                $.each(spsub0, function (index0, value0) {


                    var spsub1 = value.toString().replace(/,,/g, ',0,').trim().split('<span>');
                    //alert((spsub1.length-1).toString());
                    var spsub0 = value.toString().replace(/,,/g, ',0,').trim().split('<div class="formrow"');

                    var numcount = 1;

                    $.each(spsub1, function (index1, value1) {

                        if (value1.indexOf("label") != -1) {

                            $("#MainContent_Panel1  .form-row").find('input[type="image"]').each(function () {

                                try {

                                    $(this).css('height', '25px');
                                } catch (err) { };

                            });
                            $("#MainContent_Panel1  .form-row").find('span').each(function () {
                                try {



                                  




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



                                        if ($(this).html().length >= 15) {
                                            $(this).css('width', '180px');
                                        }

                                        else {
                                            $(this).css('width', '120px');
                                        }


                                        if ($(this).html() == "...") {
                                            $(this).css('width', '500px');
                                        }

                                        if ($(this).html().length >= 50) {
                                            $(this).css('width', '400px');
                                        }


                                    }




                                } catch (err) { };

                            });


                            //numcount++;




                            $("#MainContent_Panel1  .form-row").find('input[type="text"]').each(function () {
                                try {
                                    if ($(this).attr('id').indexOf("ID") != -1) {

                                        $(this).css('width', '150px');
                                    }
                                    if ($(this).attr('id').indexOf("Name") != -1) {
                                        $(this).css('width', '250px');
                                    }
                                } catch (err) { };

                            });



                            //alert(value1.toString());

                        }



                    });

                });


            });



            try {
                if ($(this).html().indexOf("frmrow") != -1) {




                    $(".frmrow").each(function () {




                        if ($(this).html().indexOf("label") != -1) {



                            numcount++;




                        }
                        if ($(this).html().indexOf("</div>") != -1) {


                            //alert(numcount.toString());
                            numcount = 0;




                        }




                    });




                }

            } catch (err) { }



            //try{
            //    if($(this).html().indexOf("label")!=-1)
            //    {
            //        alert($(this).html());
            //    }
            //}catch(err){}
        } catch (err) { }


    });



    try {
        //var modal = document.getElementById('myModalwait');
        //modal.style.display = "block";
        //$("form :input").prop("disabled", true);
        $('input, :input').attr('autocomplete', 'off');
    } catch (err) { }










    $("#MainContent_Panel1 input[type='text']").each(function () {
        $("#" + $(this).attr('id')).val("");
    });
    $("#MainContent_Panel1 select").each(function () {
        $("#" + $(this).attr('id')).val("");
    });
    $("#MainContent_Panel1 textarea").each(function () {
        $("#" + $(this).attr('id')).html("");
    });








    $("input").each(function () {

        var ctlid = $(this).attr("id");

        try {

            if (ctlid.indexOf("btnedit") != -1) {

                $(this).hide();
            }
            if (ctlid.indexOf("btndel") != -1) {

                $(this).hide();
            }

        }
        catch (err) {

        }

    });

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

    }
    try {
        //$("#MainContent_txt_cltsearch").focus();
    } catch (err) {
    }
    finally {

    }

   





    $('#txtPubFilter').on('input', function (event) {
   
        pubfiltermain();

    });






});

//window.onclick = function (event) {
//    var modal = document.getElementById('myModal');
//    modal.style.display = "none";

//}


function pubfiltermain() {

    var str = $("#txtPubFilter").val();
    currentpage = 1;
    pageold = 1;
    $('#popupdt').html("");
    if (pfilter.length > 0)
    {
        str = str + "*" + pfilter;

    }
    calldata(pctl, pctlother, pcolid, pcolname, ptbl, str);


   

}
function closemodel()
{
    var modal = document.getElementById('myModal');
    modal.style.display = "none";

}

function controlpage() {




    $("textarea").keydown(function (event) {
        if (event.keyCode == 13 || event.keyCode == 9) {
            var s = $(this).val();

        }
    });


   
    $("select").keydown(function (event) {


        if (event.keyCode == 13 || event.keyCode == 9) {

            var fields = $(this).parents('form:eq(0),body').find('button,input[type="text"],textarea,select:not([disabled])');
            var index = fields.index(this);
            if (index > -1 && (index + 1) < fields.length) {



                fields.eq(index + 1).focus();
                fields.eq(index + 1).select();




            }
            return false;


        }


    });

    $("input").not($(":button")).keydown(function (evt) {


        if (evt.keyCode == 13 || evt.keyCode == 9) {
            evt.preventDefault();


            iname = $(this).val();

            if (iname !== 'Submit') {
                //var fields = $(this).parents('form:eq(0),body').find('button,input[type="text"]:not([readonly]),textarea,select:not([disabled])');
                var fields = $(this).parents('form:eq(0),body').find('button,input[type="text"],textarea,select:not([disabled])');
                var index = fields.index(this);
                if (index > -1 && (index + 1) < fields.length) {


                    fields.eq(index + 1).focus();
                    fields.eq(index + 1).select();


                }
                return false;
            }


        }
        else if (evt.keyCode == 8) {

            //$(this).val("");             
            //$(this).focus();
            //$(this).select();

        }


    });

    $("input").not($(":button")).each(function () {

        var ctlid = $(this).attr("id");

        try {
            if (ctlid != "undefined" && ctlid != "MainContent_lblrownum") {
                var title = $(this).attr("title");
                //if(title.toString()=="int")
                //{
                $("#" + ctlid).on('change', function (event) {

                    if (title.toString() == "intf") {
                        let ctlvalue = $("#" + ctlid).val();
                        ctlvalue = parseFloat(ctlvalue.replace(",", ""));
                        $("#" + ctlid).val(addCommas(ctlvalue.toFixed(2)));
                        $("#" + ctlid).css({ 'text-align': 'right' });
                    }


                });


                $("#" + ctlid).on('keyup', function (event) {
                    if (title.indexOf("int") != -1) {
                        if (/[^0-9\.\,]/g.test(this.value)) this.value = this.value.replace(/[^0-9\.\,]/g, '');
                        $("#" + ctlid).css({ 'text-align': 'right' });

                    }

                    $("input").not($(":button")).each(function () {

                        var ctlidx = $(this).attr("id");

                        try {
                            if (ctlidx != "undefined" && ctlidx != "MainContent_lblrownum") {

                                if ($("#" + ctlidx).val() == "NaN") {
                                    $("#" + ctlidx).val("");
                                }


                            }


                        }

                        catch (err) { }

                    });


                });


                //}






            }

            //if(ctlid.indexOf("frm")!=-1)
            //{
            //    $("#"+ctlid).css({'font-size':'24px'});
            //}

        }
        catch (err) {

        }

    });


}



function SetZIndex(control, args) {
    // Set auto complete extender control's z-index to a high value
    // so it will appear on top of, not under, the ModalPopUp extended panel.
    control._completionListElement.style.zIndex = 9999999999999;
}








function CheckOne(obj) {




    var grid = obj.parentNode.parentNode.parentNode;
    var inputs = grid.getElementsByTagName("input");
    for (var i = 0; i < inputs.length; i++) {
        if (inputs[i].type == "checkbox") {
            if (obj.checked && inputs[i] != obj && inputs[i].checked) {
                inputs[i].checked = false;


            }
        }
    }
}

function HighlightRow(chkB) {
    var IsChecked = chkB.checked;
    if (IsChecked) {
        chkB.parentElement.parentElement.style.backgroundColor = '#DADCDA';
        chkB.parentElement.parentElement.style.color = 'white';
    } else {
        chkB.parentElement.parentElement.style.backgroundColor = 'white';
        chkB.parentElement.parentElement.style.color = 'black';
    }
}

function SelectAll(obj, childname) {
    var CheckValue = obj.checked;

    var objCheckBoxes = document.getElementsByTagName("input");
    if (!objCheckBoxes)
        return;
    var countCheckBoxes = objCheckBoxes.length;

    if (countCheckBoxes == 1) {

        if (objCheckBoxes.name.indexOf("gvEmployees") >= 0 && objCheckBoxes.name.indexOf(childname) >= 0)
            objCheckBoxes.checked = CheckValue;
    }
    else {
        // set the check value for all check boxes 
        for (var i = 0; i < countCheckBoxes; i++)
            if (objCheckBoxes[i].type == "checkbox")
                if (objCheckBoxes[i].name.indexOf("gvEmployees") >= 0 && objCheckBoxes[i].name.indexOf(childname) >= 0)
                    objCheckBoxes[i].checked = CheckValue;
    }
}


function SelectAll1(obj, childname) {
    var CheckValue = obj.checked;

    var objCheckBoxes = document.getElementsByTagName("input");
    if (!objCheckBoxes)
        return;
    var countCheckBoxes = objCheckBoxes.length;

    if (countCheckBoxes == 1) {

        if (objCheckBoxes.name.indexOf("gv") >= 0 && objCheckBoxes.name.indexOf(childname) >= 0)
            objCheckBoxes.checked = CheckValue;
    }
    else {
        // set the check value for all check boxes 
        for (var i = 0; i < countCheckBoxes; i++)
            if (objCheckBoxes[i].type == "checkbox")
                if (objCheckBoxes[i].name.indexOf("gv") >= 0 && objCheckBoxes[i].name.indexOf(childname) >= 0)
                    objCheckBoxes[i].checked = CheckValue;
    }
}

function addCommas(amount) {



    return amount.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, '$1,');

    //nStr += '';
    //x = nStr.split('.');
    //x1 = x[0];
    //x2 = x.length > 1 ? '.' + x[1] : '';
    //var rgx = /(\d+)(\d{3})/;
    //while (rgx.test(x1)) {
    //    x1 = x1.replace(rgx, '$1' + ',' + '$2');
    //}
    //return x1 + x2;


}
function addCommas1(nStr) {
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1;
}
function chkdec(ele) {
    var num = parseFloat(ele.value);
    ele.value = addCommas(num.toFixed(2));
    if (ele.value == 'NaN') {
        ele.value = '0';
    } else {

        ele.value = addCommas(num.toFixed(2));
    }
}
function chkint(ele) {
    var num = parseFloat(ele.value);
    ele.value = addCommas1(num);
    if (ele.value == 'NaN') {
        ele.value = '0';
    } else {
        ele.value = addCommas(num);

    }
}


function postBackHiddenField(hiddenFieldID) {
    var hiddenField = $get(hiddenFieldID);
    if (hiddenField) {
        __doPostBack(hiddenFieldID, '');
    }
}
function getUrlVars() {
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for (var i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];

    }



    return vars;
}


let pctl="";
let pcolid="";
let ptbl="";
let pcolname = "";
let pfilter = "";
let currentpage = 1;
let pctlother = "";
let pageold = 1;
function filterpopup(ctl, ctlother, colid, colname, tbl, filter) {

   pctl = "";
   pcolid = "";
   ptbl = "";
   pcolname = "";
   pfilter = "";
   currentpage = 1;
   pctlother = "";
   pageold = 1;
   $("#txtPubFilter").val("");

   calldata(ctl, ctlother, colid, colname, tbl, filter);

}
function calldata(ctl,ctlother, colid,colname, tbl, filter) {

    
    $("#dataload").show();
    var dt = "";
  
    pctl = ctl;
    pcolid = colid;
    ptbl = tbl;
    pcolname = colname;
    pctlother = ctlother;
    pfilter = filter;

    if (ctl != pctl && currentpage > 1) {
        currentpage = 1;
        pageold = 1;

    }

    var pagesize = 20;

    $.ajax({
        type: "POST",
        url: "../frmCallData.aspx/calldata",
        data: '{ctl:"' + ctl + '",colid:"'+colid+'",colname:"'+colname+'", tbl:"'+tbl+'",currentpage:"'+currentpage+'",pagesize:"'+pagesize+'",filter:"'+filter+'"}',
        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) {

                $("#dataload").hide();

            }

            $.each(customers, function () {


                var valuename = $(this).find("ValueName").text();
                var valueid = $(this).find("ValueID").text();
                
                
                if (tbl == "InspectionItem" && $(this).find("resultstatus").text() == "OK")
                {

                    dt = dt + "<a href=\"javascript:selectitem('" + valueid + "','" + valuename + "','" + ctl + "','" + ctlother + "', '" + tbl + "');\" style='text-decoration: none;color:black'><div class='link-container' style='background-color:#77A9F9;'><span style='font-size:14px;'>" + valueid + "</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style='font-size:18px;'><center>" + valuename + "</center></span></div></a>";

                }
                else if (tbl == "InspectionItem" && $(this).find("resultstatus").text() == "NG")
                {
                    
                    dt = dt + "<a href=\"javascript:selectitem('" + valueid + "','" + valuename + "','" + ctl + "','" + ctlother + "', '" + tbl + "');\" style='text-decoration: none;color:black;'><div class='link-container' style='background-color:#F8183D;'><span style='font-size:14px;'>" + valueid + "</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style='font-size:18px;'><center>" + valuename + "</center></span></div></a>";

                }
                else
                {
                    dt = dt + "<a href=\"javascript:selectitem('" + valueid + "','" + valuename + "','" + ctl + "','" + ctlother + "', '" + tbl + "');\" style='text-decoration: none;color:black;'><div class='link-container'><span style='font-size:14px;'>" + valueid + "</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style='font-size:18px;'><center>" + valuename + "</center></span></div></a>";


                }






            });



            if (currentpage == 1) {
                $('#popupdt').html("");
                $('#popupdt').append("</br>" + dt);
                if (dt == "") {
                    $('#popupdt').html("<br/><br/><br/><br/>ไม่พบข้อมูล<br/><br/><br/><br/>");

                }
                $("#dataload").hide();
                var modal = document.getElementById('myModal');
                modal.style.display = "block";


            }
            else if (filter != "" && dt != "") {

              
                $('#popupdt').append(dt);
                
            }
            else if (currentpage > 1 && dt != "" && currentpage > pageold) {

                pageold = currentpage;
                $('#popupdt').append(dt);
    

            }
            

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





}

function myscroll() {


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



        try {


            //var modal = document.getElementById('myModalwait');
            //modal.style.display = "block";
            currentpage = currentpage + 1;
            calldata(pctl,pctlother, pcolid ,pcolname, ptbl,pfilter);

        } catch (err) { };



    }

}


function selectitem(valid,valname, ctl,ctlother, tbl) {



    try {
        $('#' + ctl).val("");
        $('#' + ctl).focus();
        $('#' + ctl).select();
        $('#' + ctl).val(valid);


        $('#' + ctlother).val("");
        $('#' + ctlother).focus();
        $('#' + ctlother).select();
        $('#' + ctlother).val(valname);


    } catch (err) {
        $('#' + ctl).html("");
        $('#' + ctl).html(val);

        $('#' + ctlother).html("");
        $('#' + ctlother).html(valname);


    };

    try {

        calldata_other();

    } catch (err) { }


    var modal = document.getElementById('myModal');
    modal.style.display = "none";



}


function link(page) {

    window.location.href = page;


}


function getCookie(cname) {
    let name = cname + "=";
    let decodedCookie = decodeURIComponent(document.cookie);
    let ca = decodedCookie.split(';');
    for (let i = 0; i < ca.length; i++) {
        let c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}
function setCookie(cname, cvalue, exdays) {
    const d = new Date();
    d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
    let expires = "expires=" + d.toUTCString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}


function checkreq() {
    var chk = "";
    $("input").not($(":button")).each(function () {

        var ctlid = $(this).attr("id");

        try {
            var title = $(this).attr("title");
            if (title.toString().indexOf("*") != -1 && $(this).val() == "") {


                msgwarning(this, 'Please input ' + title.toString().replace("*", ""), ctlid);


                $(this).focus();
                chk = "N";
                return false;



            }


        }
        catch (err) {

        }

    });

    if (chk == "") {
        $("textarea").not($(":button")).each(function () {

            var ctlid = $(this).attr("id");

            try {
                var title = $(this).attr("title");
                if (title.toString().indexOf("*") != -1 && $(this).val() == "") {
                    msgwarning(this, 'Please input ' + title.toString().replace("*", ""), ctlid);
                    $(this).focus();
                    chk = "N";
                    return false;


                }
            }
            catch (err) {

            }

        });
    }


    if (chk == "") {
        $("select").not($(":button")).each(function () {

            var ctlid = $(this).attr("id");

            try {
                var title = $(this).attr("title");
                if (title.toString().indexOf("*") != -1 && ($(this).val() == "" || $(this).val() == "0")) {
                    msgwarning(this, 'Please input ' + title.toString().replace("*", ""), ctlid);
                    $(this).focus();
                    chk = "N";
                    return false;


                }

            }
            catch (err) {

            }

        });
    }






    return chk;

}


function msgwarning(ctl, msg, ctlname) {

    swal(
         'Warning',
          msg+".",
         'warning'
       );
    $(ctl).focus();
    $(ctl).select();

}