    <!-- latest jquery-->
    <script src="../assets/js/jquery-3.2.1.min.js"></script>

    <!-- Bootstrap js-->
    <script src="../assets/js/bootstrap/popper.min.js"></script>
    <script src="../assets/js/bootstrap/bootstrap.js"></script>

    <!-- Ion Range Slider js -->
    <script src="../assets/js/range-slider/ion.rangeSlider.min.js"></script>
    <script src="../assets/js/range-slider/rangeslider-script.js"></script>

    <!-- Counter js-->
    <script src="../assets/js/counter/jquery.waypoints.min.js"></script>
    <script src="../assets/js/counter/jquery.counterup.min.js"></script>
    <!-- <script src="../assets/js/counter/counter-custom.js"></script> -->

    <!-- owlcarousel js-->
    <script src="../assets/js/owlcarousel/owl.carousel.js"></script>

    <!-- prism js -->
    <script src="../assets/js/prism/prism.min.js"></script>

    <!-- clipboard js -->
    <script src="../assets/js/clipboard/clipboard.min.js"></script>

    <!-- custom card js  -->
    <script src="../assets/js/custom-card/custom-card.js"></script>

    <!--Height Equal Js-->
    <script src="../assets/js/height-equal.js"></script>

    <!-- Sidebar jquery-->
    <script src="../assets/js/sidebar-menu.js"></script>
    <script src="../assets/js/compact-small-button.js"></script>

    <!-- Theme js-->
    <script src="../assets/js/script.js"></script>

    <!-- tour js -->
    <script src="../assets/js/tour/intro.js"></script>
    <script src="../assets/js/tour/intro-init.js"></script>

    <!-- Chartist  -->
    <script src="../assets/js/chartis/chartist.js"></script>

    <!--Sparkline  Chart JS-->
    <script src="../assets/js/sparkline/sparkline.js"></script>

    <!--Dashboard business js-->
    <!-- <script  src="../assets/js/dashboard-business.js"></script> -->
    <script src="../assets/js/date-picker/datepicker.js"></script>
    <script src="../assets/js/date-picker/datepicker.en.js"></script>

    <script src="../assets/js/bootbox.min.js"></script>

    <!-- bootstrap notify js -->
    <script src="../assets/js/notify/bootstrap-notify.min.js"></script>

    <!-- Select2 js -->
    <script type="text/javascript" src="../assets/js/select2/select2.full.min.js"></script>

    <!--Summer-note js-->
    <script src="../assets/js/summernote/summernote.js"></script>

    <script src="../assets/js/datatables/jquery.dataTables.min.js"></script>
    <script src="../assets/js/datatables/datatable.custom.js"></script>

    <!--rwdImageMaps-->
    <script src="../assets/js/rwdImageMaps.js"></script>

    <script>



        function getRandomInt(min, max) {
            min = Math.ceil(min);
            max = Math.floor(max);
            return Math.floor(Math.random() * (max - min + 1)) + min;
        }



        //function navigateTo(sender,pageLink,sideBarName,sideBarID)
        // console.log( $("#main-page-sidebar",parent.document) )
        // console.log( $("#main-page-sidebar",parent.document).length )
        // javascript:

        function getUrlParams(url) {
            var lastURL1 = "";
            var urlParams = {} // return value
            var queryString = getQueryString()

            if (queryString) {
                var keyValuePairs = queryString.split('&')
                for (var i = 0; i < keyValuePairs.length; i++) {
                    var keyValuePair = keyValuePairs[i].split('=')
                    var paramName = keyValuePair[0]
                    var paramValue = keyValuePair[1] || ''
                    urlParams[paramName] = decodeURIComponent(paramValue.replace(/\+/g, ' '))
                }
            }
            return urlParams // functions below
            function getQueryString() {
                var reducedUrl = lastURL1 || url || window.location.search

                reducedUrl = reducedUrl.split('#')[0] // Discard fragment identifier.
                var queryString = reducedUrl.split('?')[1]
                if (!queryString) {
                    if (reducedUrl.search('=') !== false) { // URL is a query string.
                        queryString = reducedUrl
                    }
                }
                return queryString
            } // getQueryString
        } // getUrlParams

        var SideBarID = getUrlParams()["sidebarid"];
        var SideBarName = getUrlParams()["sidebarname"];
        var TextBoxName = getUrlParams()["TextBoxName"];
        var CurrentCompanyID = getUrlParams()["CompanyID"];



        var currentEditRow;
        var currentGeneratedRow;
        var SearchBrandID;
        var cboVehicleBrand;
        var cboVehicleModel;
        var cboVehicleType;
        var cboVehicleSize;
        var cboVehicleColor;
        var cboManufacturerYear;
        var cboCustomerType;
        var cboSalesPerson;
        var cboInstallersBy;
        var modal_PassCode;
        var txtMobile;
        var txtCustomerName;
        var txtEmail;
        var txtTRN;
        var dtJobCardDate;
        var txtPlateNo;
        var txtChassisNo;
        var txtKMRun;
        var dtPromiseDate;
        var txtPreparedBy;
        var inspectiontable;
        var inspectiontablebody;
        var warningtable;
        var warningtablebody;
        var checklisttable;
        var checklisttablebody;
        var txtNotes;
        var txtFuel;
        var txtLastModificationTimeStamp;
        var table;
        var tableBody;
        var searchForm;
        var tableSearch;
        var tableBodySearch;
        var txtInvoiceID;

        var customersearchForm;
        var tableCustomer;
        var tableBodyCustomer;

        var tableChassis;
        var tableBodyChassis;

        var Modal_Search_Customer = $('#Modal_Search_Customer')
        var Search_Customer = $('#Search_Customer');
        var Search_MobileNumber = $('#Search_MobileNumber');
        var Search_Email = $('#Search_Email');
        var Search_PlateNumber = $('#Search_PlateNumber');
        var Search_ChassisNumber = $('#Search_ChassisNumber');
        var Search_VehicleType = $('#Search_VehicleType');
        var Search_CustomerType = $('#Search_CustomerType');

        var Search_Chassis_PlateNumber = $('#Search_Chassis_PlateNumber');
        var Search_Chassis_ChassisNumber = $('#Search_Chassis_ChassisNumber');
        var Search_Chassis_VehicleType = $('#Search_Chassis_VehicleType');
        /////////////////DETAIL///////////////
        var cboItem;
        var cboUnit;
        var totalValue;
        var totalDiscount;
        var totalTax;
        var grandTotal;
        var txtQty;
        var txtRate;
        var txtAmount;
        var txtDiscount;
        var txtVAT;
        var txtNetAmount;
        var txtDiscountAmount;
        var txtVATAmount;
        var txtPartNumber;
        var txtPack;
        var txtBatchNo;
        var txtMulkiyaNo;
        var txtParkingNo;
        var txtKeyNo;


        var txtDetailNarration;

        /* Added Saeed 01-29-2020*/
        var Advance_cboCash = $('#Advance_cboCash');
        var Advance_cboCredit = $('#Advance_cboCredit');
        var advance_creditcardamount;
        var advance_transactionno;
        var advance_cashamount;
        var advance_totalreceived;
        //var globalWebServiceInventoryPath="http://localhost:3321";
        var globalWebServiceInventoryPath = "../";

        var alertTypeCritical = {
            type: 'danger',
            timer: 1000,
            placement: { from: 'top', align: 'right' },
            offset: { x: 30, y: 90 },
            delay: 500,
            z_index: 10000,
            animate: { enter: 'animated bounce', exit: 'animated fadeOut' }
        };
        var alertTypeInfo = {
            type: 'primary',
            timer: 1000,
            placement: { from: 'top', align: 'right' },
            offset: { x: 30, y: 90 },
            delay: 500,
            z_index: 10000,
            animate: { enter: 'animated fadeIn', exit: 'animated fadeOut' }
        };
        var alertTypeSuccess = {
            type: 'success',
            timer: 1000,
            placement: { from: 'top', align: 'right' },
            offset: { x: 30, y: 90 },
            delay: 500,
            z_index: 10000,
            animate: { enter: 'animated fadeIn', exit: 'animated fadeOut' }
        };


        //::CREATE_ITEM
        $('#button_CreateItem').click(function () {
            localStorage.removeItem("item_NewItemID")
            $('#modal_CreateItem').modal('show');
            $('#frame_CreateItem').attr('src', "../pages/modal_product_information.html?sidebarid=44&CategorySideBarID=42&UnitSideBarID=43&ProductBaseType=ITEM&CompanyID=" + CurrentCompanyID)
        })
        //::CREATE_ITEM
        $('#modal_CreateItem').on('hidden.bs.modal', function () {

            if (localStorage.getItem("item_NewItemID")) {
                var data = JSON.parse(localStorage.getItem("item_NewItemID"));
                $("#cboItem_Item").val(null).append(new Option(data.ItemName, localStorage.getItem("item_NewItemID"), true, true)).trigger('change');
            }
        });
        //::CREATE_ITEM
        window.item_CloseModal = function () {
            $('#modal_CreateItem').modal('hide');
        };

        function col_Action_Script(InvoiceID, KeyField, GodownID) {


            return '    <div class="btn-group">\r\n' +
                '        <button type="button" class="btn btn-danger dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">\r\n' +
                '            Action\r\n' +
                '        </button>\r\n' +
                '        <div class="dropdown-menu">\r\n' +
                '            <a class="dropdown-item" href="#" onclick="javascript:editMaster(this);"><i class="fa fa-pencil fa-lg" style="text-align: left;color: blue;cursor:pointer;" ></i>&nbsp;&nbsp;Edit</a>\r\n' +
                '            <a class="dropdown-item" href="#" onclick="javascript:deleteMaster(this);"><i class="fa fa-trash-o fa-lg" style="text-align: left;color: red;cursor:pointer;" ></i>&nbsp;&nbsp;Delete</a>\r\n' +
                '            <div class="dropdown-divider"></div>\r\n' +
                '            <a class="dropdown-item" href="#" onclick="javascript:ApprovedRow(this);"><i class="icon-check fa-lg" style="text-align: left;color: blue;cursor:pointer;" ></i>&nbsp;&nbsp;Approve</a>\r\n' +
                '            <a class="dropdown-item" href="#" onclick="javascript:DisApproveRow(this);"><i class="icon-close fa-lg" style="text-align: left;color: red;cursor:pointer;" ></i>&nbsp;&nbsp;Disapprove</a>\r\n' +
                '            <div class="dropdown-divider"></div>\r\n' +
                '            <a class="dropdown-item" href="#" onclick="javascript:GenerateInvoice(this);"><i class="fa fa-file" style="text-align: left;color: red;cursor:pointer;" ></i>&nbsp;&nbsp;Generate Invoice</a>\r\n' +
                '            <a class="dropdown-item" href="#" onclick="javascript:GenerateAdvance(this);"><i class="fa fa-file" style="text-align: left;color: blue;cursor:pointer;" ></i>&nbsp;&nbsp;Payment Receipt</a>\r\n' +
                '            <div class="dropdown-divider"></div>\r\n' +

                '            <a class="dropdown-item" href="#" onclick="javascript:openReport(this,\'./pages/job_sheet.html?sidebarid=' + SideBarID + '&InvoiceID=' + InvoiceID + '&InvoiceNo=' + KeyField + '\',\'Job Sheet\');" ><i class="icon-pencil-alt fa-lg" style="text-align: left;color: black;cursor:pointer;" ></i>&nbsp;&nbsp;Job Sheet</a>\r\n' +
                '            <a class="dropdown-item" href="#" onclick="javascript:openReport(this,\'./pages/material_request.html?ProductSideBarID=44&InvoiceType=6&ProductBaseType=ITEM&sidebarid=' + SideBarID + '&InvoiceID=' + InvoiceID + '&InvoiceNo=' + KeyField + '&GodownID=' + GodownID + '\',\'Issue Slip\');" ><i class="icon-shopping-cart-full fa-lg" style="text-align: left;color: black;cursor:pointer;" ></i>&nbsp;&nbsp;Issue Slip</a>\r\n' +

                '            <div class="dropdown-divider"></div>\r\n' +
                '            <a class="dropdown-item" href="#" target2="_blank" href2="http://member.ddns.net:53556/reportViewer.aspx?refresh=1&reportFileName=reports/Job_Card.trdx&KeyField='+ InvoiceID+'" onclick="javascript:openReport(this,\'./report_files/reportViewer.html?refresh=1&reportFileName=jobcardreport.html&KeyField=' + InvoiceID+'&GodownID=' + GodownID + '\',\'Job Card Report\');" ><i class="icon-printer fa-lg" style="text-align: left;color: green;cursor:pointer;" ></i>&nbsp;&nbsp;Job card</a>\r\n' +
                '            <a class="dropdown-item" target="_blank" href="http://member.ddns.net:53556/reportViewer.aspx?refresh=1&reportFileName=reports/Damage_Report.trdx&KeyField='+ InvoiceID+'" onclick1="javascript:openReport(this,\'http://member.ddns.net:53556/reportViewer.aspx?refresh=1&reportFileName=reports/Damage_Report.trdx&KeyField=' + InvoiceID + '\',\'Inspection Report\');" ><i class="icon-printer fa-lg" style="text-align: left;color: green;cursor:pointer;" ></i>&nbsp;&nbsp;Inspection Report</a>\r\n' +
                '            <a class="dropdown-item" target="_blank" href="http://member.ddns.net:53556/reportViewer.aspx?refresh=1&reportFileName=reports/JobSheet_Report.trdx&KeyField='+ InvoiceID +'"  onclick1="javascript:openReport(this,\'http://member.ddns.net:53556/reportViewer.aspx?refresh=1&reportFileName=reports/JobSheet_Report.trdx&KeyField=' + InvoiceID + '\',\'Job Sheet Report\');" ><i class="icon-printer fa-lg" style="text-align: left;color: green;cursor:pointer;" ></i>&nbsp;&nbsp;JobSheet</a>\r\n' +
                '        </div>\r\n' +
                '    </div>\r\n';



        }





        function col_Action_Script_03_Jan(InvoiceID, KeyField, GodownID) {


            return '    <div class="btn-group">\r\n' +
                '        <button type="button" class="btn btn-danger dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">\r\n' +
                '            Action\r\n' +
                '        </button>\r\n' +
                '        <div class="dropdown-menu">\r\n' +
                '            <a class="dropdown-item" href="#" onclick="javascript:editMaster(this);"><i class="fa fa-pencil fa-lg" style="text-align: left;color: blue;cursor:pointer;" ></i>&nbsp;&nbsp;Edit</a>\r\n' +
                '            <a class="dropdown-item" href="#" onclick="javascript:deleteMaster(this);"><i class="fa fa-trash-o fa-lg" style="text-align: left;color: red;cursor:pointer;" ></i>&nbsp;&nbsp;Delete</a>\r\n' +
                '            <div class="dropdown-divider"></div>\r\n' +
                '            <a class="dropdown-item" href="#" onclick="javascript:ApprovedRow(this);"><i class="icon-check fa-lg" style="text-align: left;color: blue;cursor:pointer;" ></i>&nbsp;&nbsp;Approve</a>\r\n' +
                '            <a class="dropdown-item" href="#" onclick="javascript:DisApproveRow(this);"><i class="icon-close fa-lg" style="text-align: left;color: red;cursor:pointer;" ></i>&nbsp;&nbsp;Disapprove</a>\r\n' +
                '            <div class="dropdown-divider"></div>\r\n' +
                '            <a class="dropdown-item" href="#" onclick="javascript:GenerateInvoice(this);"><i class="fa fa-file" style="text-align: left;color: red;cursor:pointer;" ></i>&nbsp;&nbsp;Generate Invoice</a>\r\n' +
                '            <div class="dropdown-divider"></div>\r\n' +

                '            <a class="dropdown-item" href="#" onclick="javascript:openReport(this,\'./pages/job_sheet.html?sidebarid=' + SideBarID + '&InvoiceID=' + InvoiceID + '&InvoiceNo=' + KeyField + '\',\'Job Sheet\');" ><i class="icon-pencil-alt fa-lg" style="text-align: left;color: black;cursor:pointer;" ></i>&nbsp;&nbsp;Job Sheet</a>\r\n' +
                '            <a class="dropdown-item" href="#" onclick="javascript:openReport(this,\'./pages/material_request.html?ProductSideBarID=44&InvoiceType=6&ProductBaseType=ITEM&sidebarid=' + SideBarID + '&InvoiceID=' + InvoiceID + '&InvoiceNo=' + KeyField + '&GodownID=' + GodownID + '\',\'Issue Slip\');" ><i class="icon-shopping-cart-full fa-lg" style="text-align: left;color: black;cursor:pointer;" ></i>&nbsp;&nbsp;Issue Slip</a>\r\n' +

                '            <div class="dropdown-divider"></div>\r\n' +
                '            <a class="dropdown-item" href="#" onclick="javascript:openReport(this,\'./reportViewer.aspx?refresh=1&reportFileName=reports/Job_Card.trdx&KeyField=' + InvoiceID + '\',\'Job Card Report\');" ><i class="icon-printer fa-lg" style="text-align: left;color: green;cursor:pointer;" ></i>&nbsp;&nbsp;Print Job card</a>\r\n' +
                '            <a class="dropdown-item" href="#" onclick="javascript:openReport(this,\'./reportViewer.aspx?refresh=1&reportFileName=reports/Damage_Report.trdx&KeyField=' + InvoiceID + '\',\'Damage Report\');" ><i class="icon-printer fa-lg" style="text-align: left;color: green;cursor:pointer;" ></i>&nbsp;&nbsp;Print Damage report</a>\r\n' +
                '            <a class="dropdown-item" href="#" onclick="javascript:openReport(this,\'./reportViewer.aspx?refresh=1&reportFileName=reports/JobSheet_Report.trdx&KeyField=' + InvoiceID + '\',\'Job Sheet Report\');" ><i class="icon-printer fa-lg" style="text-align: left;color: green;cursor:pointer;" ></i>&nbsp;&nbsp;Print JobSheet</a>\r\n' +
                '        </div>\r\n' +
                '    </div>\r\n';



        }









        $(document).ready(function () {

                    $('#invoice-search').dataTable({
            "bSortCellsTop": true,
            "processing": false,
            "deferRender":true,
            "sDom": '<"top"flp>rt<"bottom"i><"clear">',
            "responsive": false,
            "paging": true,
            "lengthMenu": [[10, 20, 30, 40, 500000], [10, 20, 30, 40, "All"]],
            "pageLength": 10,
            "searching": false,
            "serverSide": false,
            "sAjaxDataProp": "",
            "order": [[0, "desc"]],
            "bAutoWidth": false,


            "ajax": {

                url: globalWebServiceInventoryPath + 'getjobcard.php?action=jobcardlist&SideBarID=' + SideBarID + '&CompanyID='+CurrentCompanyID+'&InvoiceType=' + 5,

                "data": function (d) {
                    var Data = new Object();
                    $.each(d.order, function (key, value) {
                        this.column = d.columns[this.column].data;
                    });
                    if (d.order)
                        Data.sorting = JSON.stringify(d.order);
                    try { Data.current_page = (d.start / d.length) + 1; } catch (e) { Data.current_page = 1; }
                    Data.records_to_return = d.length;


                    var fields = $(searchForm).serializeArray();

                    Data.Company = $('#Search_Company').val();
                    Data.Supplier = $('#Search_Supplier').val();
                    Data.Narration = $('#Search_Narration').val();
                    Data.ReferenceNo = $('#Search_ReferenceNo').val();
                    Data.Customer_CustomerName = $('#Search_Customer').val();
                    Data.GodownID = CurrentCompanyID;

                    Data.Customer_MobileNumber = $('#Invoice_Search_CustomerMobile').val();
                    Data.Customer_PlateNumber = $('#Invoice_Search_PlateNumber').val();
                    Data.Customer_ChassisNumber = $('#Invoice_Search_ChassisNumber').val();
                    Data.InvoiceStatus = $('#Invoice_Search_OrderStatus').val();

                    if ($('#Search_BillDate').val()) {
                        Data.BillDate = convertToDate($('#Search_BillDate'));
                    }

                    if ($('#Invoice_Search_PromiseDate').val()) {
                        Data.DeliveryDate = convertToDate($('#Invoice_Search_PromiseDate'));
                    }

                    


                    Data.draw = d.draw;
                    return Data;

                }
            },


            "columns": [
                { "data": "row_num", sWidth: "5%" },//S#
                { "data": "JC_CustomerName", sWidth: "10%" },//JC_CustomerName
                { "data": "CompanyShortForm", sWidth: "14%" },//CompanyShortForm
                //{ "data": "InvoiceDate", sWidth: "14%" },//BillDate
                { "data": function (x) { return "JC.Dt: "+ x.InvoiceDate + "<br/><small>" + "PR.Dt: "+x.DeliveryDate + '</small>' }, sWidth: "14%",},//KeyField+CreateByUserName
                // (x.ChassisNumber ? x.ChassisNumber : 'NA')
                //{ "data": "KeyField", sWidth: "14%" },//ReferenceNo
                { "data": function (x) { return x.KeyField + "<br/><small>" + x.CreateByUserName + '</small>' }, sWidth: "14%", "name": "KeyField" },//KeyField+CreateByUserName
                // { "data": "DeliveryDate", sWidth: "14%" },//Delivery Date
                //{ "data": function (x) { return x ? "<small>" + (x.Narration ? x.Narration : "") + "</small>" : ""; }, sWidth: "25%" },//Narration
                { "data": function (x) { return (x.JC_MobileNumber ? "Mob: "+x.JC_MobileNumber : 'Mob: NA') + "<br/><small>" + (x.JC_PlateNumber ? "Plate: "+x.JC_PlateNumber : 'Plate: NA') + '</small>' + "<br/><small>" + (x.JC_ChassisNumber ? "Ch: "+x.JC_ChassisNumber : 'Ch: NA')+ '</small>'  }, sWidth: "14%",},//KeyField+CreateByUserName
                { "data": "InvoiceStatus", sWidth: "8" },//InvoiceStatus
                //{ "data": "col_Action", sWidth: "8%" },//Action
                { "data": function (x) { return col_Action_Script(x.InvoiceID, x.KeyField, x.GodownID) }, sWidth: "10%" },//
            ],

            "columnDefs": [
                {
                    "targets": [7],
                    "sortable": false,
                    "className": "dt-center",

                },
            ],
        });//Data Table



                        
            $('#takeOtherPictures').click(function()//PICTURE_LINE
            {
                window.parent.modal_BrowsePicture($('#PictureLocation').val(),1 /*0 FOR SINGLE: 1 FOR MULTIPLE*/,function(data)
                {
                    $('#PictureLocation').val(data)
                })
            })



            $('#Invoice_Search_OrderStatus').select2({
                width: "100%"});




            $('#Supplier_cboSupplier').select2({
                width: "100%",
                dropdownAutoWidth: true,
                placeholder: "--Select Customer--",
                templateResult: function (data) {
                    var i = $(data.element);
                    var $template;
                    if (i.attr('data-VendorName'))
                        $template = '<small><mark>' + i.attr('data-VendorName') + '</mark></small>'
                    else
                        $template = "<span>--Select Customer--</span>";
                    return $($template);
                }
            });
            var $request_supplier = $.ajax({
                url: globalWebServiceInventoryPath + 'getjobcard.php?action=GetAccountsMasterForm&fieldid=COAID&fieldname=COAName&TextBoxName=accounts&NatureID=14&SideBarID=22',
                dataType: "json"
            });


            $request_supplier.then(function (data) {
                for (var d = 0; d < data.length; d++) {
                    var supplier = data[d];
                    var option = new Option(supplier.COAName, supplier.COAID);
                    $(option).attr('data-COAID', supplier.COAID + "")
                    $(option).attr('data-VendorName', supplier.COAName + "")
                    $('#Supplier_cboSupplier').append(option);
                }
                $('#Supplier_cboSupplier').val('96').trigger('change');
            });

            $('#cboDebitTo').select2({
                width: "100%",
                dropdownAutoWidth: true,
                placeholder: "--Select Sales Head--",
                templateResult: function (data) {
                    var i = $(data.element);
                    var $template;
                    if (i.attr('data-VendorName'))
                        $template = '<small><mark>' + i.attr('data-VendorName') + '</mark></small>'
                    else
                        $template = "<span>" + "--Select Sales Head--" + "</span>";
                    return $($template);
                }
            });
            $('#cboVATLedgerID').select2({
                width: "100%",
                dropdownAutoWidth: true,
                placeholder: "--Select VAT A/c--",
                templateResult: function (data) {
                    var i = $(data.element);
                    var $template;
                    if (i.attr('data-VendorName'))
                        $template = '<small><mark>' + i.attr('data-VendorName') + '</mark></small>'
                    else
                        $template = "<span>--Select VAT A/c--</span>";
                    return $($template);
                }
            });



            $('#cboCOGSLedger').select2({
                width: "100%",
                dropdownAutoWidth: true,
                placeholder: "--Select COGS A/c--",
                templateResult: function (data) {
                    var i = $(data.element);
                    var $template;
                    if (i.attr('data-VendorName'))
                        $template = '<small><mark>' + i.attr('data-VendorName') + '</mark></small>'
                    else
                        $template = "<span>--Select COGS A/c--</span>";
                    return $($template);
                }
            });

            $('#cboStockLedger').select2({
                width: "100%",
                dropdownAutoWidth: true,
                placeholder: "--Select Stock A/c--",
                templateResult: function (data) {
                    var i = $(data.element);
                    var $template;
                    if (i.attr('data-VendorName'))
                        $template = '<small><mark>' + i.attr('data-VendorName') + '</mark></small>'
                    else
                        $template = "<span>--Select Stock A/c--</span>";
                    return $($template);
                }
            });

            /*SAEED 01-29-2020*/
            $(Advance_cboCash).select2({
                width: "100%",
                dropdownAutoWidth: true,
                placeholder: "--Select Cash A/C--",
                templateResult: function (data) {
                    var i = $(data.element);
                    var $template;
                    if (i.attr('data-VendorName'))
                        $template = '<small><mark>' + i.attr('data-VendorName') + '</mark></small>'
                    else
                        $template = "<span>--Select Cash A/C--</span>";
                    return $($template);
                }
            });


            /*SAEED 01-29-2020*/
            $(Advance_cboCredit).select2({
                width: "100%",
                dropdownAutoWidth: true,
                placeholder: "--Select Credit A/C--",
                templateResult: function (data) {
                    var i = $(data.element);
                    var $template;
                    if (i.attr('data-VendorName'))
                        $template = '<small><mark>' + i.attr('data-VendorName') + '</mark></small>'
                    else
                        $template = "<span>--Select Credit A/C--</span>";
                    return $($template);
                }
            });


            $.ajax({
                url: globalWebServiceInventoryPath + 'getjobcard.php?action=GetAccountsMasterForm&fieldid=COAID&fieldname=COAName&TextBoxName=accounts&condition=106,170,172,241,96,102&SideBarID=22',
                dataType: "json"
            }).then(function (data) {
                for (var d = 0; d < data.length; d++) {

                    var supplier = data[d];
                    var option = new Option(supplier.COAName, supplier.COAID);
                    $(option).attr('data-COAID', supplier.COAID + "")
                    $(option).attr('data-VendorName', supplier.COAName + "")
                    $('#cboDebitTo').append(option);

                    var option2 = new Option(supplier.COAName, supplier.COAID);
                    $(option2).attr('data-COAID', supplier.COAID + "")
                    $(option2).attr('data-VendorName', supplier.COAName + "")
                    $('#cboVATLedgerID').append(option2);


                    // ADDED BY SAEED 31-DEC-19
                    var option3 = new Option(supplier.COAName, supplier.COAID);
                    $(option3).attr('data-COAID', supplier.COAID + "")
                    $(option3).attr('data-VendorName', supplier.COAName + "")
                    $('#cboCOGSLedger').append(option3);


                    var option4 = new Option(supplier.COAName, supplier.COAID);
                    $(option4).attr('data-COAID', supplier.COAID + "")
                    $(option4).attr('data-VendorName', supplier.COAName + "")
                    $('#cboStockLedger').append(option4);



                    /*SAEED 01-29-2020*/
                    // var option5 = new Option(supplier.COAName, supplier.COAID);
                    // $(option5).attr('data-COAID', supplier.COAID + "")
                    // $(option5).attr('data-VendorName', supplier.COAName + "")
                    // $(Advance_cboCash).append(option5);


                    // /*SAEED 01-29-2020*/
                    // var option6 = new Option(supplier.COAName, supplier.COAID);
                    // $(option6).attr('data-COAID', supplier.COAID + "")
                    // $(option6).attr('data-VendorName', supplier.COAName + "")
                    // $(Advance_cboCredit).append(option6);




                }
                //cboSupplier.trigger('change');
                $('#cboDebitTo').val('170').trigger('change')
                $('#cboVATLedgerID').val('106').trigger('change')
                $('#cboCOGSLedger').val('172').trigger('change')
                $('#cboStockLedger').val('241').trigger('change')

            });




            $.ajax({
                url: globalWebServiceInventoryPath + 'getjobcard.php?action=GetAccountsMasterForm&fieldid=COAID&fieldname=COAName&TextBoxName=accounts&SideBarID=22&GLStartsWith=1.1.2.2',
                dataType: "json"
            }).then(function (data) {
                for (var d = 0; d < data.length; d++) {

                    var supplier = data[d];

                    /*SAEED 01-29-2020*/
                    var option5 = new Option(supplier.COAName, supplier.COAID);
                    $(option5).attr('data-COAID', supplier.COAID + "")
                    $(option5).attr('data-VendorName', supplier.COAName + "")
                    $(Advance_cboCash).append(option5);


                }
                $('#Advance_cboCash').val('96').trigger('change')
            });




            $.ajax({
                url: globalWebServiceInventoryPath + 'getjobcard.php?action=GetAccountsMasterForm&TextBoxName=accounts&fieldid=COAID&fieldname=COAName&SideBarID=22&GLStartsWith=1.1.2.2',
                dataType: "json"
            }).then(function (data) {
                for (var d = 0; d < data.length; d++) {

                    var supplier = data[d];

                    /*SAEED 01-29-2020*/
                    var option5 = new Option(supplier.COAName, supplier.COAID);
                    $(option5).attr('data-COAID', supplier.COAID + "")
                    $(option5).attr('data-VendorName', supplier.COAName + "")
                    $(Advance_cboCredit).append(option5);


                }
                $('#Advance_cboCredit').val('98').trigger('change')
            });



            $('.table-responsive').on('show.bs.dropdown', function () {
                $('.table-responsive').css("overflow", "inherit");
            });

            $('.table-responsive').on('hide.bs.dropdown', function () {
                $('.table-responsive').css("overflow", "auto");
            })




/*            $.ajax({
                url:  'http://member.ddns.net:53556/webservice_Inventroid.asmx/GetProduct_Companies?SideBarID=' + SideBarID + '&CompanyID=' + CurrentCompanyID,
                dataType: "json"
            }).then(function (data) {
                if (data && data.length == 1) {
                    $('#cboItem_Company').append(new Option(data[0].Value, data[0].ID, true, true));

                }
            });

*/


            $('#cboItem_Company').select2({//modal_cboItem



                placeholder: "--Company--",

                ajax: {
                    url: 'http://member.ddns.net:53556/webservice_Inventroid.asmx/GetProduct_Companies?SideBarID=' + SideBarID,
                    dataType: 'json',
                    delay: 250,
                    cache: false,
                    allowClear: true,


                    processResults: function (resp) {

                        var data = resp;
                        var more = true;

                        if (!resp.total_records || !resp.filtered_records || (resp.draw) * 10 > resp.filtered_records) {
                            more = false;
                        }

                        if (data) {

                            var result = data.map(function (el) {
                                var o = Object.assign({}, el);
                                el.label = el.Value;
                                el.id = el.ID;
                                el.text = el.Value;
                                el.value = el.ID;
                                return o;
                            })

                            if (resp.draw == 1)
                                data.unshift({ label: "--Company--", id: " ", text: "--Company--", value: " " })

                        }
                        return {
                            results: data,
                            "pagination": {
                                "more": more
                            }
                        };
                    }, data: function (params) {


                        var query = {
                            term: params.term,
                            records_to_return: 10,
                            current_page: params.page || 1,
                            draw: params.page || 1,
                            Size: "ACTIVE",
                            IsFixedAsset: false,
                            ShowInSales: true,

                        }


                        return query;

                    }

                },
                escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
                width: '100%',
                // templateResult: function (repo) {
                //     if (repo.loading) {
                //         return repo.text;
                //     }
                //     var $result = $(
                //         '<div  class="select2-result-repository clearfix"><b>' + repo.ItemName + '</b><br/><span style="font-size:10px">' + repo.Barcode + '</span></div>'
                //     );
                //     return $result;s
                // },
            })
var condition='';
            $('#cboItem_BaseType').select2({//modal_cboItem



                placeholder: "--Type--",

                ajax: {
                    url: globalWebServiceInventoryPath +'getmastervalue.php?action=optionselect&TextBoxName=Inventory&fieldname=1 as ID&fieldid=Distinct(productBaseType) as Value&condition='+condition+'&SideBarID=' + SideBarID,
                    dataType: 'json',
                    delay: 250,
                    cache: false,
                    allowClear: true,


                    processResults: function (resp) {

                        var data = resp;
                        var more = true;

                        if (!resp.total_records || !resp.filtered_records || (resp.draw) * 10 > resp.filtered_records) {
                            more = false;
                        }

                        if (data) {

                            var result = data.map(function (el) {
                                var o = Object.assign({}, el);
                                el.label = el.Value;
                                el.id = el.Value;
                                el.text = el.Value;
                                el.value = el.Value;//edited replace ID with Value
                                return o;
                            })

                            if (resp.draw == 1)
                                data.unshift({ label: "--Type--", id: " ", text: "--Type--", value: " " })

                        }
                        return {
                            results: data,
                            "pagination": {
                                "more": more
                            }
                        };
                    }, data: function (params) {

                        var CompanyID;
                        CompanyID = $('#cboItem_Company').val();

                        var query = {
                            term: params.term,
                            records_to_return: 10,
                            current_page: params.page || 1,
                            draw: params.page || 1,
                            Size: "ACTIVE",
                            IsFixedAsset: false,
                            ShowInSales: true,
                            CompanyID: CompanyID

                        }


                        return query;

                    }

                },
                escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
                width: '100%',
                // templateResult: function (repo) {
                //     if (repo.loading) {
                //         return repo.text;
                //     }
                //     var $result = $(
                //         '<div  class="select2-result-repository clearfix"><b>' + repo.ItemName + '</b><br/><span style="font-size:10px">' + repo.Barcode + '</span></div>'
                //     );
                //     return $result;s
                // },
            })
var condition=" [group]=1 and under=0";
            $('#cboItem_MainCategory').select2({//modal_cboItem



                placeholder: "--Main Cat--",

                ajax: {
                    url: globalWebServiceInventoryPath + 'getjobcard.php?action=getSubcategory&TextBoxName=Inventory&fieldid=ID&fieldname=Name as Value&condition='+condition+'&SideBarID=' + SideBarID,
                    dataType: 'json',
                    delay: 250,
                    cache: false,
                    allowClear: true,


                    processResults: function (resp) {

                        var data = resp;
                        var more = true;

                        if (!resp.total_records || !resp.filtered_records || (resp.draw) * 10 > resp.filtered_records) {
                            more = false;
                        }

                        if (data) {

                            var result = data.map(function (el) {
                                var o = Object.assign({}, el);
                                el.label = el.Value;
                                el.id = el.ID;
                                el.text = el.Value;
                                el.value = el.ID;
                                return o;
                            })

                            if (resp.draw == 1)
                                data.unshift({ label: "--Main Cat--", id: " ", text: "--Main Cat--", value: " " })

                        }
                        return {
                            results: data,
                            "pagination": {
                                "more": more
                            }
                        };
                    }, data: function (params) {

                        var CompanyID;
                        CompanyID = $('#cboItem_Company').val();
                        var BaseType = $('#cboItem_BaseType').val()
                        var AdditionalInfo3_JobCard;
                        var vehicletype;
                        if (cboVehicleType.select2('data')[0]) {
                            vehicletype = cboVehicleType.select2('data')[0].element;
                        }
                        AdditionalInfo3_JobCard = $(vehicletype).attr('data-MasterValue');

                        var query = {
                            term: params.term,
                            records_to_return: 10,
                            current_page: params.page || 1,
                            draw: params.page || 1,
                            Size: "ACTIVE",
                            IsFixedAsset: false,
                            ShowInSales: true,
                            CompanyID: CurrentCompanyID,
                            AdditionalInfo3_JobCard: AdditionalInfo3_JobCard,
                            BaseType: BaseType

                        }


                        return query;

                    }

                },
                escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
                width: '100%',
                // templateResult: function (repo) {
                //     if (repo.loading) {
                //         return repo.text;
                //     }
                //     var $result = $(
                //         '<div  class="select2-result-repository clearfix"><b>' + repo.ItemName + '</b><br/><span style="font-size:10px">' + repo.Barcode + '</span></div>'
                //     );
                //     return $result;s
                // },
            })
var condition="ProductBaseType='ITEM' and [group]=1";

            $('#cboItem_SubCategory').select2({//modal_cboItem



                placeholder: "--Sub Cat--",

                ajax: {
                    url: globalWebServiceInventoryPath + 'getjobcard.php?action=getSubcategory&TextBoxName=Inventory&fieldid=ID&fieldname=Name as Value&condition='+condition+'&SideBarID=' + SideBarID,
                    dataType: 'json',
                    delay: 250,
                    cache: false,
                    allowClear: true,


                    processResults: function (resp) {

                        var data = resp;
                        var more = true;

                        if (!resp.total_records || !resp.filtered_records || (resp.draw) * 10 > resp.filtered_records) {
                            more = false;
                        }

                        if (data) {

                            var result = data.map(function (el) {
                                var o = Object.assign({}, el);
                                el.label = el.Value;
                                el.id = el.ID;
                                el.text = el.Value;
                                el.value = el.ID;
                                return o;
                            })

                            if (resp.draw == 1)
                                data.unshift({ label: "--Sub Cat--", id: " ", text: "--Sub Cat--", value: " " })

                        }
                        return {
                            results: data,
                            "pagination": {
                                "more": more
                            }
                        };
                    }, data: function (params) {

                        var CompanyID;
                        CompanyID = $('#cboItem_Company').val();

                        var Under;
                        Under = $('#cboItem_MainCategory').val();

                        var BaseType = $('#cboItem_BaseType').val()

                        var AdditionalInfo3_JobCard;
                        var vehicletype;
                        if (cboVehicleType.select2('data')[0]) {
                            vehicletype = cboVehicleType.select2('data')[0].element;
                        }
                        AdditionalInfo3_JobCard = $(vehicletype).attr('data-MasterValue');

                        var query = {
                            term: params.term,
                            records_to_return: 10,
                            current_page: params.page || 1,
                            draw: params.page || 1,
                            Size: "ACTIVE",
                            IsFixedAsset: false,
                            ShowInSales: true,
                            CompanyID: CurrentCompanyID,
                            Under: Under,
                            AdditionalInfo3_JobCard: AdditionalInfo3_JobCard,
                            BaseType: BaseType

                        }


                        return query;

                    }

                },
                escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
                width: '100%',
                // templateResult: function (repo) {
                //     if (repo.loading) {
                //         return repo.text;
                //     }
                //     var $result = $(
                //         '<div  class="select2-result-repository clearfix"><b>' + repo.ItemName + '</b><br/><span style="font-size:10px">' + repo.Barcode + '</span></div>'
                //     );
                //     return $result;s
                // },
            })

            $('#cboItem_Brand').select2({//modal_cboItem



                placeholder: "--Brand--",

                ajax: {
                    url: globalWebServiceInventoryPath + 'getjobcard.php?action=getSubcategory&TextBoxName=Inventory&fieldid=ID&fieldname=AdditionalInfo3 as Value&condition='+condition+'&SideBarID=' + SideBarID,
                    dataType: 'json',
                    delay: 250,
                    cache: false,
                    allowClear: true,


                    processResults: function (resp) {

                        var data = resp;
                        var more = true;

                        if (!resp.total_records || !resp.filtered_records || (resp.draw) * 10 > resp.filtered_records) {
                            more = false;
                        }

                        if (data) {

                            var result = data.map(function (el) {
                                var o = Object.assign({}, el);
                                el.label = el.Value;
                                el.id = el.ID;
                                el.text = el.Value;
                                el.value = el.ID;
                                return o;
                            })

                            if (resp.draw == 1)
                                data.unshift({ label: "--Brand--", id: " ", text: "--Brand--", value: " " })

                        }
                        return {
                            results: data,
                            "pagination": {
                                "more": more
                            }
                        };
                    }, data: function (params) {

                        var CompanyID;
                        CompanyID = $('#cboItem_Company').val();

                        var Under;
                        Under = $('#cboItem_MainCategory').val();

                        var SubCategory;
                        SubCategory = $('#cboItem_SubCategory').val();

                        var BaseType = $('#cboItem_BaseType').val();

                        var AdditionalInfo3_JobCard;
                        var vehicletype;
                        if (cboVehicleType.select2('data')[0]) {
                            vehicletype = cboVehicleType.select2('data')[0].element;
                        }
                        AdditionalInfo3_JobCard = $(vehicletype).attr('data-MasterValue');

                        var query = {
                            term: params.term,
                            records_to_return: 10,
                            current_page: params.page || 1,
                            draw: params.page || 1,
                            Size: "ACTIVE",
                            IsFixedAsset: false,
                            ShowInSales: true,
                            CompanyID: CompanyID,
                            Under: Under,
                            ItemName: SubCategory,
                            AdditionalInfo3_JobCard: AdditionalInfo3_JobCard,
                            BaseType: BaseType
                        }


                        return query;

                    }

                },
                escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
                width: '100%',
                // templateResult: function (repo) {
                //     if (repo.loading) {
                //         return repo.text;
                //     }
                //     var $result = $(
                //         '<div  class="select2-result-repository clearfix"><b>' + repo.ItemName + '</b><br/><span style="font-size:10px">' + repo.Barcode + '</span></div>'
                //     );
                //     return $result;s
                // },
            })

            $('#cboItem_ItemLevel').select2({//modal_cboItem



                placeholder: "--Level--",

                ajax: {
                    url: globalWebServiceInventoryPath + 'getjobcard.php?action=getSubcategory&TextBoxName=Inventory&fieldid=ID&fieldname=MaxQtyLevel as Value&condition='+condition+'&SideBarID=' + SideBarID,
                    dataType: 'json',
                    delay: 250,
                    cache: false,
                    allowClear: true,


                    processResults: function (resp) {

                        var data = resp;
                        var more = true;

                        if (!resp.total_records || !resp.filtered_records || (resp.draw) * 10 > resp.filtered_records) {
                            more = false;
                        }

                        if (data) {

                            var result = data.map(function (el) {
                                var o = Object.assign({}, el);
                                el.label = el.Value;
                                el.id = el.ID;
                                el.text = el.Value;
                                el.value = el.ID;
                                return o;
                            })

                            if (resp.draw == 1)
                                data.unshift({ label: "--Level--", id: " ", text: "--Level--", value: " " })

                        }
                        return {
                            results: data,
                            "pagination": {
                                "more": more
                            }
                        };
                    }, data: function (params) {

                        var CompanyID;
                        CompanyID = $('#cboItem_Company').val();

                        var Under;
                        Under = $('#cboItem_MainCategory').val();

                        var SubCategory;
                        SubCategory = $('#cboItem_SubCategory').val();

                        var BaseType = $('#cboItem_BaseType').val()


                        var Brand;
                        Brand = $('#cboItem_Brand').val();
                        var AdditionalInfo3_JobCard;
                        var vehicletype;
                        if (cboVehicleType.select2('data')[0]) {
                            vehicletype = cboVehicleType.select2('data')[0].element;
                        }
                        AdditionalInfo3_JobCard = $(vehicletype).attr('data-MasterValue');


                        var query = {
                            term: params.term,
                            records_to_return: 10,
                            current_page: params.page || 1,
                            draw: params.page || 1,
                            Size: "ACTIVE",
                            IsFixedAsset: false,
                            ShowInSales: true,
                            CompanyID: CompanyID,
                            Under: Under,
                            ItemName: SubCategory,
                            BaseType: BaseType,
                            AdditionalInfo3_JobCard: AdditionalInfo3_JobCard,
                            Brand: Brand
                        }


                        return query;

                    }

                },
                escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
                width: '100%',
                // templateResult: function (repo) {
                //     if (repo.loading) {
                //         return repo.text;
                //     }
                //     var $result = $(
                //         '<div  class="select2-result-repository clearfix"><b>' + repo.ItemName + '</b><br/><span style="font-size:10px">' + repo.Barcode + '</span></div>'
                //     );
                //     return $result;s
                // },
            })

            $('#cboItem_Item').select2({//modal_cboItem
                placeholder: "--Select Item--",

                ajax: {
                    url: globalWebServiceInventoryPath + 'getjobcard.php?action=getitem&TextBoxName=Inventory&fieldid=ID&fieldname=Name as Value&condition='+condition +'&SideBarID=' + SideBarID,
                    dataType: 'json',
                    delay: 250,
                    cache: false,
                    allowClear: true,


                    processResults: function (resp) {

                        var data = resp;
                        var more = true;

                        if (!resp.total_records || !resp.filtered_records || (resp.draw) * 10 > resp.filtered_records) {
                            more = false;
                        }

                        if (data) {
                                console.log(data);
                            var result = data.map(function (el) {
                                var o = Object.assign({}, el);
                                el.label = el.Value;
                                el.id = JSON.stringify(el);
                                el.text = el.Value;
                                el.value = el.ID;
                                return o;
                            })

                            if (resp.draw == 1)
                                data.unshift({ label: "--Select Item--", id: " ", text: "--Select Item--", value: " " })

                        }
                        return {
                            results: data,
                            "pagination": {
                                "more": more
                            }
                        };
                    }, data: function (params) {

                        var BaseType = $('#cboItem_BaseType').val()

                        var CompanyID;
                        CompanyID = $('#cboItem_Company').val();

                        var Under;
                        Under = $('#cboItem_MainCategory').val();

                        var SubCategory;
                        SubCategory = $('#cboItem_SubCategory').val();

                        var Brand;
                        Brand = $('#cboItem_Brand').val();

                        var ProductLevel = $('#cboItem_ItemLevel').val();

                        var AdditionalInfo3_JobCard;
                        var vehicletype;
                        if (cboVehicleType.select2('data')[0]) {
                            vehicletype = cboVehicleType.select2('data')[0].element;
                        }
                        AdditionalInfo3_JobCard = $(vehicletype).attr('data-MasterValue');

                        var query = {

                            //AdditionalInfo1: params.term,

                            records_to_return: 10,
                            current_page: params.page || 1,
                            draw: params.page || 1,
                            Size: "ACTIVE",
                            IsFixedAsset: false,
                            ShowInSales: true,
                            CompanyID: CompanyID,
                            Under: Under,
                            ItemName: SubCategory && SubCategory.trim() ? SubCategory : params.term,
                            IName:params.term,
                            Brand: Brand,
                            BaseType: BaseType,
                            AdditionalInfo3_JobCard: AdditionalInfo3_JobCard,
                            ProductLevel: ProductLevel
                        }


                        return query;

                    }

                },
                escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
                width: '100%',
                templateResult: function (repo) {
                    if (repo.loading || !repo.id || repo.id == " ") {
                        return repo.text;
                    }
                    var $result = $(
                        '<div  class="select2-result-repository clearfix"><b>' + repo.Value + '</b>' +
                        (repo.Barcode ? '<br/><span style="font-size:10px"><small>BCode: </small>' + repo.Barcode + '</span>' : '') +
                        (repo.Brand ? '<br/><span style="font-size:10px"><small>Brand: </small>' + repo.Brand + '</span>' : '') +
                        (repo.ServiceLevel ? '<br/><span style="font-size:10px"><small>Level: </small>' + repo.ServiceLevel + '</span></div>' : '') +
                        (repo.PartNumber ? '<br/><span style="font-size:10px"><small>Part #: </small>' + repo.PartNumber + '</span></div>' : '')

                    );
                    return $result; s
                },
            }).on('change', function (a, b, c) {
                if ($(this).val() && $(this).val().trim()) {
                    var o = JSON.parse($(this).val());
                    console.log('o:'+$(this).val());
                    $(txtRate).val(o.SalePrice);
                    $(txtVAT).val(o.VATPercent);
                    doCalculation();
                }
            })

            $('#summernote').summernote({
                height: 300,
                tabsize: 2
            });


            $('#cboCustomerType').change(function () {
                var type;
                if (cboCustomerType.select2('data')[0]) {

                    type = cboCustomerType.select2('data')[0].element;
                }
                var MasterValue = $(type).attr('data-MasterValue');

                if (MasterValue == "CORPORATE") {
                    txtTRN.prop('disabled', null)
                }
                else {
                    txtTRN.prop('disabled', "disabled")
                }
            });



            $('#formTitle').html(SideBarName);

            customersearchForm = $('#customersearchForm');
            searchForm = $('#searchForm');
            form = $('#InvoiceForm');
            warningtable = $('#warningtable');
            warningtablebody = $('tbody', warningtable);
            cboItem = $('#invoice_cboItem');
            cboUnit = $('#invoice_cboUnit');
            checklisttable = $('#checklisttable');
            checklisttablebody = $('tbody', checklisttable);

            cboCustomerType = $('#cboCustomerType');
            cboVehicleBrand = $('#cboVehicleBrand');
            cboVehicleModel = $('#cboVehicleModel');
            cboVehicleType = $('#cboVehicleType');
            cboVehicleSize = $('#cboVehicleSize');
            cboVehicleColor = $('#cboVehicleColor');
            cboManufacturerYear = $('#cboManufacturerYear');
            cboSalesPerson = $('#cboSalesPerson');
            cboInstallersBy = $('#cboInstallersBy');
            txtNotes = $('#summernote');
            txtMobile = $('#mobile');
            txtCustomerName = $('#customername');
            txtEmail = $('#email');
            txtTRN = $('#trn');
            dtJobCardDate = $('#jobcarddate');
            txtPlateNo = $('#plateno');
            txtChassisNo = $('#chassisno');
            dtPromiseDate = $('#promiseddate');
            txtPreparedBy = $('#preparedby');
            txtKMRun = $('#kmrun');
            txtFuel = $('#myRange');
            table = $('#invoice');
            tableBody = $('tbody', table);
            inspectiontable = $('#inspectiontable');
            inspectiontablebody = $('tbody', inspectiontable);
            tableSearch = $('#invoice-search');
            tableBodySearch = $('tbody', tableSearch);
            txtQty = $('#invoice_txtQty');
            txtAmount = $('#invoice_txtAmount');
            txtRate = $('#invoice_txtPrice');
            txtDiscount = $('#invoice_txtDiscount');
            txtVAT = $('#invoice_txtVAT');
            txtNetAmount = $('#invoice_txtNetAmount');
            txtDiscountAmount = $('#invoice_txtDiscountAmount');
            txtVATAmount = $('#invoice_txtVATAmount');
            txtPack = $('#invoice_txtPack');
            txtPartNumber = $('#invoice_txtPartNumber');
            totalValue = $('#totalValue');
            totalDiscount = $('#totalDiscount');
            totalTax = $('#totalTax');
            grandTotal = $('#grandTotal');
            txtBatchNo = $('#invoice_txtBatchNo');
            modal_PassCode = $('#modal_passcode');
            tableCustomer = $('#customer-search');
            tableBodyCustomer = $('tbody', tableCustomer);
            txtDetailNarration = $('invoice_txtNarration');
            txtMulkiyaNo = $('#mulkiyano');
            txtParkingNo = $('#parkingno');
            txtKeyNo = $('#keyno');

            /*SAEED 01-29-2020*/
            advance_creditcardamount = $('#advance_creditcardamount');
            advance_transactionno = $('#advance_transactionno');
            advance_cashamount = $('#advance_cashamount');
            advance_totalreceived  = $('#advance_totalreceived');

            tableChassis = $('#chassis-search');
            tableBodyChassis = $('tbody', tableChassis);



            $(txtFuel).change(function () {
                $('#fuel_level_percent').html($(this).val())
            })

            cboItem.select2({
                width: "100%",
                dropdownAutoWidth: true,
                templateResult: function (data) {
                    var i = $(data.element);
                    var $template;
                    if (i.attr('data-ItemName'))
                        $template = '<small><mark>' + i.attr('data-ItemName') + '</mark><em>&nbsp;' + i.attr('data-Brand') + '</em><br><span style="font-weight:bold">B:</span><span>' + i.attr('data-Barcode') + '</span><span style=font-weight:bold>&nbsp;S:</span><span>' + i.attr('data-Size') + '</span></small>'
                    else
                        $template = "<span>--Select Item--</span>";
                    return $($template);
                }
            });



//            FillCombo();

/*            cboUnit.select2({
                width: "100%",
                dropdownAutoWidth: true,
                templateResult: function (data) {
                    var i = $(data.element);
                    var $template;
                    if (i.attr('data-UnitName'))
                        $template = '<small><mark>' + i.attr('data-UnitName') + '</mark><em>&nbsp;' + i.attr('data-OtherInformation') + '</em><br></small>'
                    else
                        $template = "<span>--Select Unit--</span>";
                    return $($template);
                }
            });
//http://member.ddns.net:53556/webservice_Inventroid.asmx/GetCP_Unit
            var $request_unit = $.ajax({
                url: '',
                dataType: "json"
            });

            $request_unit.then(function (data) {
                for (var d = 0; d < data.length; d++) {
                    var unit = data[d];
                    var option = new Option(unit.UnitName + " / " + unit.OtherInformation, unit.ID, true, false);
                    $(option).attr('data-ID', unit.ID + "")
                    $(option).attr('data-UnitName', unit.UnitName + "")
                    $(option).attr('data-OtherInformation', unit.OtherInformation + "")
                    cboUnit.append(option);
                }
                cboUnit.trigger('change');
            });
*/




            cboSalesPerson.select2({
                placeholder: "--Select Sales Person--",
                width: "100%",
                dropdownAutoWidth: true,
                templateResult: function (data) {
                    var i = $(data.element);
                    var $template;
                    if (i.attr('data-SalesManName'))
                        $template = '<small><mark>' + i.attr('data-SalesManName') + '</mark></small>'
                    else
                        $template = "<span>--Select Sales Person--</span>";
                    return $($template);
                }
            });

            var $request_textbox = $.ajax({
                url: globalWebServiceInventoryPath + 'getjobcard.php?action=GetSalesMan&TextBoxName=SalesManInformation&fieldid=SalesManID&fieldname=SalesManName',
                dataType: "json"

            });


            $request_textbox.then(function (data) {
                for (var d = 0; d < data.length; d++) {
                    var textbox = data[d];
                    var option = new Option(textbox.SalesManName, textbox.SalesManID);

                    $(option).attr('data-SalesManID', textbox.SalesManID + "")
                    $(option).attr('data-SalesManName', textbox.SalesManName + "")
                    cboSalesPerson.append(option);
                }
                cboSalesPerson.trigger('change');
            });





            cboInstallersBy.select2({
                placeholder: "--Select Installers By--",
                width: "100%",
                dropdownAutoWidth: true,
                templateResult: function (data) {
                    var i = $(data.element);
                    var $template;
                    if (i.attr('data-SalesManName'))
                        $template = '<small><mark>' + i.attr('data-SalesManName') + '</mark></small>'
                    else
                        $template = "<span>--Select Installers By--</span>";
                    return $($template);
                }
            });

            var $request_textbox = $.ajax({
                url: globalWebServiceInventoryPath + 'getjobcard.php?action=GetSalesMan&TextBoxName=SalesManInformation&fieldid=SalesManID&fieldname=SalesManName',
                dataType: "json"

            });


            $request_textbox.then(function (data) {
                for (var d = 0; d < data.length; d++) {
                    var textbox = data[d];
                    var option = new Option(textbox.SalesManName, textbox.SalesManID);

                    $(option).attr('data-SalesManID', textbox.SalesManID + "")
                    $(option).attr('data-SalesManName', textbox.SalesManName + "")
                    cboInstallersBy.append(option);
                }
                cboInstallersBy.trigger('change');
            });


            cboVehicleBrand.select2({
                placeholder: "--Select Vehicle Brand--",
                width: "100%",
                dropdownAutoWidth: true,
                templateResult: function (data) {
                    var i = $(data.element);
                    var $template;
                    if (i.attr('data-MasterValue'))
                        $template = '<small><mark>' + i.attr('data-MasterValue') + '</mark></small>'
                    else
                        $template = "<span>--Select Vehicle Brand--</span>";
                    return $($template);
                }
            });

            var $request_textbox = $.ajax({
                url: globalWebServiceInventoryPath + 'getmastervalue.php?action=optionview&TextBoxName=Make',
                dataType: "json"

            });


            $request_textbox.then(function (data) {
                for (var d = 0; d < data.length; d++) {
                    var textbox = data[d];
                    var option = new Option(textbox.MasterValue, textbox.MasterValueID);

                    $(option).attr('data-MasterValueID', textbox.MasterValueID + "")
                    $(option).attr('data-MasterValue', textbox.MasterValue + "")
                    cboVehicleBrand.append(option);
                }
                cboVehicleBrand.trigger('change');
            });

            // cboVehicleBrand.change(function () {
            //     var brand = cboVehicleBrand.select2('data')[0].element;
            //     SearchBrandID = $(brand).attr('data-MasterValueID');

            //     VehicleModelRetreive();
            // });


            cboVehicleType.select2({
                placeholder: "--Select Type--",
                width: "100%",
                dropdownAutoWidth: true,
                templateResult: function (data) {
                    var i = $(data.element);
                    var $template;
                    if (i.attr('data-MasterValue'))
                        $template = '<small><mark>' + i.attr('data-MasterValue') + '</mark></small>'
                    else
                        $template = "<span>--Select Type--</span>";
                    return $($template);
                }
            });

            var $request_textbox = $.ajax({
                url: globalWebServiceInventoryPath + 'getmastervalue.php?action=optionview&TextBoxName=Vehicle Type',
                dataType: "json"

            });


            $request_textbox.then(function (data) {
                for (var d = 0; d < data.length; d++) {
                    var textbox = data[d];
                    var option = new Option(textbox.MasterValue, textbox.MasterValueID);

                    $(option).attr('data-MasterValueID', textbox.MasterValueID + "")
                    $(option).attr('data-MasterValue', textbox.MasterValue + "")
                    cboVehicleType.append(option);
                }
                cboVehicleType.trigger('change');
            });




            $(cboVehicleModel).select2({//cboVehicleModel

                placeholder: "--Select Model--",
                ajax: {
                    //                    url: globalWebServiceInventoryPath + '/webservice_Inventroid.asmx/GetMasterValueOperations?TextBoxName=Model&CategoryID=' + SearchBrandID,
                    url: globalWebServiceInventoryPath + 'getmastervalue.php?action=optionview&TextBoxName=Model',
                    dataType: 'json',
                    delay: 250,
                    cache: false,

                    processResults: function (resp) {

                        var data = resp;
                        if (data) {
                            var result = data.map(function (el) {
                                var o = Object.assign({}, el);
                                el.label = el.MasterValue;
                                el.id = el.MasterValueID;
                                el.text = el.MasterValue;
                                el.value = el.MasterValueID;
                                return o;
                            })
                            data.unshift({ label: "--Select Model--", id: " ", text: "--Select Model--", value: " " })
                        }
                        return {
                            results: data,
                            "pagination": {
                                "more": false
                            }
                        };
                    }, data: function (params) {

                        var brand = cboVehicleBrand.select2('data')[0].element;
                        var query = {
                            MasterValue: params.term,
                            CategoryID: $(brand).attr('data-MasterValueID') ? $(brand).attr('data-MasterValueID') : null,

                        }

                        //console.log(query)
                        return query;

                    }

                },
                escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
                width: '100%',
            })
























            // function VehicleModelRetreive() {

            //     cboVehicleModel.select2({
            //         placeholder: "--Select Model--",
            //         width: "100%",
            //         dropdownAutoWidth: true,
            //         templateResult: function (data) {
            //             var i = $(data.element);
            //             var $template;
            //             if (i.attr('data-MasterValue'))
            //                 $template = '<small><mark>' + i.attr('data-MasterValue') + '</mark></small>'
            //             else
            //                 $template = "<span>--Select Model--</span>";
            //             return $($template);
            //         }
            //     });


            //     var $request_textbox = $.ajax({
            //         url: globalWebServiceInventoryPath + '/webservice_Inventroid.asmx/GetMasterValueOperations?TextBoxName=Model&CategoryID=' + SearchBrandID,
            //         dataType: "json"

            //     });


            //     $request_textbox.then(function (data) {
            //         for (var d = 0; d < data.length; d++) {
            //             var textbox = data[d];
            //             var option = new Option(textbox.MasterValue, textbox.MasterValueID);

            //             $(option).attr('data-MasterValueID', textbox.MasterValueID + "")
            //             $(option).attr('data-MasterValue', textbox.MasterValue + "")
            //             cboVehicleModel.append(option);
            //         }
            //         cboVehicleModel.trigger('change');

            //     });

            // }







            cboVehicleSize.select2({
                placeholder: "--Select Vehicle Size--",
                width: "100%",
                dropdownAutoWidth: true,
                templateResult: function (data) {
                    var i = $(data.element);
                    var $template;
                    if (i.attr('data-MasterValue'))
                        $template = '<small><mark>' + i.attr('data-MasterValue') + '</mark></small>'
                    else
                        $template = "<span>--Select Vehicle Size--</span>";
                    return $($template);
                }
            });

            var $request_textbox = $.ajax({
                url: globalWebServiceInventoryPath + 'getmastervalue.php?action=optionview&TextBoxName=Vehicle Size',
                dataType: "json"

            });


            $request_textbox.then(function (data) {
                for (var d = 0; d < data.length; d++) {
                    var textbox = data[d];
                    var option = new Option(textbox.MasterValue, textbox.MasterValueID);

                    $(option).attr('data-MasterValueID', textbox.MasterValueID + "")
                    $(option).attr('data-MasterValue', textbox.MasterValue + "")
                    cboVehicleSize.append(option);
                }
                cboVehicleSize.trigger('change');
            });


            cboVehicleColor.select2({
                placeholder: "--Select Vehicle Color--",
                width: "100%",
                dropdownAutoWidth: true,
                templateResult: function (data) {
                    var i = $(data.element);
                    var $template;
                    if (i.attr('data-MasterValue'))
                        $template = '<small><mark>' + i.attr('data-MasterValue') + '</mark></small>'
                    else
                        $template = "<span>--Select Vehicle Color--</span>";
                    return $($template);
                }
            });

            var $request_textbox = $.ajax({
                url: globalWebServiceInventoryPath + 'getmastervalue.php?action=optionview&TextBoxName=Vehicle Colors',
                dataType: "json"

            });


            $request_textbox.then(function (data) {
                for (var d = 0; d < data.length; d++) {
                    var textbox = data[d];
                    var option = new Option(textbox.MasterValue, textbox.MasterValueID);

                    $(option).attr('data-MasterValueID', textbox.MasterValueID + "")
                    $(option).attr('data-MasterValue', textbox.MasterValue + "")
                    cboVehicleColor.append(option);
                }
                cboVehicleColor.trigger('change');
            });


            cboManufacturerYear.select2({
                placeholder: "--Select Year--",
                width: "100%",
                dropdownAutoWidth: true,
                templateResult: function (data) {
                    var i = $(data.element);
                    var $template;
                    if (i.attr('data-MasterValue'))
                        $template = '<small><mark>' + i.attr('data-MasterValue') + '</mark></small>'
                    else
                        $template = "<span>--Select Year--</span>";
                    return $($template);
                }
            });

            var $request_textbox = $.ajax({
                url: globalWebServiceInventoryPath + 'getmastervalue.php?action=optionview&TextBoxName=Year',
                dataType: "json"

            });


            $request_textbox.then(function (data) {
                for (var d = 0; d < data.length; d++) {
                    var textbox = data[d];
                    var option = new Option(textbox.MasterValue, textbox.MasterValueID);

                    $(option).attr('data-MasterValueID', textbox.MasterValueID + "")
                    $(option).attr('data-MasterValue', textbox.MasterValue + "")
                    cboManufacturerYear.append(option);
                }
                cboManufacturerYear.trigger('change');
            });





            cboCustomerType.select2({
                placeholder: "--Select Customer Type--",
                width: "100%",
                dropdownAutoWidth: true,
                templateResult: function (data) {
                    var i = $(data.element);
                    var $template;
                    if (i.attr('data-MasterValue'))
                        $template = '<small><mark>' + i.attr('data-MasterValue') + '</mark></small>'
                    else
                        $template = "<span>--Select Types--</span>";
                    return $($template);
                }
            });

            var $request_textbox = $.ajax({
                url: globalWebServiceInventoryPath + 'getmastervalue.php?action=optionview&TextBoxName=CustomerType',
                dataType: "json"

            });


            $request_textbox.then(function (data) {
                for (var d = 0; d < data.length; d++) {
                    var textbox = data[d];
                    var option = new Option(textbox.MasterValue, textbox.MasterValueID);

                    $(option).attr('data-MasterValueID', textbox.MasterValueID + "")
                    $(option).attr('data-MasterValue', textbox.MasterValue + "")
                    cboCustomerType.append(option);
                }
                cboCustomerType.trigger('change');
            });
        })



        GetWarningLights();
        GetCheckList();

        function FillCombo() {
            var $request_item = $.ajax({
                url: globalWebServiceInventoryPath + '/webservice_Inventroid.asmx/GetProducts?SideBarID=53',
                dataType: "json"
            });

            $request_item.then(function (data) {
                if (!data || !data.Database) return;

                for (var d = 0; d < data.length; d++) {
                    var item = data[d];
                    var option = new Option(item.ItemName, item.ID, true, false);
                    $(option).attr('data-ItemID', item.ID + "")
                    $(option).attr('data-ItemName', item.ItemName + "")
                    $(option).attr('data-GodownID', item.GodownID + "")
                    $(option).attr('data-Balance', item.Balance + "")
                    $(option).attr('data-BalanceCartons', item.BalanceCartons + "")
                    $(option).attr('data-Size', item.Size + "")
                    $(option).attr('data-Barcode', item.Barcode + "")
                    $(option).attr('data-Location', item.Location + "")
                    $(option).attr('data-Category', item.Category + "")
                    $(option).attr('data-Unit', item.Unit + "")
                    $(option).attr('data-Brand', item.Brand + "")
                    $(option).attr('data-Rate', item.RetailPrice + "")
                    cboItem.append(option);

                }

                cboItem.trigger('change');

                cboItem.change(function () {
                    var item = cboItem.select2('data')[0].element;
                    txtRate.val($(item).attr('data-Rate'));
                });

            });
        }

        function GetWarningLights() {
            $.ajax({
                url: globalWebServiceInventoryPath + 'getmastervalue.php?action=optionview&TextBoxName=Warning LIST',
                dataType: "json",
            }).then(function (data) {
                fillWarningList(data);
            });

        }

        function fillWarningList(data) {

            $('tr', warningtablebody).remove();

            if (!data) return;

            for (var i = 0; i < data.length; i++) {

                var o = new Object();
                o.RowNum = data[i].row_num ? data[i].row_num : "";
                o.MasterValue = data[i].MasterValue ? data[i].MasterValue : "";
                o.MasterValueID = data[i].MasterValueID;
                o.Description = data[i].Description;
                o.JobDetailID = data[i].JobDetailID ? data[i].JobDetailID : 0;

                var checkValueYes = "";
                var checkValueNo = "";

                if (!o.Description || o.Description == "0") {
                    checkValueYes = "";
                    checkValueNo = 'checked="checked"';
                }
                else {
                    checkValueYes = 'checked="checked"';
                    checkValueNo = "";
                }

                currentEditRow = $('<tr>\r\n' +
                    '  <td style="border:1px solid #000;" name="col_MasterValue">' + o.MasterValue + '</td>\r\n' +
                    '  <td style="border:1px solid #000;width: 10%;">\r\n' +
                    '      <label class="switchToggle1" style="margin-bottom:0px;">\r\n' +
                    '          <input type="radio" name="warninglights' + o.MasterValueID + '" value="1" ' + checkValueYes + '>\r\n' +
                    '          <span class="slider aqua round"></span> \r\n' +
                    '      </label></td>\r\n' +
                    '  <td style="border:1px solid #000;width: 10%;">\r\n' +
                    '      <label class="switchToggle1" style="margin-bottom:0px;">\r\n' +
                    '          <input type="radio" name="warninglights' + o.MasterValueID + '" value="0" ' + checkValueNo + '>\r\n' +
                    '          <span class="slider aqua round"></span> \r\n' +
                    '      </label></td>\r\n' +
                    '</tr>\r\n');

                currentEditRow.attr("data-Row", JSON.stringify(o));

                $(currentEditRow).hide()
                    .appendTo(warningtablebody)
                    .fadeIn("slow");
                currentEditRow = null;


            }
        }

        function GetCheckList() {
            $.ajax({
                url: globalWebServiceInventoryPath + 'getmastervalue.php?action=optionview&TextBoxName=Check LIST',
                dataType: "json",
            }).then(function (data) {
                fillCheckList(data);
            });
        }

        function fillCheckList(data) {


            $('tr', checklisttablebody).remove();

            if (!data) return;

            for (var i = 0; i < data.length; i++) {

                var o = new Object();
                o.MasterValue = data[i].MasterValue ? data[i].MasterValue : "";
                o.MasterValueID = data[i].MasterValueID;
                o.Description = data[i].Description;
                o.JobDetailID = data[i].JobDetailID ? data[i].JobDetailID : 0;

                var checkValue = "";

                if (!o.Description || o.Description == "0") {

                }
                else {
                    checkValue = 'checked="checked"';
                }



                currentEditRow = $('<tr>\r\n' +
                    '  <td style="border:1px solid #000; width: 10%;">\r\n' +
                    '  <label class="switchToggle1" style="margin-bottom:0px;">\r\n' +
                    '     <input type="checkbox" name="col_MasterValueID' + o.MasterValueID + '" value="1" ' + checkValue + '>\r\n' +
                    '         <span class="slider aqua round"></span> \r\n' +
                    '          <span class="slider aqua round"></span> \r\n' +
                    '      </label></td>\r\n' +
                    '  <td style="border:1px solid #000; "name="col_MasterValue">' + o.MasterValue + '</td>\r\n' +
                    '</tr>\r\n');
                currentEditRow.attr("data-Row", JSON.stringify(o));

                $(currentEditRow).hide()
                    .appendTo(checklisttablebody)
                    .fadeIn("slow");
                currentEditRow = null;
            }

        }



        function convertToDate(object) {
            if ($(object).val()) {

                try {

                    const months = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"];
                    var parts = $(object).val().split("-");
                    var current_datetime = new Date(parts[2], parts[1] - 1, parts[0], 0, 0, 0, 0);
                    let formatted_date = current_datetime.getDate() + "-" + months[current_datetime.getMonth()] + "-" + current_datetime.getFullYear()
                    return formatted_date + "";

                } catch{
                    return null;
                }
            }

        }




        function fillInspectionList(data) {
            console.log('ins:'+JSON.stringify(data));
            $('tr', inspectiontablebody).remove();

            if (!data) return;
            for (var i = 0; i < data.length; i++) {


                var o = new Object();
                o.RowNum = data[i].row_num ? data[i].row_num : "";
                o.MasterValue = data[i].MasterValue ? data[i].MasterValue : "";
                if(o.MasterValue=='')
                o.MasterValue = data[i].Particulars ? data[i].Particulars : "";                
                o.MasterValueID = data[i].MasterValueID;
                o.Description = data[i].Description;
                o.JobDetailID = data[i].JobDetailID ? data[i].JobDetailID : 0;
                o.PictureLocation = data[i].PictureLocation;

                currentEditRow = $("<tr><td><a href='javascript:void(0);' class='remove' title='Remove'><i class='fa fa-trash-o'></i></a><small>" + o.MasterValue + "</small><input type='hidden' name='insp[]' value='" + o.MasterValue + "'><br/><input class='form-control'  type='text' name='remark[]' value='" + o.Description + "' placeholder='Explain problem' ></td><td> <small>Snap</small><br/> <label for='file-upload' class='custom-file-upload snap'><i class='fa fa-camera'></i></label></td></tr>");


                $(currentEditRow).attr("data-Row", JSON.stringify(o));


                $(currentEditRow).hide()
                    .appendTo(inspectiontablebody)
                    .fadeIn("slow");
                currentEditRow = null;
            }

        }

        //console.log(globalWebServiceInventoryPath + '/webservice_Inventroid.asmx/GetPurchaseInvoiceList?SideBarID=' + SideBarID + '&InvoiceType=' + 5)








    




        $('#doSearch').click(function () {

        /*    refreshTable();
            return;
*/
            var data = new Object();
            data.Company = $('#Search_Company').val();
            data.Supplier = $('#Search_Supplier').val();
            data.BillDate = $('#Search_BillDate').val();
            data.Narration = $('#Search_Narration').val();
            data.ReferenceNo = $('#Search_ReferenceNo').val();
            data.Customer = $('#Search_Customer').val();
            data.GodownID = CurrentCompanyID;
       data.Customer_MobileNumber = $('#Invoice_Search_CustomerMobile').val();
                    data.Customer_PlateNumber = $('#Invoice_Search_PlateNumber').val();
                    data.Customer_ChassisNumber = $('#Invoice_Search_ChassisNumber').val();
                    data.InvoiceStatus = $('#Invoice_Search_OrderStatus').val();

                    if ($('#Search_BillDate').val()) {
                        data.BillDate = convertToDate($('#Search_BillDate'));
                    }

                    if ($('#Invoice_Search_PromiseDate').val()) {
                        data.DeliveryDate = convertToDate($('#Invoice_Search_PromiseDate'));
                    }

            $('tr>td:not(#invoice-no-data-search)', tableBodySearch).remove();
            //tableBodySearch.find('tr:not(#invoice-no-data-search)').remove();
            $('#invoice-no-data-search').fadeIn('fast');

            var $request_voucher = $.ajax({
                url: globalWebServiceInventoryPath + 'getjobcard.php?action=jobcardlist&search=true&SideBarID=' + SideBarID + '&InvoiceType=' + 5,
                dataType: "json",
                data: data,
            });

            $request_voucher.then(function (data) {
                $('#invoice-no-data-search').fadeOut('fast');
                for (var i = 0; i < data.length; i++) {


                    var o = new Object();
                    var status;
                    o.InvoiceDate = data[i].InvoiceDate ? data[i].InvoiceDate : "";
                    o.Narration = data[i].Narration ? data[i].Narration : "";
                    o.KeyField = data[i].KeyField ? data[i].KeyField : "";
                    o.Location = data[i].CompanyShortForm ? data[i].CompanyShortForm : "";

                    //o.Customer = data[i].Customer ? data[i].Customer : "";
                    o.JC_MobileNumber = data[i].JC_MobileNumber;
                    o.JC_PlateNumber = data[i].JC_PlateNumber;
                    o.JC_ChassisNumber = data[i].JC_ChassisNumber;
                    o.JC_CustomerName = data[i].JC_CustomerName;

                    o.DeliveryDate = data[i].DeliveryDate ? data[i].DeliveryDate : "";
                    o.LastModificationTimeStamp = data[i].LastModificationTimeStamp;
                    o.InvoiceID = data[i].InvoiceID;
                    o.OrderStatus = data[i].InvoiceStatus;
                    switch(o.OrderStatus)
                    {
                        case '1':
                        o.OrderStatus='PENDING';
                        break;
                        case '2':
                        o.OrderStatus='ACCEPTED';
                        break;
                        case '3':
                        o.OrderStatus='REJECTED';
                        break;
                        case '4':
                        o.OrderStatus='CLOSED';
                        break;
                    }
                    o.Row_No = data[i].row_num;

                    currentEditRow = $('<tr>\r\n' +
                        '    <td name="col_SNo"></td>\r\n' +
                        '    <td name="col_Customer"></td>\r\n' +
                        '    <td name="col_Company"></td>\r\n' +
                        '    <td name="col_BillDate"></td>\r\n' +
                        '    <td name="col_ReferenceNo"></td>\r\n' +
                        '    <td name="col_DeliveryDate" style="width:40%;"></td>\r\n' +
                        '    <td name="col_OrderStatus"></td>\r\n' +
                        '    <td name="col_Action" style="display:none;width: 80px;text-align: center;vertical-align: middle">\r\n' +
                        //'\r\n' +
                        //'        <i class="fa fa-pencil fa-lg" style="text-align: left;color: blue;cursor:pointer;" onclick="javascript:editMaster(this);"></i><br/>\r\n' +
                        //'        <i class="fa fa-trash-o fa-lg" style="text-align: right;color: red;cursor:pointer;" onclick="javascript:deleteMaster(this);"></i>\r\n' +
                        //'    \r\n' +
                        '    </td>\r\n' +
                        '<td name="col_Action1" style="width: 80px;">\r\n' +
                        '    <div class="btn-group">\r\n' +
                        '        <button type="button" class="btn btn-danger dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">\r\n' +
                        '            Action\r\n' +
                        '        </button>\r\n' +
                        '        <div class="dropdown-menu">\r\n' +
                        '            <a class="dropdown-item" href="#" onclick="javascript:editMaster(this);"><i class="fa fa-pencil fa-lg" style="text-align: left;color: blue;cursor:pointer;" ></i>&nbsp;&nbsp;Edit</a>\r\n' +
                        '            <a class="dropdown-item" href="#" onclick="javascript:deleteMaster(this);"><i class="fa fa-trash-o fa-lg" style="text-align: left;color: red;cursor:pointer;" ></i>&nbsp;&nbsp;Delete</a>\r\n' +
                        '            <div class="dropdown-divider"></div>\r\n' +
                        '            <a class="dropdown-item" href="#" onclick="javascript:ApprovedRow(this);"><i class="icon-check fa-lg" style="text-align: left;color: blue;cursor:pointer;" ></i>&nbsp;&nbsp;Approve</a>\r\n' +
                        '            <a class="dropdown-item" href="#" onclick="javascript:DisApproveRow(this);"><i class="icon-close fa-lg" style="text-align: left;color: red;cursor:pointer;" ></i>&nbsp;&nbsp;Disapprove</a>\r\n' +
                        '            <div class="dropdown-divider"></div>\r\n' +
                        '            <a class="dropdown-item" href="#" onclick="javascript:GenerateInvoice(this);"><i class="fa fa-file-alt" style="text-align: left;color: red;cursor:pointer;" ></i>&nbsp;&nbsp;Generate Invoice</a>\r\n' +
                        '            <div class="dropdown-divider"></div>\r\n' +

                        '            <a class="dropdown-item" href="#" onclick="javascript:openReport(this,\'./pages/job_sheet.html?sidebarid=' + SideBarID + '&InvoiceID=' + o.InvoiceID + '&InvoiceNo=' + o.KeyField + '\',\'Job Sheet\');" ><i class="icon-pencil-alt fa-lg" style="text-align: left;color: black;cursor:pointer;" ></i>&nbsp;&nbsp;Job Sheet</a>\r\n' +
                        '            <a class="dropdown-item" href="#" onclick="javascript:openReport(this,\'./pages/material_request.html?ProductSideBarID=44&InvoiceType=6&ProductBaseType=ITEM&sidebarid=' + SideBarID + '&InvoiceID=' + o.InvoiceID + '&InvoiceNo=' + o.KeyField + '\',\'Issue Slip\');" ><i class="icon-shopping-cart-full fa-lg" style="text-align: left;color: black;cursor:pointer;" ></i>&nbsp;&nbsp;Issue Slip</a>\r\n' +

                        '            <div class="dropdown-divider"></div>\r\n' +
                        '            <a class="dropdown-item" href="#" onclick="javascript:openReport(this,\'./reportViewer.aspx?refresh=1&reportFileName=jobcardreport.html&KeyField=' + o.InvoiceID + '\',\'Job Card Report\');" ><i class="icon-printer fa-lg" style="text-align: left;color: green;cursor:pointer;" ></i>&nbsp;&nbsp;Print Job card</a>\r\n' +
                        '            <a class="dropdown-item" href="#" onclick="javascript:openReport(this,\'./reportViewer.aspx?refresh=1&reportFileName=reports/Damage_Report.trdx&KeyField=' + o.InvoiceID + '\',\'Inspection Report\');" ><i class="icon-printer fa-lg" style="text-align: left;color: green;cursor:pointer;" ></i>&nbsp;&nbsp;Inspection Report</a>\r\n' +
                        '        </div>\r\n' +
                        '    </div>\r\n' +

                        /*
                            

                        '<div class="btn-group">\r\n' +
                        '    <button type="button" class="btn btn-danger">Action</button>\r\n' +
                        '    <button type="button" class="btn btn-danger dropdown-toggle" data-toggle="dropdown">\r\n' +
                        '        <span class="caret"></span>\r\n' +
                        '        <span class="sr-only">Toggle Dropdown</span>\r\n' +
                        '    </button>\r\n' +
                        '    <ul class="dropdown-menu" role="menu">\r\n' +
                        '        <li><a class="dropdown-item" href="#" onclick="javascript:editMaster(this);"><i class="fa fa-pencil fa-lg" style="text-align: left;color: blue;cursor:pointer;" ></i>&nbsp;&nbsp;Edit</a></li>\r\n' +
                        '        <li><a class="dropdown-item" href="#" onclick="javascript:deleteMaster(this);"><i class="fa fa-trash-o fa-lg" style="text-align: left;color: red;cursor:pointer;" ></i>&nbsp;&nbsp;Delete</a></li>\r\n' +
                        '        <li class="divider"></li>\r\n' +
                        
                        '        <li><a class="dropdown-item" href="#" onclick="javascript:ApprovedRow(this);"><i class="icon-check fa-lg" style="text-align: left;color: blue;cursor:pointer;" ></i>&nbsp;&nbsp;Approve</a></li>\r\n' +
                        '        <li><a class="dropdown-item" href="#" onclick="javascript:DisApproveRow(this);"><i class="icon-close fa-lg" style="text-align: left;color: red;cursor:pointer;" ></i>&nbsp;&nbsp;Disapprove</a></li>\r\n' +
                        '        <li class="divider"></li>\r\n' +

                        '        <li><a class="dropdown-item" href="#" onclick="javascript:openReport(this,\'./reportViewer.aspx?refresh=1&reportFileName=reports/Job_Card.trdx&KeyField=' + o.InvoiceID + '\',\'Job Card Report\');" ><i class="icon-printer fa-lg" style="text-align: left;color: green;cursor:pointer;" ></i>&nbsp;&nbsp;Print Job card</a></li>\r\n' +
                        '        <li><a class="dropdown-item" href="#" onclick="javascript:openReport(this,\'./reportViewer.aspx?refresh=1&reportFileName=reports/Damage_Report.trdx&KeyField=' + o.InvoiceID + '\',\'Damage Report\');" ><i class="icon-printer fa-lg" style="text-align: left;color: green;cursor:pointer;" ></i>&nbsp;&nbsp;Print Damage report</a></li>\r\n' +

                        '    </ul>\r\n' +
                        '    </div>\r\n' +
                        */

                        // '<div class="dropdown-basic" style="min-width:110px">\r\n'+
                        // '<div class="dropdown">\r\n' +
                        // '    <div class="btn-group mb-0">\r\n' +
                        // '        <button type="button" class="dropbtn btn-info">Action <span><i class="icofont icofont-arrow-down"></i></span></button>\r\n' +
                        // '        <div class="dropdown-content">\r\n' +
                        // '            \r\n' +
                        // '            <a href="#"><i class="fa fa-pencil fa-lg" style="text-align: left;color: blue;cursor:pointer;" onclick="javascript:editMaster(this);"></i></a>\r\n' +
                        // '            <a href="#"><i class="fa fa-trash-o fa-lg" style="text-align: right;color: red;cursor:pointer;" onclick="javascript:deleteMaster(this);"></i></a>\r\n' +

                        // '            <div class="dropdown-divider"></div>\r\n' +

                        // '            <a href="#"><i class="icon-check fa-lg" style="text-align: left;color: blue;cursor:pointer;" onclick="javascript:ApprovedRow(this);"></i> Approve</a>\r\n' +
                        // '            <a href="#"><i class="icon-close fa-lg" style="text-align: right;color: red;cursor:pointer;" onclick="javascript:DisApproveRow(this);"></i>Disapprove</a>\r\n' +
                        // '        </div>\r\n' +
                        // '    </div>\r\n' +
                        // '</div>\r\n' +
                        // '</div>\r\n' +

                        '</td>\r\n' +
                        '\r\n' +
                        '</tr>\r\n')


                    currentEditRow.attr('data-Flag', 'R');
                    currentEditRow.children("td[name='col_SNo']").html('' + o.Row_No + '<br/>');
                    currentEditRow.children("td[name='col_Customer']").html('' + o.JC_CustomerName + '<br/><mark>' + o.JC_MobileNumber + '</mark>');
                    currentEditRow.children("td[name='col_Company']").html('' + o.Location + '<br/>');
                    currentEditRow.children("td[name='col_BillDate']").html('' + o.InvoiceDate + '<br/>');
                    currentEditRow.children("td[name='col_ReferenceNo']").html('' + o.KeyField + '<br/>');
                    currentEditRow.children("td[name='col_DeliveryDate']").html('' + o.DeliveryDate + '<br/>'+'Details:'+o.Narration+'<br>Chassis Number: '+o.JC_ChassisNumber+'<br/>'+'Plate Number: '+o.JC_PlateNumber+'<br/>');
//                    currentEditRow.children("td[name='col_Narration']").html('' + o.Narration + '<br/>');
                    currentEditRow.children("td[name='col_OrderStatus']").html('' + o.OrderStatus + '<br/>');
                    currentEditRow.attr("data-Row", JSON.stringify(o));
                    $(currentEditRow).hide()
                        .prependTo(tableBodySearch)
                        .fadeIn("slow");
                    currentEditRow = null;
                }

            });

        });

        function deleteMaster(sender) {
            bootbox.confirm({
                title: "Delete Item",
                message: "Do you want to delete this row?",
                buttons: {
                    cancel: {
                        label: '<i class="fa fa-times"></i> Cancel'
                    },
                    confirm: {
                        label: '<i class="fa fa-check"></i> Confirm'
                    }
                },
                callback: function (result) {
                    if (result) {
                        currentEditRow = $(sender).parents('tr');
                        // var data = JSON.parse(currentEditRow.attr("data-Row"));

                        var row = $(tableSearch).DataTable().row(currentEditRow);//Added for DataTable
                        var data = row.data();//Added for DataTable

                        $.ajax({

                            url: globalWebServiceInventoryPath + '/webservice_Inventroid.asmx/DeletePurchaseInvoice?SideBarID=' + SideBarID + '&InvoiceID=' + (data.InvoiceID) + '&LastModificationTimeStamp=' + (data.LastModificationTimeStamp),

                            type: 'post',
                            dataType: 'json',
                            //timeout: 2000,
                            beforeSend: function () {
                                (form).find(":submit").prop("disabled", "disabled");
                            },
                            success: function (data) {
                                if (data.status == "ok") {
                                    $.notify({ message: data.description }, alertTypeSuccess);

                                    $(currentEditRow).remove();

                                    var visibleCount = tableBody.children('tr:visible').length;
                                    if (visibleCount == 0) {
                                        $('#invoice-no-data-search').fadeIn('fast');
                                    }
                                }
                                else {
                                    $.notify({ message: data.description }, alertTypeCritical);
                                }
                            }, error: function (jqXHR, textStatus) {
                                $.notify({ message: data.description }, alertTypeCritical);
                            }, complete: function () {
                                $(form).find(":submit").prop("disabled", null);
                            }
                        });
                    }
                }
            });
        }


        function editMaster(sender) {

            var edit_row = $(sender).parents('tr');
            // var data = JSON.parse(searchRow.attr("data-Row"));
            var row = $(tableSearch).DataTable().row(edit_row);//Added for DataTable
            var data = row.data();//Added for DataTable
            InvoiceID=data.InvoiceID;
            var $request_voucherdetails = $.ajax({
                url: globalWebServiceInventoryPath + 'getjobcard.php?action=getInvoice&InvoiceID=' + (data.InvoiceID) + '&SideBarID=' + SideBarID,
                dataType: "json"
            });

            $request_voucherdetails.then(function (data) {

                ClearForm(true);


                var allinvoice = data[0][0];
                allinvoice.CheckList=data['CheckList'];
                allinvoice.WarningDetail=data['WarningDetail'];
                allinvoice.InspectionList=data['InspectionList'];
                allinvoice.detailitems=data['detailitems'];
//console.log(allinvoice.detailitems);


                if (allinvoice.CheckInTime) {
                    $('#CheckIn').html(allinvoice.CheckInTime);
                }
                else {
                    $('#CheckIn').prop('disabled', null)
                }


                if (allinvoice.CheckInTime && allinvoice.CheckOutTime) {
                    $('#CheckOut').html(allinvoice.CheckOutTime);

                } else {
                    if (allinvoice.CheckInTime)
                        $('#CheckOut').prop('disabled', null)
                }

                txtFuel.val(allinvoice.fuellevel).trigger('change');
                
                $('#PictureLocation').val(allinvoice.picturelocation);//PICTURE_LINE

                dtJobCardDate.val(date_format(allinvoice.invoicedate));
                dtPromiseDate.val(date_format(allinvoice.deliverydate));
                txtPreparedBy.val(allinvoice.UserName).trigger('change');
                cboVehicleBrand.val(allinvoice.vehiclebrand).trigger('change');
                cboVehicleModel.val(allinvoice.vehiclemodel).trigger('change');
                cboVehicleType.val(allinvoice.vehicletype).trigger('change');
                cboVehicleSize.val(allinvoice.vehiclesize).trigger('change');
                cboVehicleColor.val(allinvoice.vehiclecolor).trigger('change');
                cboManufacturerYear.val(allinvoice.vehicleyear).trigger('change');
                cboCustomerType.val(allinvoice.customertype).trigger('change');
                cboSalesPerson.val(allinvoice.salesmanid).trigger('change');
                cboInstallersBy.val(allinvoice.salesmanid2).trigger('change');


                txtKMRun.val(allinvoice.challanno);

                txtInvoiceID = InvoiceID;

                $('#Supplier_cboSupplier').val(allinvoice.supplierid).trigger('change');

                txtLastModificationTimeStamp = allinvoice.lastmodificationdatetime;
                txtNotes.summernote('code', allinvoice.notes);

                txtMobile.val(allinvoice.mobilenumber);
                txtCustomerName.val(allinvoice.customerName);
                txtPlateNo.val(allinvoice.platenumber);
                txtChassisNo.val(allinvoice.chassisnumber);
                txtTRN.val(allinvoice.trnno);
                txtEmail.val(allinvoice.email);

                totalValue.text(allinvoice.totalamount);
                totalDiscount.text(allinvoice.discountamount);
                totalTax.text(allinvoice.taxamount);
                grandTotal.text(allinvoice.netamount);

                txtMulkiyaNo.val(allinvoice.mulkiyano);
                txtParkingNo.val(allinvoice.parkingno);
                txtKeyNo.val(allinvoice.keyno);
                $("#RetreiveKeyField").text('(EDIT MODE)' + allinvoice.keyfield);

                fillCheckList(allinvoice.CheckList);
                fillWarningList(allinvoice.WarningDetail);
                fillInspectionList(allinvoice.InspectionList);


                if (allinvoice.detailitems && allinvoice.detailitems.length) {
                    $('#invoice-no-data').fadeOut('fast');


                    for (var i = 0; i < allinvoice.detailitems.length; i++) {

                        var invoice_row = allinvoice.detailitems[i];

                        var o = new Object();

                        o.GUID = invoice_row.detailguid

                        o.Company_ID = invoice_row.ItemCompanyID
                        o.Company_Value = invoice_row.ItemCompanyName

                        o.BaseType_ID = invoice_row.ItemProductBaseType ? invoice_row.ItemProductBaseType : "";
                        o.BaseType_Value = invoice_row.ItemProductBaseType ? invoice_row.ItemProductBaseType : "";

                        o.MainCategory_ID = invoice_row.Under ? invoice_row.Under : "";
                        o.MainCategory_Value = invoice_row.Category ? invoice_row.Category : "";

                        o.SubCategory_ID = invoice_row.itemname ? invoice_row.itemname : "";
                        o.SubCategory_Value = invoice_row.itemname ? invoice_row.itemname : "";

                        o.Brand_ID = invoice_row.brand;
                        o.Brand_Value = invoice_row.brand;

                        o.Level_ID = invoice_row.ItemMaxQtyLevel ? invoice_row.ItemMaxQtyLevel : "";
                        o.Level_Value = invoice_row.ItemMaxQtyLevel ? invoice_row.ItemMaxQtyLevel : "";

                        o.Item_ItemID = invoice_row.itemid;
                        o.Item_ItemName = invoice_row.itemname;
                        o.Item_Barcode = invoice_row.barcode;

                        o.Qty = invoice_row.qty;
                        o.Rate = invoice_row.unitprice;
                        o.Amount = invoice_row.amount;
                        o.Discount = invoice_row.discountpercent;
                        o.DiscountAmount = invoice_row.discountamount;
                        o.VAT = invoice_row.vatpercent;
                        o.VATAmount = invoice_row.vatamount;
                        o.NetAmount = invoice_row.netamount;
                        o.TransactionID = invoice_row.transactionid;
                        o.Flag = "R";
                        o.SNo = invoice_row.row_num;
                        o.Narration = invoice_row.detailnarration;

                        currentEditRow = null;

                        postRow(o)

                    }
                }

                $('#basic-tab').click();
                setTimeout(function () { showFirstSlide() }, 10);

            });
        }

        function refreshTable()//Added for DataTable
        {
            $(tableSearch).DataTable().ajax.reload();//Added for DataTable
        }//Added for DataTable

        function refreshTableCustomer()//Added for DataTable
        {
            $(tableCustomer).DataTable().ajax.reload();//Added for DataTable
        }//Added for DataTable
        function doCustomerSearch() {
            refreshTableCustomer();
        }


        function refreshTableChassis()//Added for DataTable
        {
            $(tableChassis).DataTable().ajax.reload();//Added for DataTable
        }//Added for DataTable

        function doChassisSearch() {
            refreshTableChassis();
        }

        function doPost() {
            tableBody.find('tr:not(#invoice-no-data)').remove();
            $('#invoice-no-data').fadeIn('fast');


            var $request_accounts = $.ajax({
                url: globalWebServiceInventoryPath + '/webservice_Inventroid.asmx/GetMasterValueOperations',
                dataType: "json",
                data: $(searchForm).serialize(),
            });

            $request_accounts.then(function (data) {
                if (data.length)
                    $('#invoice-no-data').fadeOut('fast');

                for (var i = 0; i < data.length; i++) {


                    var o = new Object();
                    o.RowNum = data[i].row_num ? data[i].row_num : "";
                    o.MasterValue = data[i].MasterValue ? data[i].MasterValue : "";
                    o.TextBoxName = data[i].TextBoxName ? data[i].TextBoxName : "";
                    o.MasterValueID = data[i].MasterValueID;


                    currentEditRow = $('<tr>\r\n' +
                        '    <td name="col_SNo"></td>\r\n' +
                        '    <td name="col_MasterValue"></td>\r\n' +
                        '    <td name="col_TextBoxName"></td>\r\n' +
                        '    <td name="col_Action" style="width: 80px;text-align: center;vertical-align: middle">\r\n' +
                        '\r\n' +
                        '        <i class="fa fa-pencil fa-lg" style="text-align: left;color: blue;cursor:pointer;" onclick="javascript:editRow(this);"></i><br/>\r\n' +
                        '        <i class="fa fa-trash-o fa-lg" style="text-align: right;color: red;cursor:pointer;" onclick="javascript:deleteRow(this);"></i>\r\n' +
                        '    \r\n' +
                        '    </td>\r\n' +
                        '\r\n' +
                        '</tr>\r\n')



                    currentEditRow.attr('data-Flag', 'R');
                    currentEditRow.children("td[name='col_SNo']").html(i + 1 + '<br/>');
                    currentEditRow.children("td[name='col_MasterValue']").html('<mark>' + o.MasterValue + '</mark>');
                    currentEditRow.children("td[name='col_TextBoxName']").html('<mark>' + o.TextBoxName + '</mark>');
                    currentEditRow.attr("data-Row", JSON.stringify(o));

                    $(currentEditRow).hide()
                        .prependTo(tableBody)
                        .fadeIn("slow");
                    currentEditRow = null;
                }

            });

        }

        /* Added Saeed 01-29-2020*/
        function GenerateAdvance(sender) {

            $('#ReceivedAdvance').modal('show');
            currentGeneratedRow = $(sender).parents('tr');

            var row = $(tableSearch).DataTable().row(currentGeneratedRow);//Added for DataTable
            var data = row.data();//Added for DataTable

            //$('tr', advance_table_body).remove();

            $("#Advance_history_table tbody>tr").remove();
            advance_totalreceived.val('');

            $.ajax({
                url: globalWebServiceInventoryPath + 'getdepreciation.php?action=GetPaymentHistory&ReferenceInvoiceID=' + data.InvoiceID,
                dataType: "json"
            }).then(function (data) {
                for (var d = 0; d < data.length; d++) {
                    advance_history_row(data[d]);
                }
                advance_totalreceived.val(data.description);
            });




        }




        function doReceiptVoucherPrintOut(voucherID)
        {
           // $('#printModal').modal('show');
           // $('#reportPreview').attr('src', "http://member.ddns.net:53556/reportViewer.aspx?refresh=1&reportFileName=reports/Receipt_Voucher.trdx&VoucherNo=" + voucherID)
            //$('#reportPreview').refresh();
            var win=window.open("http://member.ddns.net:53556/reportViewer.aspx?refresh=1&reportFileName=reports/Receipt_Voucher.trdx&VoucherNo=" + voucherID,"_blank");
        }


        function advance_history_row(data)
        {
            var AdvanceHistoryRow = null;

            var detail_o = new Object();
            detail_o.VoucherID = data.VoucherID;
            detail_o.VoucherNo = data.VoucherNo;
            detail_o.TotalAmount = (data.TotalAmount ? data.TotalAmount : 0);
            detail_o.VoucherDate = data.VoucherDate;
            detail_o.ReferenceInvoiceID = data.ReferenceInvoiceID;
            detail_o.Print ='Print';
 
            detail_o.RowNo = data.row_num;
            AdvanceHistoryRow = $('<tr>\r\n' +
                '    <td name="col_SNo"></td>\r\n' +
                '    <td name="col_VoucherNo"></td>\r\n' +
                '    <td name="col_VoucherDate"></td>\r\n' +
                '    <td name="col_ReceivedAmount"></td>\r\n' +
                '    <td name="col_Print"><a href="#" onclick="javascript:doReceiptVoucherPrintOut(\''+ data.VoucherNo +'\');">' + detail_o.Print + '</a></td>\r\n')

                AdvanceHistoryRow.attr("data-Row", JSON.stringify(detail_o));
               // AdvanceHistoryRow.children("td[name='col_SNo']").html($('#Advance_history_table').children('tr:visible:not(#invoice-no-data)').length + 1);
                AdvanceHistoryRow.children("td[name='col_SNo']").html(detail_o.RowNo);
                AdvanceHistoryRow.children("td[name='col_VoucherNo']").html(detail_o.VoucherNo);
                AdvanceHistoryRow.children("td[name='col_VoucherDate']").html(detail_o.VoucherDate);
                AdvanceHistoryRow.children("td[name='col_ReceivedAmount']").html(detail_o.TotalAmount);
                // AdvanceHistoryRow.children("td[name='col_Print']").html(detail_o.Print);
            $(AdvanceHistoryRow).hide()
                .appendTo($('#Advance_history_table>tbody'))
                .fadeIn("slow");

            AdvanceHistoryRow = null;

        }








        /* Added Saeed 01-29-2020*/
        $('#saveAdvancePayment').click(function () {
            {

                // currentGeneratedRow = $(sender).parents('tr');
                var row = $(tableSearch).DataTable().row(currentGeneratedRow);//Added for DataTable
                var data = row.data();//Added for DataTable
                var Data = new Object();

                var cash;
                var credit;


                if ($(Advance_cboCash).select2('data')[0]) {
                    cash = $(Advance_cboCash).select2('data')[0].element;
                }
                if ($(Advance_cboCredit).select2('data')[0]) {
                    credit = $(Advance_cboCredit).select2('data')[0].element;
                }


                Data.CashAccountID = $(cash).attr('data-COAID');
                Data.CashAccountName = $(cash).attr('data-VendorName');

                Data.CreditAccountID = $(credit).attr('data-COAID');
                Data.CreditAccountName = $(credit).attr('data-VendorName');


                Data.CustomerID = 96;
                Data.CustomerName = 'Cash Customers';
                if (!Data.CashAccountID) {
                    $.notify({ message: 'Please select Cash A/C' }, alertTypeCritical);
                    return;
                }

                if (!Data.CreditAccountID) {
                    $.notify({ message: 'Please select Credit A/C' }, alertTypeCritical);
                    return;
                }

                if (Number($('#advance_creditcardamount').val()) > 0 && String($('#advance_transactionno').val()).trim().length == 0) {

                    $.notify({ message: 'Please enter credit card transaction number.' }, alertTypeCritical);
                    $('#advance_transactionno').focus();
                    return;
                }

                Data.InvoiceID = data.InvoiceID;
                Data.KeyField = data.KeyField;
                Data.GodownID = data.GodownID;
                Data.SideBarID = SideBarID;
                Data.InvoiceDate = data.InvoiceDate;
                Data.VoucherTypeID = 5;
                Data.CashAmount = advance_cashamount.val();
                Data.CreditAmount = advance_creditcardamount.val();
                Data.TransactionNumber = advance_transactionno.val();

                console.log(Data);

                $.ajax({

                    url: globalWebServiceInventoryPath + 'getjobcard.php?action=GenerateAdvancePayment',

                    type: 'post',
                    dataType: 'json',
                    data: 'data='+JSON.stringify(Data),

                    beforeSend: function () {
                        (form).find(":submit").prop("disabled", "disabled");
                    },
                    success: function (data) {
                        if (data.status == "ok") {
                            $.notify({ message:'Payment Received ' + data.description }, alertTypeSuccess);

                            //   $(Advance_cboCash).val('').trigger('change');
                            // $(Advance_cboCredit).val('').trigger('change');
                            $(advance_cashamount).val('').trigger('change');
                            $(advance_creditcardamount).val('').trigger('change');
                            $(advance_transactionno).val('').trigger('change');
                            currentGeneratedRow = null;
                            refreshTable();
                            $('#ReceivedAdvance').modal('hide');

                            doReceiptVoucherPrintOut(data.description);
                        }
                        else {
                            $.notify({ message: data.description }, alertTypeCritical);
                            currentGeneratedRow = null;

                        }
                    },

                });
            }
        });





        function GenerateInvoice(sender) {

            currentGeneratedRow = $(sender).parents('tr');
            var row = $(tableSearch).DataTable().row(currentGeneratedRow);//Added for DataTable
            var data = row.data();//Added for DataTable

            //Data.InvoiceID = data.InvoiceID;
            //console.log(data.InvoiceID)
            $.ajax({

                url: globalWebServiceInventoryPath + 'getjobcard.php?action=InvoiceCheck&InvoiceID=' + (data.InvoiceID),

                type: 'post',
                dataType: 'json',
                //data: JSON.stringify(Data),

                beforeSend: function () {
                    (form).find(":submit").prop("disabled", "disabled");
                },
                success: function (data) {
                    if (data.status == "ok") {
                        // $.notify({ message: data.description }, alertTypeSuccess);                    
                        $('#saveModal').modal('show');
                    }
                    else {
                        // $.notify({ message: data.description }, alertTypeCritical);
                        // currentGeneratedRow =null;
                        $('#printModal').modal('show');
                        $('#reportPreview').attr('src', "../report.php?refresh=1&reportFileName=reports/SalesInvoiceReport.trdx&InvoiceID=" + data.description)

                    }
                },

            });


        }






        $('#saveInvoice').click(function () {
            {


                //  var currentEditRow = $(this).attr('data-Row');
                var row = $(tableSearch).DataTable().row(currentGeneratedRow);//Added for DataTable
                var data = row.data();//Added for DataTable

                var Data = new Object();

                var customer;
                var sales;
                var ledger;
                var cogs;
                var stock;

                if ($('#Supplier_cboSupplier').select2('data')[0]) {
                    customer = $('#Supplier_cboSupplier').select2('data')[0].element;
                }
                if ($('#cboDebitTo').select2('data')[0]) {
                    sales = $('#cboDebitTo').select2('data')[0].element;
                }
                if ($('#cboVATLedgerID').select2('data')[0]) {
                    ledger = $('#cboVATLedgerID').select2('data')[0].element;
                }

                if ($('#cboCOGSLedger').select2('data')[0]) {
                    cogs = $('#cboCOGSLedger').select2('data')[0].element;
                }

                if ($('#cboStockLedger').select2('data')[0]) {
                    stock = $('#cboStockLedger').select2('data')[0].element;
                }





                Data.CustomerLedgerID = $(customer).attr('data-COAID');
                Data.CustomerLedgerName = $(customer).attr('data-VendorName');

                Data.SalesLedgerID = $(sales).attr('data-COAID');
                Data.SalesLedgerName = $(sales).attr('data-VendorName');

                Data.VATLedgerID = $(ledger).attr('data-COAID');
                Data.VATLedgerName = $(ledger).attr('data-VendorName');

                Data.COGSLedgerID = $(cogs).attr('data-COAID');
                Data.COGSLedgerName = $(cogs).attr('data-VendorName');

                Data.StockLedgerID = $(stock).attr('data-COAID');
                Data.StockLedgerName = $(stock).attr('data-VendorName');



                if (!Data.CustomerLedgerID) {
                    $.notify({ message: 'Please select Customer A/C' }, alertTypeCritical);
                    return;
                }

                if (!Data.SalesLedgerID) {
                    $.notify({ message: 'Please select Sales A/C' }, alertTypeCritical);
                    return;
                }

                if (!Data.VATLedgerID) {
                    $.notify({ message: 'Please select VAT A/C' }, alertTypeCritical);
                    return;
                }

                if (!Data.COGSLedgerID) {
                    $.notify({ message: 'Please select COGS A/C' }, alertTypeCritical);
                    return;
                }

                if (!Data.StockLedgerID) {
                    $.notify({ message: 'Please select Stock A/C' }, alertTypeCritical);
                    return;
                }



                Data.InvoiceID = data.InvoiceID;
                Data.KeyField = data.KeyField;
                Data.GodownID = data.GodownID;
                Data.SideBarID = SideBarID;
                Data.InvoiceDate = data.InvoiceDate;
                Data.VoucherTypeID = 7;

                $.ajax({

                    url: globalWebServiceInventoryPath + 'getjobcard.php?action=GenerateSalesInvoice&InvoiceID='+(Data.InvoiceID),

                    type: 'post',
                    dataType: 'json',
                    data: JSON.stringify(Data),

                    beforeSend: function () {
                        (form).find(":submit").prop("disabled", "disabled");
                    },
                    success: function (data) {
                        if (data.status == "ok") {
                            $.notify({ message: data.description }, alertTypeSuccess);

                            $('#Supplier_cboSupplier').val('').trigger('change');
                            $('#cboDebitTo').val('').trigger('change');
                            $('#cboVATLedgerID').val('').trigger('change');
                            $('#cboCOGSLedger').val('').trigger('change');
                            $('#cboStockLedger').val('').trigger('change');
                            currentGeneratedRow = null;
                            refreshTable();
                        }
                        else {
                            // $.notify({ message: data.description }, alertTypeCritical);
                            // currentGeneratedRow =null;
                            $('#printModal').modal('show');
                            $('#reportPreview').attr('src', "../reportViewer.aspx?refresh=1&reportFileName=reports/SalesInvoiceReport.trdx&InvoiceID=" + data.description)

                        }
                    },

                });

                $('#saveModal').modal('hide');
            }
        });



        function ApprovedRow(sender) {
            bootbox.confirm({
                title: "Approve Row",
                message: "Do you want to Approve this row?",
                buttons: {
                    cancel: {
                        label: '<i class="fa fa-times"></i> Cancel'
                    },
                    confirm: {
                        label: '<i class="fa fa-check"></i> Confirm'
                    }
                },
                callback: function (result) {
                    if (result) {
                        currentEditRow = $(sender).parents('tr');
                        // var data = JSON.parse(currentEditRow.attr("data-Row"));

                        var row = $(tableSearch).DataTable().row(currentEditRow);//Added for DataTable
                        var data = row.data();//Added for DataTable

                        $.ajax({
                            url: globalWebServiceInventoryPath + 'getjobcard.php?action=ApproveInvoiceStatus&InvoiceStatus=' + 1 + '&InvoiceID=' + (data.InvoiceID),

                            type: 'post',
                            dataType: 'json',
                            //timeout: 2000,
                            beforeSend: function () {
                                (form).find(":submit").prop("disabled", "disabled");
                            },
                            success: function (data) {
                                if (data.status == "ok") {
                                    $.notify({ message: data.description }, alertTypeSuccess);

                                    $(currentEditRow).remove();

                                    var visibleCount = tableBody.children('tr:visible').length;
                                    if (visibleCount == 0) {
                                        $('#invoice-no-data-search').fadeIn('fast');
                                    }
                                }
                                else {
                                    $.notify({ message: data.description }, alertTypeCritical);
                                }
                            }, error: function (jqXHR, textStatus) {
                                $.notify({ message: data.description }, alertTypeCritical);
                            }, complete: function () {
                                $(form).find(":submit").prop("disabled", null);
                            }
                        });
                    }
                }
            });
        }



        function DisApproveRow(sender) {
            bootbox.confirm({
                title: "Dis-Approve Row",
                message: "Do you want to Dis-Approve this row?",
                buttons: {
                    cancel: {
                        label: '<i class="fa fa-times"></i> Cancel'
                    },
                    confirm: {
                        label: '<i class="fa fa-check"></i> Confirm'
                    }
                },
                callback: function (result) {
                    if (result) {
                        currentEditRow = $(sender).parents('tr');
                        // var data = JSON.parse(currentEditRow.attr("data-Row"));

                        var row = $(tableSearch).DataTable().row(currentEditRow);//Added for DataTable
                        var data = row.data();//Added for DataTable
                        $.ajax({

                            url: globalWebServiceInventoryPath + 'getjobcard.php?action=DisapproveInvoiceStatus&InvoiceStatus=' + 2 + '&InvoiceID=' + (data.InvoiceID),

                            type: 'post',
                            dataType: 'json',
                            //timeout: 2000,
                            beforeSend: function () {
                                (form).find(":submit").prop("disabled", "disabled");
                            },
                            success: function (data) {
                                if (data.status == "ok") {
                                    $.notify({ message: data.description }, alertTypeSuccess);

                                    $(currentEditRow).remove();
                                    var visibleCount = tableBody.children('tr:visible').length;
                                    if (visibleCount == 0) {
                                        $('#invoice-no-data-search').fadeIn('fast');
                                    }
                                }
                                else {
                                    $.notify({ message: data.description }, alertTypeCritical);
                                }
                            }, error: function (jqXHR, textStatus) {
                                $.notify({ message: data.description }, alertTypeCritical);
                            }, complete: function () {
                                $(form).find(":submit").prop("disabled", null);
                            }
                        });
                    }
                }
            });
        }

        $("#CheckIn").click(function () {
            bootbox.confirm({
                title: "Check In",
                message: "Do you want to Check In?",
                buttons: {
                    cancel: {
                        label: '<i class="fa fa-times"></i> Cancel'
                    },
                    confirm: {
                        label: '<i class="fa fa-check"></i> Confirm'
                    }
                },
                callback: function (result) {
                    if (result) {

                        $.ajax({

                            url: globalWebServiceInventoryPath + '/webservice_Inventroid.asmx/JobCardCheckIn?x=x' + '&InvoiceID=' + txtInvoiceID,

                            type: 'post',
                            dataType: 'json',
                            //timeout: 2000,
                            beforeSend: function () {
                                (form).find(":submit").prop("disabled", "disabled");
                            },
                            success: function (data) {
                                if (data.status == "ok") {
                                    $.notify({ message: "Check In Sucessfully!" }, alertTypeSuccess);
                                    $('#CheckIn').html(data.description);
                                    $('#CheckOut').prop('disabled', null)
                                    $('#CheckIn').prop('disabled', 'disabled')

                                }
                                else {
                                    $.notify({ message: data.description }, alertTypeCritical);
                                }
                            }, error: function (jqXHR, textStatus) {
                                $.notify({ message: data.description }, alertTypeCritical);
                            }, complete: function () {
                                $(form).find(":submit").prop("disabled", null);
                            }
                        });
                    }
                }
            });
        });








        $("#CheckOut").click(function () {
            bootbox.confirm({
                title: "Check Out",
                message: "Do you want to Check Out?",
                buttons: {
                    cancel: {
                        label: '<i class="fa fa-times"></i> Cancel'
                    },
                    confirm: {
                        label: '<i class="fa fa-check"></i> Confirm'
                    }
                },
                callback: function (result) {
                    if (result) {

                        $.ajax({

                            url: globalWebServiceInventoryPath + '/webservice_Inventroid.asmx/JobCardCheckOut?x=x' + '&InvoiceID=' + txtInvoiceID,

                            type: 'post',
                            dataType: 'json',
                            //timeout: 2000,
                            beforeSend: function () {
                                (form).find(":submit").prop("disabled", "disabled");
                            },
                            success: function (data) {
                                if (data.status == "ok") {
                                    $.notify({ message: "Check Out Sucessfully!" }, alertTypeSuccess);

                                    $('#CheckOut').html(data.description);
                                    $('#CheckOut').prop('disabled', 'disabled')
                                }
                                else {
                                    $.notify({ message: data.description }, alertTypeCritical);
                                }
                            }, error: function (jqXHR, textStatus) {
                                $.notify({ message: data.description }, alertTypeCritical);
                            }, complete: function () {
                                $(form).find(":submit").prop("disabled", null);
                            }
                        });
                    }
                }
            });
        });






        function openReport(sender, link, title) {



            parent.navigateTo(null, link, title, getRandomInt(5000000, 6000000));

        }
        function date_format(d) {

            d = new Date(d);

            year = format_two_digits(d.getFullYear());
            month = format_two_digits(d.getMonth() + 1);
            date = format_two_digits(d.getDate());
            return date + "-" + month + "-" + year;

        }

        function format_two_digits(n) {
            return n < 10 ? '0' + n : n;
        }


        function ClearForm(isRetrieve, IsCancel) {
            $('#PictureLocation').val('');//PICTURE_LINE
            
            $("#Advance_history_table tbody>tr").remove();
            advance_totalreceived.val('');

            tableBody.find('tr:not(#invoice-no-data)').remove();
            $('#invoice-no-data').fadeIn('fast');
            currentGeneratedRow = null;
            currentEditRow = null
            $('tr', warningtablebody).remove();
            $('tr', inspectiontablebody).remove();
            $('tr', checklisttablebody).remove();
           // $(cboCustomerType).prop('disabled', null);
            $('#Supplier_cboSupplier').prop('disabled', null);
            $('#Supplier_cboSupplier').val('96').trigger('change');

            if (!isRetrieve) {
                GetCheckList();
                GetWarningLights();
            }

            $('#CheckIn').html("Check In");
            $('#CheckOut').html("Check Out");
            $('#CheckIn').prop('disabled', 'disabled')
            $('#CheckOut').prop('disabled', 'disabled')

            txtInvoiceID = "";

            txtLastModificationTimeStamp = '';
            cboCustomerType.val('').trigger('change');
            cboVehicleBrand.val('').trigger('change');
            cboVehicleModel.val('').trigger('change');
            cboVehicleType.val('').trigger('change');
            cboVehicleSize.val('').trigger('change');
            cboVehicleColor.val('').trigger('change');
            cboManufacturerYear.val('').trigger('change');
            cboInstallersBy.val('').trigger('change');
            cboSalesPerson.val('').trigger('change');
            txtMobile.val('');
            txtCustomerName.val('');
            txtEmail.val('');
            txtTRN.val('');
            dtJobCardDate.val(date_format(new Date()));
            modal_PassCode.val('');
            txtPlateNo.val('');
            txtChassisNo.val('');
            dtPromiseDate.val('');
            txtPreparedBy.val('');
            txtKMRun.val('');
            tableBody.find('tr:not(#invoice-no-data)').remove();
            totalValue.text(0);
            totalDiscount.text(0);
            totalTax.text(0);
            grandTotal.text(0);
            txtMulkiyaNo.val('');
            txtParkingNo.val('');
            txtKeyNo.val('');
            SearchBrandID = '';
            txtNotes.summernote('code', '');
            advance_totalreceived.val('');
            txtFuel.val(1).trigger('change');
            //$('#fuel_level_percent').html("1");
            $("#RetreiveKeyField").text('');
            if (IsCancel == true) {
                $('#supplier-tabs').click();
            }
            showFirstSlide();
            clearPostForm();
            calculateTotals();
        }

        function calculateTotals() {

            var qty = 0;
            var amt = 0;
            var disc = 0;
            var vat = 0;
            var netamt = 0;


            $('tbody>tr', table).each(function () {

                var r = $(this).attr('data-Row');
                if (r) {
                    r = JSON.parse(r);
                    if (r.Flag != "D") {
                        qty += parseFloat(r.Qty);
                        amt += parseFloat(r.Amount);
                        disc += parseFloat(r.DiscountAmount);
                        vat += parseFloat(r.VATAmount);
                        netamt += parseFloat(r.NetAmount);
                    }

                }
                totalValue.text(amt)
                totalDiscount.text(disc)
                totalTax.text(vat)
                grandTotal.text(netamt)
            });
        }





        function addRow(sender) {

            var isNew = false;

            if (!currentEditRow) {
                isNew = true;
            }

            var item = $("#cboItem_Item").val();

            if (item && item.trim()) {
                item = JSON.parse(item);
            }
            else {
                $.notify({ message: 'Please select item' }, alertTypeCritical);
                return;
            }

            var table = $('#invoice');
            var tableBody = $('tbody', table);

            if (isNew) {
                if (!item) {
                    $.notify({ message: 'Please select item' }, alertTypeCritical);
                    return;
                }
                // if (!$(unit).attr('data-ID')) {
                //     $.notify({ message: 'Please select Unit' }, alertTypeCritical);
                //     return;
                // }
            }

            if (!$('#invoice_txtQty').val()) {
                $.notify({ message: 'Please enter qty' }, alertTypeCritical);
                return;
            }

            $('#invoice-no-data').fadeOut('fast');

            var o = new Object();

            if (isNew) {
                o.Item_ItemID = item.ID ? item.ID : "";
                o.Item_ItemName = item.Value ? item.Value : "";
                o.Item_Barcode = item.Barcode ? item.Barcode : "";
                o.Item_Brand = item.Brand ? item.Brand : "";
                o.Item_Level = item.MaxQtyLevel ? item.MaxQtyLevel : "";

                o.Company_ID = item.CompanyID ? item.CompanyID : "";
                o.Company_Value = item.Company ? item.Company : "";

                o.BaseType_ID = item.ProductBaseType ? item.ProductBaseType : "";
                o.BaseType_Value = item.ProductBaseType ? item.ProductBaseType : "";

                o.MainCategory_ID = item.ProductCategoryID ? item.ProductCategoryID : "";
                o.MainCategory_Value = item.ProductCategoryName ? item.ProductCategoryName : "";

                o.SubCategory_ID = item.ItemName ? item.ItemName : "";
                o.SubCategory_Value = item.ItemName ? item.ItemName : "";

                o.Brand_ID = item.Brand ? item.Brand : "";
                o.Brand_Value = item.Brand ? item.Brand : "";

                o.Level_ID = item.MaxQtyLevel ? item.MaxQtyLevel : "";
                o.Level_Value = item.MaxQtyLevel ? item.MaxQtyLevel : "";



                o.Flag = "I";
                o.TransactionID = 0;
                o.SNo = tableBody.children('tr:visible:not(#invoice-no-data)').length + 1;
            }
            else {
                o = JSON.parse($(currentEditRow).attr('data-Row'));
                if (o.TransactionID) {
                    o.Flag = "E";
                }
            }
            o.ROW_BASE_TYPE = "JOBCARD_ESTIMATION";
            o.Qty = txtQty.val();
            o.Rate = txtRate.val();
            o.Amount = txtAmount.val();
            o.Discount = txtDiscount.val();
            o.DiscountAmount = txtDiscountAmount.val();
            o.VAT = txtVAT.val();
            o.VATAmount = txtVATAmount.val();
            o.NetAmount = txtNetAmount.val();
            o.Narration = $('#invoice_txtNarration').val();

            postRow(o)
            clearPostForm();
            calculateTotals();

        }

        function postRow(o) {
            var isNew = false;

            if (!currentEditRow) {
                isNew = true;
            }

            if (!currentEditRow) {

                currentEditRow = $('<tr>\r\n' +
                    '    <td name="col_SNo"></td>\r\n' +
                    '    <td name="col_Item"></td>\r\n' +
                    '    <td name="col_Qty"></td>\r\n' +
                    '    <td name="col_Amount"></td>\r\n' +
                    '    <td name="col_Discount"></td>\r\n' +
                    '    <td name="col_VAT"></td>\r\n' +
                    '    <td name="col_NetAmount"></td>\r\n' +
                    '    <td name="col_Narration"></td>\r\n' +
                    '    <td name="col_Action" style="width: 80px;text-align: center;vertical-align: middle">\r\n' +
                    '\r\n' +
                    '        <i class="fa fa-pencil fa-lg" style="text-align: left;color: blue;cursor:pointer;" onclick="javascript:editRow(this);"></i><br/>\r\n' +
                    '        <i class="fa fa-trash-o fa-lg" style="text-align: right;color: red;cursor:pointer;" onclick="javascript:deleteRow(this);"></i>\r\n' +
                    '    \r\n' +
                    '    </td>\r\n' +
                    '\r\n' +
                    '</tr>\r\n')
            }

            currentEditRow.attr("data-Row", JSON.stringify(o));

            currentEditRow.children("td[name='col_Item']").html('<mark>' + o.Item_ItemName + '</mark>' +
                (o.Item_Barcode ? '<br/><small><span style="font-weight:bold">B:</span><span>' + o.Item_Barcode + '</span></small>' : '') +
                (o.Item_Brand ? '<br/><small><em>' + o.Item_Brand + '</em></small>' : '') +
                (o.Item_Level ? '<br/><small><span style=font-weight:bold>Level:</span><span>' + o.Item_Level + '</span></small>' : ''));


            currentEditRow.children("td[name='col_SNo']").html(o.SNo);
            currentEditRow.children("td[name='col_Qty']").html(o.Qty + '<br/>x ' + o.Rate);
            currentEditRow.children("td[name='col_Amount']").html(o.Amount);
            currentEditRow.children("td[name='col_Discount']").html(o.Discount + "%<br/>" + o.DiscountAmount);
            currentEditRow.children("td[name='col_VAT']").html(o.VAT + "%<br/>" + o.VATAmount);
            currentEditRow.children("td[name='col_NetAmount']").html(o.NetAmount);
            currentEditRow.children("td[name='col_Narration']").html(o.Narration);
            if (isNew) {
                $(currentEditRow).hide()
                    .prependTo(tableBody)
                    .fadeIn("slow");
            }
            else {
                //Do nothing
            }

            currentEditRow = null
        }

        function clearPostForm() {
            currentEditRow = null;

            $(cboItem).prop("disabled", false);
            $(cboItem).val('Item').trigger('change');

            $(cboUnit).prop("disabled", false);
            $(cboUnit).val('Unit').trigger('change');

            $("#cboItem_Company").attr('disabled', null);
            $("#cboItem_BaseType").attr('disabled', null);
            $("#cboItem_MainCategory").val(null).trigger('change').attr('disabled', null);
            $("#cboItem_SubCategory").val(null).trigger('change').attr('disabled', null);
            $("#cboItem_Brand").val(null).trigger('change').attr('disabled', null);
            $("#cboItem_ItemLevel").val(null).trigger('change').attr('disabled', null);
            $("#cboItem_Item").val(null).trigger('change').attr('disabled', null);
            $("#cboItem_BaseType").val(null).trigger('change').attr('disabled', null);
            txtAmount.val('');
            txtQty.val('');
            txtRate.val('');
            txtVAT.val('');
            txtDiscount.val('');
            txtNetAmount.val('');
            txtVATAmount.val('');
            txtDiscountAmount.val('');
            txtBatchNo.val('');
            txtPack.val('');
            txtPartNumber.val('');
            $('#invoice_txtNarration').val('')
        }







        function doCalculation() {

            txtAmount.val(txtQty.val() * txtRate.val());

            var discAmount = (txtAmount.val() / 100) * txtDiscount.val();
            var netAmt = txtAmount.val() - discAmount;
            var vatAmount = (netAmt / 100) * txtVAT.val();
            txtNetAmount.val(netAmt + vatAmount);
            txtVATAmount.val(vatAmount);
            txtDiscountAmount.val(discAmount);


        }




        function deleteRow(sender) {
            bootbox.confirm({
                title: "Delete Item",
                message: "Do you want to delete this row?",
                buttons: {
                    cancel: {
                        label: '<i class="fa fa-times"></i> Cancel'
                    },
                    confirm: {
                        label: '<i class="fa fa-check"></i> Confirm'
                    }
                },
                callback: function (result) {
                    if (result) {
                        $(sender).parents('tr').fadeOut("slow", function () {

                            $(this).fadeOut();
                            var txtTransactionID;
                            var json = JSON.parse($(this).attr('data-Row'));
                            if (!json.TransactionID || json.TransactionID == 0) {
                                // alert("to be full deleted")
                                $(json).attr('Flag', 'R');
                                $(this).remove();//Added By Saeed For Mis-Calculation After Deleting the Row - 01-22-2020
                            }
                            else {
                                $(json).attr('Flag', 'D');
                            }

                            $(this).attr("data-Row", JSON.stringify(json));
                            calculateTotals();
                        });

                        $.notify({ message: 'Row deleted' }, alertTypeInfo);
                    }
                }
            });
        }

        function editRow(sender) {
            currentEditRow = $(sender).parents('tr');
            var data = JSON.parse(currentEditRow.attr("data-Row"));


            $("#cboItem_Company").val(null).append(new Option(data.Company_Value, data.Company_ID, true, true)).attr('disabled', 'disabled');
            $("#cboItem_BaseType").val(null).append(new Option(data.BaseType_Value, data.BaseType_ID, true, true)).attr('disabled', 'disabled');
            $("#cboItem_MainCategory").val(null).append(new Option(data.MainCategory_Value, data.MainCategory_ID, true, true)).attr('disabled', 'disabled');
            $("#cboItem_SubCategory").val(null).append(new Option(data.SubCategory_Value, data.SubCategory_ID, true, true)).attr('disabled', 'disabled');
            $("#cboItem_Brand").val(null).append(new Option(data.Brand_Value, data.Brand_ID, true, true)).attr('disabled', 'disabled');
            $("#cboItem_ItemLevel").val(null).append(new Option(data.Level_Value, data.Level_ID, true, true)).attr('disabled', 'disabled');
            $("#cboItem_Item").val(null).append(new Option(data.Item_ItemName, data.Item_ItemID, true, true)).attr('disabled', 'disabled');


            txtQty.val(data.Qty);
            txtRate.val(data.Rate);
            txtAmount.val(data.Amount);
            txtDiscount.val(data.Discount);
            txtDiscountAmount.val(data.DiscountAmount);
            txtVAT.val(data.VAT);
            txtVATAmount.val(data.VATAmount);
            txtNetAmount.val(data.NetAmount);
            $('#invoice_txtNarration').val(data.Narration);
        }



        //  function toDate(dateStr) {
        //     var parts = dateStr.split("-")
        //     var d= Date(parts[2], parts[1] - 1, parts[0])



        //     const months = ["JAN", "FEB", "MAR","APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"];

        //     let current_datetime = new Date(d);

        //     return current_datetime.getDate() + "-" + months[current_datetime.getMonth()] + "-" + current_datetime.getFullYear()

        // }
        function toDate(object) {
            if ($(object).val()) {

                try {

                    const months = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"];
                    var parts = $(object).val().split("-");
                    var current_datetime = new Date(parts[2], parts[1] - 1, parts[0], 0, 0, 0, 0);
                    let formatted_date = current_datetime.getDate() + "-" + months[current_datetime.getMonth()] + "-" + current_datetime.getFullYear()
                    return formatted_date + "";

                } catch{
                    return null;
                }
            }

        }

        function ValidatePassCode(sender) {

            if (txtInvoiceID) {

                $('#PassCodeModal').modal('show');
            }

            else {

                PromptSubmit(sender);
            }
        }
        function submitInvoice(sender) {

            //Validation checks

            // if (!txtMasterValue.val())
            // {
            //     $.notify({message:'Please name'},alertTypeCritical);
            //     return;
            // }

            // var textbox;
            // if (cboTextBoxName.select2('data')[0])
            // textbox = cboTextBoxName.select2('data')[0].element;       

            // if (!$(textbox).attr('data-TextBoxName'))
            // {
            //     $.notify({message:'Please select Type'},alertTypeCritical);
            //     return;
            // }

            // var vehiclebrand;

            // if(cboVehicleBrand.select2('data')[0])
            // {
            //   vehiclebrand = cboVehicleBrand.select2('data')[0].element;
            // }

            if (!cboCustomerType.val()) {
                $.notify({ message: 'Please select customer type' }, alertTypeCritical);
                showFirstSlide();
                setTimeout(() => { $(cboCustomerType).focus(); }, 5);
                return;
            }
            if (!txtCustomerName.val()) {
                $.notify({ message: 'Please enter customer name' }, alertTypeCritical);
                showFirstSlide();
                setTimeout(() => { $(txtCustomerName).focus(); }, 5);

                return;
            }
            if (!txtMobile.val()) {
                $.notify({ message: 'Please enter customer cell number' }, alertTypeCritical);
                showFirstSlide();
                setTimeout(() => { $(txtMobile).focus(); }, 5);
                return;
            }
            if (!dtPromiseDate.val()) {
                $.notify({ message: 'Please enter promise date' }, alertTypeCritical);
                showFirstSlide();
                setTimeout(() => { $(dtPromiseDate).focus(); }, 5);
                return;
            }
            if (!dtJobCardDate.val()) {
                $.notify({ message: 'Please enter job card date' }, alertTypeCritical);
                showFirstSlide();
                setTimeout(() => { $(dtJobCardDate).focus(); }, 5);
                return;
            }

            var vehicle_type;
            if (cboVehicleType.select2('data')[0]) {
                vehicle_type = cboVehicleType.select2('data')[0].element;
                vehicle_type = $(vehicle_type).attr('data-MasterValue')

            }
            if (!vehicle_type) {
                $.notify({ message: "Please select vehicle type before proceeding" }, alertTypeCritical);
                showFirstSlide();
                setTimeout(() => { $(cboVehicleType).focus(); }, 5);
                return;
            }



            var Data = new Object();
            var customer;
            var Main=new Object()
           // var Main=[];
            if ($('#Supplier_cboSupplier').select2('data')[0]) {
                customer = $('#Supplier_cboSupplier').select2('data')[0].element;
            }
            Data.SupplierID = $(customer).attr('data-COAID');
            if (!Data.SupplierID) {
                $.notify({ message: 'Please select GL A/C' }, alertTypeCritical);
                setTimeout(() => { $('#Supplier_cboSupplier').focus(); }, 5);
                return;
            }






            Data.Mobile = txtMobile.val();
            Data.CustomerName = txtCustomerName.val();

            Data.Email = txtEmail.val();
            Data.BillDate = toDate(dtJobCardDate);
            Data.DeliveryDate = toDate(dtPromiseDate);
            Data.PlateNumber = txtPlateNo.val();
            Data.ChassisNumber = txtChassisNo.val();
            Data.ChallanNo = txtKMRun.val();

            Data.SalesManID = cboSalesPerson.val();
            Data.SalesManID2 = cboInstallersBy.val();
            Data.TRNNo = txtTRN.val();
            Data.PreparedBy = txtPreparedBy.val();
            Data.CustomerType = cboCustomerType.val();
            Data.VehicleBrand = cboVehicleBrand.val();
            // Data.VehicleBrandID = $(vehiclebrand).attr('data-MasterValueID');
            // Data.VehicleBrand   = $(vehiclebrand).attr('data-MasterValue');

            Data.VehicleModel = cboVehicleModel.val();
            Data.VehicleType = cboVehicleType.val();
            Data.VehicleSize = cboVehicleSize.val();
            Data.VehicleColor = cboVehicleColor.val();
            Data.VehicleYear = cboManufacturerYear.val();
            Data.Notes = txtNotes.val();
            Data.LastModificationTimeStamp = txtLastModificationTimeStamp;
            Data.FuelLevel = txtFuel.val();
            Data.SideBarID = SideBarID;
            Data.GodownID = CurrentCompanyID;
            // Data.SupplierID = txtCustomerID;
           // alert(txtInvoiceID);
            Data.InvoiceType = 5;
            Data.InvoiceID = txtInvoiceID;
            Data.TotalAmt = totalValue.text();
            Data.TotalDisountAmount = totalDiscount.text();
            Data.TotalTaxAmount = totalTax.text();
            Data.NetAmount = grandTotal.text();
            Data.InculsiveAmount = grandTotal.text();
            Data.PassCode = modal_PassCode.val();

            Data.MulkiyaNo = txtMulkiyaNo.val();
            Data.ParkingNo = txtParkingNo.val();
            Data.KeyNo = txtKeyNo.val();
            
            Data.PictureLocation=$('#PictureLocation').val();//PICTURE_LINE

            var warningdetail = [];
            var checklistdetail = [];
            var inspectiondetail = [];
         //   Main.checklistdetail=checklistdetail ;
            //Data.Main=Main;
            var detail = [];

        //    Data.detail= detail;

/*            Data.checklistdetail = checklistdetail 
           // detail.unshift(checklistdetail);
            Data.warningdetail = warningdetail;
            Data.inspectiondetail = inspectiondetail;
*//*            Data.checklistdetail = checklistdetail;
            Data.warningdetail = warningdetail;
            Data.inspectiondetail = inspectiondetail;
*/
            warningtablebody.children('tr').each(function () {
                var a = JSON.parse($(this).attr('data-Row'));
                var o = new Object();
                o.MasterValueID = a.MasterValueID;
                var checkbox = $('input[name="warninglights' + o.MasterValueID + '"]:checked', this);

                if (!checkbox)
                    o.Value = 0;
                else
                    o.Value = $(checkbox).val();

                warningdetail.push(o);
            });

            checklisttablebody.children('tr').each(function () {
                var a = JSON.parse($(this).attr('data-Row'));
                var checkbox = $('input[name="col_MasterValueID' + a.MasterValueID + '"]:checked', this);
                var o = new Object();
                o.MasterValueID = a.MasterValueID;

                if (!checkbox)
                    o.Value = 0;
                else
                    o.Value = $(checkbox).val();

                checklistdetail.push(o);
            });


            inspectiontablebody.children('tr').each(function () {

                var j = JSON.parse($(this).attr("data-Row"));
                // o.RowNum = data[i].row_num ? data[i].row_num : "";
                // o.MasterValue = data[i].MasterValue ? data[i].MasterValue : "";
                // o.MasterValueID = data[i].MasterValueID;
                // o.Description = data[i].Description;
                // o.JobDetailID = data[i].JobDetailID ? data[i].JobDetailID : 0;

                var o = new Object();

                o.MasterValue = j.MasterValue;
                o.Value = $('input[type="text"]', this).val();
                o.JobDetailID = j.JobDetailID;
                o.PictureLocation = j.PictureLocation; //09FEB
                inspectiondetail.push(o);
            });


            tableBody.children('tr').each(function () {
                if ($(this).attr('data-Row'))
                    detail.push(JSON.parse($(this).attr('data-Row')));
            });

            //console.log('MODEL ID' + cboVehicleModel.val())
console.log('inspect:'+JSON.stringify(inspectiondetail));
/*var myarray=new Object();
myarray.Data=Data;
myarray.checklistdetail=checklistdetail;
var Mydata=JSON.stringify(myarray);*/
            $.ajax({
                url: globalWebServiceInventoryPath + 'getjobcard.php?action=jobcardInsert',
                type: 'post',
                dataType: 'json',
                timeout: 2000,
                data: 'data='+JSON.stringify(Data)+'&detail='+JSON.stringify(detail)+'&checklistdetail='+JSON.stringify(checklistdetail)+'&warningdetail='+JSON.stringify(warningdetail)+'&inspectiondetail='+JSON.stringify(inspectiondetail),
                beforeSend: function () {
                    (form).find(":submit").prop("disabled", "disabled");
                },
                success: function (data) {

                    if (data.status == "ok") {

                        $.notify({ message: data.description }, alertTypeSuccess);
                        $('#PassCodeModal').modal('hide');
                        $(form).trigger('reset');
                        ClearForm();

                    } else {

                        $.notify({ message: data.description }, alertTypeCritical);
                        if (data.description != "Invalid PassCode!") {
                            //setTimeout(function () { $('#PassCodeModal').modal('show'); }, 10);
                            $('#PassCodeModal').modal('hide');
                        }
                    }
                }, error: function (jqXHR, textStatus) {
                    $.notify({ message: "Error, please check your internet connection status!" }, alertTypeCritical);
                }, complete: function () {
                    $(form).find(":submit").prop("disabled", null);
                }
            });

        }



        function PromptSubmit(sender) {
            event.preventDefault();
            bootbox.confirm({
                title: "Submit",
                message: "Do you want to Submit ths document?",
                buttons: {
                    cancel: {
                        label: '<i class="fa fa-times"></i> Cancel'
                    },
                    confirm: {
                        label: '<i class="fa fa-check"></i> Confirm'
                    }
                },
                callback: function (result) {
                    if (result) {

                        submitInvoice(sender);

                    }
                }
            });
        }

        function resetInvoice(sender) {
            event.preventDefault();

            bootbox.confirm({
                title: "Reset Invoice",
                message: "Do you want to Reset ths document?",
                buttons: {
                    cancel: {
                        label: '<i class="fa fa-times"></i> Cancel'
                    },
                    confirm: {
                        label: '<i class="fa fa-check"></i> Confirm'
                    }
                },
                callback: function (result) {
                    if (result) {
                        ClearForm();
                        $.notify({ message: 'Form cleared' }, alertTypeInfo);
                    }
                }
            });

        }




        function isEmpty(value) {
            var isEmptyObject = function (a) {
                if (typeof a.length === 'undefined') { // it's an Object, not an Array
                    var hasNonempty = Object.keys(a).some(function nonEmpty(element) {
                        return !isEmpty(a[element]);
                    });
                    return hasNonempty ? false : isEmptyObject(Object.keys(a));
                }

                return !a.some(function nonEmpty(element) { // check if array is really not empty as JS thinks
                    return !isEmpty(element); // at least one element should be non-empty
                });
            };
            return (
                value == false
                || typeof value === 'undefined'
                || value == null
                || (typeof value === 'object' && isEmptyObject(value))
            );
        }

        function calculatePrice(index) {
            var price = parseFloat($("#price" + index).val());
            var discount = parseFloat($("#discount" + index).val());
            var tax = parseFloat($("#tax" + index).val());
            var quantity = parseFloat($("#quantity" + index).val());
            price = parseFloat(price * quantity);
            discount = !isEmpty(discount) ? discount : parseFloat(0);
            quantity = !isEmpty(quantity) ? quantity : parseFloat(1);
            price = !isEmpty(price) ? price : parseFloat(0);
            var discount = parseFloat((discount / 100) * price);
            var totalamount = parseFloat(price - parseFloat(discount));
            var totalTax = parseFloat((tax / 100) * totalamount);
            var totalTaxamount = parseFloat(totalamount + parseFloat((tax / 100) * totalamount));
            $("#total_price_" + index).val(price.toFixed(2));
            $("#discount_value" + index).val(discount.toFixed(2));
            $("#subtotal" + index).val(totalamount.toFixed(2));
            $("#tax_amount" + index).val(totalTax.toFixed(2));
            $("#tax_amountShow" + index).html(totalTax.toFixed(2));
            $("#total" + index).val(totalTaxamount.toFixed(2));

            var total_price = 0;
            var totalPay = 0;
            var totalDis = 0;
            var totalTax = 0;
            var subtotal = 0;
            var totalQty = 0;
            $(".totalPay").each(function () {
                if (!isNaN(this.value) && this.value.length != 0) {
                    totalPay += parseFloat($(this).val());
                }
            });
            $(".totalDis").each(function () {
                if (!isNaN(this.value) && this.value.length != 0) {
                    totalDis += parseFloat($(this).val());
                }
            });
            $(".totalTax").each(function () {
                if (!isNaN(this.value) && this.value.length != 0) {
                    totalTax += parseFloat($(this).val());
                }
            });
            $(".subtotal").each(function () {
                if (!isNaN(this.value) && this.value.length != 0) {
                    subtotal += parseFloat($(this).val());
                }
            });
            $(".totalQty").each(function () {
                if (!isNaN(this.value) && this.value.length != 0) {
                    totalQty += parseFloat($(this).val());
                }
            });
            $(".total_price").each(function () {
                if (!isNaN(this.value) && this.value.length != 0) {
                    total_price += parseFloat($(this).val());
                }
            });

            $("#TotalPrice").val(total_price.toFixed(2));
            $("#TotalValue").val(subtotal.toFixed(2));
            $("#TotalDiscount").val(totalDis.toFixed(2));
            $("#TotalTax").val(totalTax.toFixed(2));

            $("#TotalPayable").val(totalPay.toFixed(2));
            $("#TotalQty").val(totalQty);

            $(".TotalValueHT").html(total_price.toFixed(2));
            $(".TotalDisHT").html(totalDis.toFixed(2));
            $(".TotalTxHT").html(totalTax.toFixed(2));
            $(".TotalPayHT").html(totalPay.toFixed(2));

        }

        function calculateSum() {
            var totalPay = 0;
            var totalDis = 0;
            var totalTax = 0;
            var subtotal = 0;
            $(".totalPay").each(function () {
                if (!isNaN(this.value) && this.value.length != 0) {
                    totalPay += parseFloat(this.value);
                }
            });
            $(".totalDis").each(function () {
                if (!isNaN(this.value) && this.value.length != 0) {
                    totalDis += parseFloat($(this).val());
                }
            });
            $(".totalTax").each(function () {
                if (!isNaN(this.value) && this.value.length != 0) {
                    totalTax += parseFloat($(this).val());
                }
            });
            $(".subtotal").each(function () {
                if (!isNaN(this.value) && this.value.length != 0) {
                    subtotal += parseFloat($(this).val());
                }
            });
            $("#TotalValue").val(subtotal.toFixed(2));
            $("#TotalDiscount").val(totalDis.toFixed(2));
            $("#TotalTax").val(totalTax.toFixed(2));
            $("#TotalPay").val(totalPay.toFixed(2));
            $("#TotalPayable").val(totalPay.toFixed(2));
            $(".TotalValueHT").html(subtotal.toFixed(2));
            $(".TotalDisHT").html(totalDis.toFixed(2));
            $(".TotalTxHT").html(totalTax.toFixed(2));
            $(".TotalPayHT").html(totalPay.toFixed(2));
        }
        $(document).ready(function () {


            dtJobCardDate.val(date_format(new Date()));

            // txtMobile.on("keyup", function (event) {


            // });




            // $('#CheckIn').css('display','none')
            // $('#CheckOut').css('display','none')
            $('#CheckIn').html("Check In");
            $('#CheckOut').html("Check Out");
            $('#CheckIn').prop('disabled', 'disabled')
            $('#CheckOut').prop('disabled', 'disabled')



            txtMobile.change(function () {


            }).keyup(function () {

            }).keydown(function (e) {

                if (e.which == 13) {

                    e.preventDefault();
                    $('#CustomerModal').modal('show');

                }

            });








            $("#TotalPay").on("keyup", function (event) {
                var TotalPayable = $("#TotalPayable").val();
                var totalPay = $("#TotalPay").val().trim();
                if (parseFloat(totalPay) > parseFloat(TotalPayable)) {
                    alert('The amount should be less than equal to of total amount');
                    $("#TotalPay").val(TotalPayable);
                    $('#otherdiscount').val(0);
                    return false;
                } else {
                    var otherdiscount = parseFloat(TotalPayable) - parseFloat(totalPay);
                    $('#otherdiscount').val(otherdiscount.toFixed(2));
                }
            });

            $(".updateservice").click(function () {
                $("input[type='checkbox']:checked").each(function () {
                    var index = $(this).attr('index');
                    $('.Rdisabled' + index).removeAttr("disabled", true);
                    calculatePrice(index);
                });
            });

            $(".check_service").click(function () {
                var index = $(this).attr('index');
                if ($(this).is(":checked")) {
                    $('#tax' + index).val('5');
                    $('.Rdisabled' + index).removeAttr("disabled", true);
                    calculatePrice(index);
                } else {
                    $("#total" + index).val(0);
                    $("#subtotal" + index).val(0);
                    $('#tax' + index).val(0);
                    $('#tax_amount' + index).val(0);
                    $('.Rdisabled' + index).attr("disabled", true);
                    calculateSum(index);
                }
            });

            $('#makePayments').on("submit", function (e) {
                e.preventDefault();
                var data = $(this).serialize();
                //alert(window.location.href);return false;
                $.ajax({
                    url: "http://erp.yesapplication.net/jobcard/makePayments",
                    type: 'POST',
                    data: data,
                    dataType: 'json',
                    beforeSend: function () {
                        $('.saveaction2').html('Please wait..');
                        $('.saveaction2').attr('disabled', true);
                    },
                    success: function (result) {
                        if (result.success) {
                            alert(result.message);
                            $('.saveaction2').removeAttr('disabled', true);
                            //$('#myModalsendMail').modal('hide');
                            window.location = window.location.href;
                        } else {
                            $('.saveaction2').removeAttr('disabled', true);
                            $('.saveaction2').html('Submit');
                            alert(result.message);
                        }
                    },
                    error: function () {
                        $('.saveaction2').removeAttr('disabled', true);
                        $('.saveaction2').html('Submit');
                        alert('oops response error');
                    }

                });
            });




            $(tableCustomer).dataTable({
                "bSortCellsTop": true,
                "processing": false,
                "sDom": '<"top"flp>rt<"bottom"i><"clear">',
                "responsive": false,
                "paging": true,
                "lengthMenu": [[5, 10, 20, 30, 500000], [5, 10, 20, 30, "All"]],
                "pageLength": 5,
                "searching": false,
                "serverSide": false,
                "sAjaxDataProp": "",
                "order": [[1]],
                "bAutoWidth": false,


                "ajax": {


                    url: globalWebServiceInventoryPath + 'getjobcard.php?action=getCustomerSearch&InvoiceType=5',
                    "data": function (d) {
                        var Data = new Object();
                        $.each(d.order, function (key, value) {
                            this.column = d.columns[this.column].data;
                        });
                        if (d.order)
                            Data.sorting = JSON.stringify(d.order);
                        try { Data.current_page = (d.start / d.length) + 1; } catch (e) { Data.current_page = 1; }
                        Data.records_to_return = d.length;


                        if ((Modal_Search_Customer).val()) $(Data).attr(Modal_Search_Customer.attr("name"), Modal_Search_Customer.val())
                        if ((Search_MobileNumber).val()) $(Data).attr(Search_MobileNumber.attr("name"), Search_MobileNumber.val())
                        if ((Search_Email).val()) $(Data).attr(Search_Email.attr("name"), Search_Email.val())
                        if ((cboCustomerType).val()) $(Data).attr(cboCustomerType.attr("name"), cboCustomerType.val())

                        Data.draw = d.draw;

                        return Data;
                    }
                },
                "columns": [
                    { "data": "row_num", sWidth: "5%" },//S#
                    { "data": "CustomerName", sWidth: "5%" },//CustomerName
                    { "data": "MobileNumber", sWidth: "5%" },//Mobile Number
                    { "data": "Email", sWidth: "5%" },//Mobile Number
                    { "data": function (x) { return (x.GLCode ? x.GLCode : 'N/A') + "<br/><small>" + (x.COAName ? x.COAName : 'N/A') + '</small>' }, sWidth: "20%" },//CustomerType

                    //{ "data": function (x) { return x.CustomerName + "<br/><small>" + (x.MobileNumber ? x.MobileNumber : 'N/A') + '</small><i class="fa fa-angle-double-right txt-primary m-r-5 m-l-5"></i><small>' + (x.Email ? x.Email : 'N/A') + "</small> " }, sWidth: "35%" },//CustomerName+MobileNumber+Email
                    //{ "data": function (x) { return (x.PlateNumber ? x.PlateNumber : 'NA') + "<br/><small>" + (x.ChassisNumber ? x.ChassisNumber : 'N/A') + '</small>' }, sWidth: "20%" },//Plate+ChasisNumber
                    //{ "data": function (x) { return (x.VehicleBrand ? x.VehicleBrand : 'N/A') + " <br/><small>" + (x.VehicleType ? x.VehicleType : 'N/A') + '</small><i class="fa fa-angle-double-right txt-primary m-r-5 m-l-5"></i><small>' + (x.VehicleModel ? x.VehicleModel : 'N/A') + '</small><i class="fa fa-angle-double-right txt-primary m-r-5 m-l-5"></i><small>' + (x.VehicleColor ? x.VehicleColor : 'N/A') + '</small><i class="fa fa-angle-double-right txt-primary m-r-5 m-l-5"></i><small>' + (x.VehicleYear ? x.VehicleYear : 'N/A') + "</small> " }, sWidth: "20%" },//Vehicle
                    //{ "data": function (x) { return (x.CustomerType ? x.CustomerType : 'N/A') + "<br/><small>" + (x.TRNNo ? x.TRNNo : 'N/A') + '</small>' }, sWidth: "20%" },//CustomerType
                ],


                "columnDefs": [
                    {
                        "targets": [0],
                        "sortable": false,
                        "className": "dt-center",

                    },
                ],

            });





            $(tableChassis).dataTable({
                "bSortCellsTop": true,
                "processing": false,
                "sDom": '<"top"flp>rt<"bottom"i><"clear">',
                "responsive": false,
                "paging": true,
                "lengthMenu": [[5, 10, 20, 30, 500000], [5, 10, 20, 30, "All"]],
                "pageLength": 5,
                "searching": true,
                "serverSide": false,
                "sAjaxDataProp": "",
                "order": [[1]],
                "bAutoWidth": false,


                "ajax": {

                    url: globalWebServiceInventoryPath + 'getjobcard.php?action=getChasisdata&InvoiceType=5',
                    "data": function (d) {
                        var Data = new Object();
                        $.each(d.order, function (key, value) {
                            this.column = d.columns[this.column].data;
                        });
                        if (d.order)
                            Data.sorting = JSON.stringify(d.order);
                        try { Data.current_page = (d.start / d.length) + 1; } catch (e) { Data.current_page = 1; }
                        Data.records_to_return = d.length;



                        if ((Search_Chassis_PlateNumber).val()) $(Data).attr(Search_Chassis_PlateNumber.attr("name"), Search_Chassis_PlateNumber.val())
                        if ((Search_Chassis_ChassisNumber).val()) $(Data).attr(Search_Chassis_ChassisNumber.attr("name"), Search_Chassis_ChassisNumber.val())
                        if ((Search_Chassis_VehicleType).val()) $(Data).attr(Search_Chassis_VehicleType.attr("name"), Search_Chassis_VehicleType.val())
                        // if ((Search_CustomerType).val()) $(Data).attr(Search_CustomerType.attr("name"), Search_CustomerType.val())
                        if ((txtMobile).val()) $(Data.MobileNumber).attr(txtMobile.attr("name"), txtMobile.val())
                        Data.MobileNumber = $(txtMobile).val();
                        Data.draw = d.draw;

                        return Data;
                    }
                },
                "columns": [
                    { "data": "row_num", sWidth: "5%" },//S#
                    { "data": function (x) { return (x.ChassisNumber ? x.ChassisNumber : 'NA') }, sWidth: "20%" },//ChasisNumber
                    { "data": function (x) { return (x.PlateNumber ? x.PlateNumber : 'NA') }, sWidth: "20%" },//Plate#
                    { "data": function (x) { return (x.VehicleBrand ? x.VehicleBrand : 'N/A') + " <br/><small>" + (x.VehicleType ? x.VehicleType : 'N/A') + '</small><i class="fa fa-angle-double-right txt-primary m-r-5 m-l-5"></i><small>' + (x.VehicleModel ? x.VehicleModel : 'N/A') + '</small><i class="fa fa-angle-double-right txt-primary m-r-5 m-l-5"></i><small>' + (x.VehicleColor ? x.VehicleColor : 'N/A') + '</small><i class="fa fa-angle-double-right txt-primary m-r-5 m-l-5"></i><small>' + (x.VehicleYear ? x.VehicleYear : 'N/A') + "</small> " }, sWidth: "20%" },//Vehicle

                ],


                "columnDefs": [
                    {
                        "targets": [0],
                        "sortable": false,
                        "className": "dt-center",

                    },
                ],

            });





            $('#chassis-search tbody').on('click', 'tr', function () {

                var table = $('#chassis-search').DataTable();

                var data = table.row(this).data();
                $('#ChassisModal').modal('toggle');

                txtChassisNo.val(data.ChassisNumber);
                txtPlateNo.val(data.PlateNumber);
                txtTRN.val(data.TRNNo);
                cboVehicleBrand.val(data.VehicleBrandID).trigger('change');

                if (!data.VehicleModelID || data.VehicleModelID == null) {
                    cboVehicleModel.val('').trigger('change');
                }
                else {
                    var opt = new Option(data.VehicleModel, data.VehicleModelID, true, true)
                    cboVehicleModel.append(opt);
                    cboVehicleModel.val(data.VehicleModelID).trigger('change');
                }
                cboVehicleType.val(data.VehicleTypeID).trigger('change');
                cboManufacturerYear.val(data.VehicleYearID).trigger('change');
                cboVehicleColor.val(data.VehicleColorID).trigger('change');
                //cboCustomerType.val(data.CustomerTypeID).trigger('change');

                Search_Chassis_PlateNumber.val('');
                Search_Chassis_ChassisNumber.val('');
                Search_Chassis_VehicleType.val('');

            });









            $('#customer-search tbody').on('click', 'tr', function () {

                var table = $('#customer-search').DataTable();

                var data = table.row(this).data();
                $('#CustomerModal').modal('toggle');

                console.log(data);
                txtMobile.val(data.MobileNumber);
                txtCustomerName.val(data.CustomerName);
                txtEmail.val(data.Email);

                $('#Supplier_cboSupplier').val(data.CustomerID).trigger('change');
                // txtChassisNo.val(data.ChassisNumber);
                // txtPlateNo.val(data.PlateNumber);
                // txtTRN.val(data.TRNNo);
                // cboVehicleBrand.val(data.VehicleBrandID).trigger('change');

                // if (!data.VehicleModelID || data.VehicleModelID == null) {
                //     cboVehicleModel.val('').trigger('change');
                // }
                // else {
                //     var opt = new Option(data.VehicleModel, data.VehicleModelID, true, true)
                //     cboVehicleModel.append(opt);
                //     cboVehicleModel.val(data.VehicleModelID).trigger('change');
                // }
                // cboVehicleType.val(data.VehicleTypeID).trigger('change');
                // cboManufacturerYear.val(data.VehicleYearID).trigger('change');
                // cboVehicleColor.val(data.VehicleColorID).trigger('change');
                // cboCustomerType.val(data.CustomerTypeID).trigger('change');
                Search_Customer.val('');
                Search_MobileNumber.val('');
                Search_Email.val('');
                Search_PlateNumber.val('');
                Search_ChassisNumber.val('');
                Search_VehicleType.val('');
                Search_CustomerType.val('');
              //  $(cboCustomerType).prop('disabled', 'disabled');
              //  $('#Supplier_cboSupplier').prop('disabled', 'disabled');
            });




            // $('area').on('click', function () {
            //     var title = $(this).attr('title');
            //     $('#scrac').append("<tr><td>" + title + "<input type='hidden' name='insp[]' value='" + title + "'></td><td><input class='form-control' type='text' name='remark[]' placeholder='Explain problem' ></td><td><input type='file' class='form-control' name='image[]' placeholder='Imgages'  ></td><td><a href='javascript:void(0);' class='remove' title='Remove'><i class='fa fa-trash-o'></i></a></td></tr>");
            // });

            $('area').on('click', function () {

                var title = $(this).attr('title');
                var id = $(this).attr('id');

                var o = new Object()
                o.MasterValue = title;
                o.MasterValueID = id;

                //                var ro = $("<tr><td><a href='javascript:void(0);' class='remove' title='Remove'><i class='fa fa-trash-o'></i></a><small>" + title + "</small><input type='hidden' name='insp[]' value='" + title + "'><br/><input class='form-control'  type='text' name='remark[]' placeholder='Explain problem' ></td><td> <small>Snap</small><br/> <input type='file' class='form-control' name='image[]' placeholder='Imgages'  ></td></tr>");
                var ro = $("<tr><td><a href='javascript:void(0);' class='remove' title='Remove'><i class='fa fa-trash-o'></i></a><small>" + title + "</small><input type='hidden' name='insp[]' value='" + title + "'><br/><input class='form-control'  type='text' name='remark[]' placeholder='Explain problem' ></td><td> <small>Snap</small><br/> <label for='file-upload' class='custom-file-upload snap'><i class='fa fa-camera'></i></label></td></tr>");
                //09FEB


                //
                $(ro).attr('data-Row', JSON.stringify(o));

                $('#scrac').append(ro);
            });

            $(".RowsGroup").on('click', '.remove', function () {
                $(this).parent().parent().remove();
            });

            //09FEB
            $(".RowsGroup").on('click', '.snap', function () {
                var  row = $(this).closest('tr');

                var json = $(row).attr('data-Row');
                var existingPicture = "";
                if (json)
                {
                    json = JSON.parse(json);
                    existingPicture = json.PictureLocation
                }
                console.log('json here: '+json.MasterValue);
                window.parent.modal_BrowsePicture(existingPicture,0 /*0 FOR SINGLE: 1 FOR MULTIPLE*/,function(data)
                {
                    console.log('picture:'+data);
                    json.PictureLocation = data;
                    $(row).attr('data-Row',JSON.stringify(json))
                },json.MasterValue)


            });

            // //##Temp
            // $('#basic-tab').click();
            // setTimeout(function () { showThirdSlide() }, 10);



        });

        function showFirstSlide() {
            $("#secondSlide").hide();
            $("#thirdSlide").hide();
            $("#firstSlide").show();


            //toSvg("Map")
        }
        function showSecondSlide() {

         /*   var vehicletype;
            if (cboVehicleType.select2('data')[0]) {
                vehicletype = cboVehicleType.select2('data')[0].element;
                vehicletype = $(vehicletype).attr('data-MasterValue')

            }
            if (!vehicletype) {
                $.notify({ message: "Please select vehicle type before proceeding" }, alertTypeCritical);
                setTimeout(() => { $(cboVehicleType).focus(); }, 5);
                return;
            }


            if (!txtMobile.val()) {
                $.notify({ message: "Please enter mobile number" }, alertTypeCritical);
                setTimeout(() => { $(txtMobile.val()).focus(); }, 5);
                return;
            }

            if (!txtCustomerName.val()) {
                $.notify({ message: "Please enter customer name" }, alertTypeCritical);
                setTimeout(() => { $(txtCustomerName.val()).focus(); }, 5);
                return;
            }


            if (!txtPlateNo.val()) {
                $.notify({ message: "Please enter plate number" }, alertTypeCritical);
                setTimeout(() => { $(txtPlateNo.val()).focus(); }, 5);
                return;
            }
            if (!txtChassisNo.val()) {
                $.notify({ message: "Please enter chassis number" }, alertTypeCritical);
                setTimeout(() => { $(txtChassisNo.val()).focus(); }, 5);
                return;
            }





            var vehiclebrand;
            if (cboVehicleBrand.select2('data')[0]) {
                vehiclebrand = cboVehicleBrand.select2('data')[0].element;
                vehiclebrand = $(vehiclebrand).attr('data-MasterValue')

            }
            if (!vehiclebrand) {
                $.notify({ message: "Please select vehicle brand before proceeding" }, alertTypeCritical);
                setTimeout(() => { $(cboVehicleBrand).focus(); }, 5);
                return;
            }


            var vehiclecolor;
            if (cboVehicleColor.select2('data')[0]) {
                vehiclecolor = cboVehicleColor.select2('data')[0].element;
                vehiclecolor = $(vehiclecolor).attr('data-MasterValue')

            }
            if (!vehiclecolor) {
                $.notify({ message: "Please select vehicle color before proceeding" }, alertTypeCritical);
                setTimeout(() => { $(cboVehicleColor).focus(); }, 5);
                return;
            }



            var vehicleyear;
            if (cboManufacturerYear.select2('data')[0]) {
                vehicleyear = cboManufacturerYear.select2('data')[0].element;
                vehicleyear = $(vehicleyear).attr('data-MasterValue')

            }
            if (!vehicleyear) {
                $.notify({ message: "Please select vehicle manfacture year before proceeding" }, alertTypeCritical);
                setTimeout(() => { $(cboManufacturerYear).focus(); }, 5);
                return;
            }




            var customertype;
            if (cboCustomerType.select2('data')[0]) {
                customertype = cboCustomerType.select2('data')[0].element;
                customertype = $(customertype).attr('data-MasterValue')

            }
            if (!customertype) {
                $.notify({ message: "Please select customer type before proceeding" }, alertTypeCritical);
                setTimeout(() => { $(cboCustomerType).focus(); }, 5);
                return;
            }

*/
            $("#firstSlide").hide();
            // $("#secondSlide").show(function(){
            //     $('#carImage').rwdImageMaps();
            // });


            $("#secondSlide").show()

            setTimeout(() => {
                $('#carImage').rwdImageMaps();
            }, 100);

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


        }
        function showThirdSlide() {
            $("#firstSlide").hide();
            $("#secondSlide").hide();
            $("#thirdSlide").show();


        }


        $('#CustomerModal').on('shown.bs.modal', function (e) {
            //alert("I want this to appear after the modal has opened!");
            setTimeout(function () { $('#Search_MobileNumber').focus(); }, 20);
            Search_MobileNumber.val(txtMobile.val());
        })

        function showCustomer() {


            var type;
            if (cboCustomerType.select2('data')[0]) {

                type = cboCustomerType.select2('data')[0].element;
            }
            var MasterValueID = $(type).attr('data-MasterValueID');

            if (!MasterValueID) {
                $.notify({ message: 'Please select Customer Type First' }, alertTypeCritical);
                $(cboCustomerType).focus();
                return;

            }


            $('#CustomerModal').modal('show');
            refreshTableCustomer();
        }




        function showChassis() {


            var type;
            if (cboCustomerType.select2('data')[0]) {

                type = cboCustomerType.select2('data')[0].element;
            }
            var MasterValueID = $(type).attr('data-MasterValueID');

            if (!MasterValueID) {
                $.notify({ message: 'Please select Customer Type First' }, alertTypeCritical);
                $(cboCustomerType).focus();
                return;

            }



            if (!txtMobile.val()) {
                $.notify({ message: 'Please enter mobile #' }, alertTypeCritical);
                $(txtMobile).focus();
                return;

            }


            $('#ChassisModal').modal('show');
            refreshTableChassis();
        }




        function toSvg(ad) {
            var m, a, t, s, b, c, cc;
            m = document.getElementById(ad);
            a = m.getElementsByTagName('area');
            t = '<svg class="uzay">';

            // alert(a.length);
            //alert(a[0].getAttribute('shape'));
            for (var i = 0; i < a.length; i++) {
                s = a[i].getAttribute('shape');
                c = a[i].getAttribute('coords');
                b = s + i;
                if (s == 'poly') {
                    t += '<polyline points="' + c + '" fill="red" id="' + b + '" onclick="renkli(this.id)"/>';
                }
                if (s == 'circle') {
                    cc = c.split(',');
                    t += '<circle cx="' + cc[0] + '"  cy="' + cc[1] + '"  r="' + cc[2] + '" class="circle"  id="' + b + '" onclick="renkli(this.id)"/>';
                }
                if (s == 'rect') {
                    cc = c.split(',');
                    t += '<rect x="' + cc[0] + '"  y="' + cc[1] + '"  width="' + (cc[2] - cc[0]) + '" height="' + (cc[3] - cc[1]) + '" class="rect"  id="' + b + '" onclick="renkli(this.id)"/>';
                }
            }

            t += '</svg>';

            //var el= document.getElementById('mekan');

            //alert(el.innerHTML);
        }


    </script>
