var ebillsetting = Number($("#ebillsetting").val());
var ebillsettingClass = '';
if (ebillsetting != 1) {
    ebillsettingClass = 'hidden';
}
$(".ImageNew ,.m_productNew").on("change", function () {
    var thisis = $(this);
    setTimeout(function () {
        var pro_id = thisis.attr('data-id');
        // console.log(thisis.val());
        // console.log(thisis.attr('id'));

        $.ajax({
            type: "POST",
            url: 'productControllerAjax.php?do=getImageDesc',
            data: {pro_id: pro_id},
            cache: false,
            success: function (data) {
                var re = JSON.parse(data)
                var bt = document.getElementById('rev_' + re.productId);
                if ((re.productDescription == "" || re.productDescription == null)
                        || (re.logo == "" || re.logo == null || re.logo == ".")) {
                    bt.disabled = true;
                } else {
                    bt.disabled = false;
                }
            }
        });

    }, 100);


});

$("#barcodeInTax1").select2({
    placeholder: "اختر",
    multiple: false,
    ajax: {
        url: "eBillRequests.php?do=barcodeInTax",
        dataType: 'json',
        data: function (term, page) {
             var itr = $(this).attr('data-itr');
             var TypeOfBarcodeInTax =  $('input[name="TypeOfBarcodeInTax'+itr+'"]:checked').val();
            return {
                term: term, //search term
                TypeOfBarcodeInTax: TypeOfBarcodeInTax,
            };
        },
        results: function (data) {
            return {results: data};
        }
    },
    formatResult: formatResultFatma,
    initSelection: function (element, callback) {
        var item = element.val().split(':');
        var data = {id: item[0], text: item[1]};
        callback(data);
    }
});



if ($('#Reviewed').length > 0) {
    var tablereviewedClients = $('#Reviewed');
    var tablereviewed = tablereviewedClients.DataTable({
        "processing": true,
        "stateSave": true,
        "serverSide": true,
        "ajax": {
            url: "productControllerAjax.php?do=getDatabyajax", type: 'POST',
            "data": {
                "reviewType": function () {
                    return 1;
                },
                "store": function () {
                    return $('#store').val()
                },
                "level": function () {
                    return $('#level').val()
                },
                "productCatId": function () {
                    var level = $('#level').val()
                    return $('#productCatId' + level).val()
                },
            }
        }, //  server side processing
        "fnRowCallback": function (nRow, aData, iDisplayIndex, iDisplayIndexFull) {
            if (aData[0].includes("danger"))//not deleted
            {
                $('td', nRow).css('background-color', '#F2DEDE');
            } else if (aData[0].includes("dark")) {
                $('td', nRow).css('background-color', '#9E9E9E');
            }

        },
        dom: 'Bfrtip',
        buttons: [//'csv', 'pdf'
            {
                extend: "print",
                className: "btn dark btn-outline",
                text: "طباعه<i class='fa fa-print'></i>",
                exportOptions: {
                    //columns: '.show-print'
                    columns: ':visible'
                },
                customize: function (win) {
                    $(win.document.body).find('table')
                            //.addClass('compact')
                            .css('direction', 'rtl');
                }
            }, {
                extend: "copy",
                className: "btn red btn-outline",
                text: "نسخ",
                exportOptions: {
                    //columns: '.show-print'
                    columns: ':visible'
                }
            }, {
                extend: "excel",
                className: "btn yellow btn-outline ",
                text: "اكسل",
                exportOptions: {
                    //columns: '.show-print'
                    columns: ':visible'
                }
            }, {
                extend: "colvis",
                className: "btn dark btn-outline",
                text: "المكونات"
            }
        ], "bStateSave": true,
        "language": {
            "aria": {
                "sortAscending": ": Used to order Ascending",
                "sortDescending": ": Used to order Descending"
            },
            "emptyTable": "لا يوجد بيانات",
            "info": "عرض من  _START_ إلى  _END_  - عدد منتجات البحث _TOTAL_",
            "infoEmpty": "لا يوجد بيانات",
            "infoFiltered": "(تنقيه  من عدد المنتجات كلى _MAX_)",
            "lengthMenu": " _MENU_ عنصر",
            "search": "البحث:",
            "zeroRecords": "لا يوجد بيانات تشابه البحث"
        },
        responsive: !0,
        "columnDefs": [
            {
                "targets": [3],
                "searchable": false,
                //className: "never"//hide
            },
        ],
        order: [
            [0, "asc"]
        ],
        paging: true,
        lengthMenu: [
            [5, 10, 15, 20, 50, -1],
            [5, 10, 15, 20, 50, "All"]
        ],
        pageLength: 10,
        dom: "<'row' <'col-md-12'B>><'row'<'col-md-6 col-sm-12'l><'col-md-6 col-sm-12'f>r><'table-scrollable't><'row'<'col-md-5 col-sm-12'i><'col-md-7 col-sm-12'p>>"
    });

    $(".Reviewed").on("click", function () {

        var pro_id = $(this).attr('data-id');
        var thisis = $(this);
        $.ajax({
            type: "POST",
            url: 'productControllerAjax.php?do=reviewunreview',
            data: {pro_id: pro_id},
            cache: false,
            success: function (res) {
                var ques = Number(res)
                if (ques == 1) {
                    thisis.parents("tr").addClass("hidden");
                    tablereviewed.ajax.reload();

                }
            }
        });

    });
}

//prevent auto submit made by parcode reader
//$(':input').live('keypress', function () {
$("[id^='parcode']").live('keypress', function () {
    if (event.which == '10' || event.which == '13') {
        event.preventDefault();
    }
});
$("[id^='parcode_detail']").live('keypress', function () {
    if (event.which == '10' || event.which == '13') {
        event.preventDefault();
        var itr = $(this).attr('id').substring(14);
        itr++;
        if ($('#parcode_detail' + itr)) {
            $('#parcode_detail' + itr).focus();
        }
    }
});

var formatResultFatma;


formatResultFatma = function (data) {
    //alert(data);
    //return  data.text;
    //return  data.text + '<span  style="text-align: left;  float: left;  width: 30%;">' + data.price + '</span ><span  style="float: left;  margin-left: 5px;"  > ' + data.productquantity + '';
    return data.text + '<span  style="float: left;  margin-left: 5px;"  > ' + data.productquantity + '';
}
$(document).ready(function (e) {



    $('.isservice').live('change', function () {
        var val = $(this).val();
        var itr = $(this).attr('name').substr(9);
        if (val == 1) {
            $('#productBuyPrice' + itr).val("");
            $('#productBuyPrice' + itr).attr('disabled', 'disabled');

            $('#productquantity' + itr).val("");
            $('#productquantity' + itr).attr('disabled', 'disabled');
        } else if (val == 0) {
            $('#productBuyPrice' + itr).removeAttr('disabled');
            $('#productquantity' + itr).removeAttr('disabled');
        }
    });

    $('.isserviceedit').live('change', function () {
        var val = $(this).val();
        var itr = $(this).attr('name').substr(9);
        if (val == 1) {
            $('#productBuyPrice' + itr).val("");
            $('#productBuyPrice' + itr).attr('disabled', 'disabled');

            $('#productquantity' + itr).attr('oldquantity', $('#productquantity' + itr).val());
            $('#productquantity' + itr).val("");
            $('#productquantity' + itr).attr('disabled', 'disabled');
        } else if (val == 0) {
            $('#productBuyPrice' + itr).removeAttr('disabled');
            $('#productquantity' + itr).val($('#productquantity' + itr).attr('oldquantity'));
            $('#productquantity' + itr).removeAttr('disabled');
        }
    });

    $('#product_repeat').live('change', function () {
        var productid = $(this).val();
        var parcode = $('#parcode_repeat').val();
        $.post('productControllerAjax.php?do=repeatsearch', {productid: productid, parcode: parcode}, function (data) {
            $('#tableWrap').html(data);
        });
    });




    $('#product_deleted').live('keyup', function () {

        var productname = $(this).val();

        $.post('productControllerAjax.php?do=product_deleted', {productname: productname}, function (data) {
            $('#tableWrap').html(data);
        });
    });


    $('#productcat_deleted').live('change', function () {

        var productcat_deleted = $(this).val();

        //alert(4444);
        $.post('productControllerAjax.php?do=product_deleted', {productcat_deleted: productcat_deleted}, function (data) {
            $('#tableWrap').html(data);
        });
    });


    $('#parcode_deleted').live('keyup', function () {

        var parcode = $('#parcode_deleted').val();
        $.post('productControllerAjax.php?do=product_deleted', {parcode: parcode}, function (data) {
            $('#tableWrap').html(data);
        });
    });



    $('#parcode_repeat').live('keyup', function () {
        var productid = $('#product_repeat').val();
        var parcode = $('#parcode_repeat').val();
        $.post('productControllerAjax.php?do=repeatsearch', {productid: productid, parcode: parcode}, function (data) {
            $('#tableWrap').html(data);
        });
    });


    /*var UITree = function () {

     return {
     //main function to initiate the module
     init: function () {*/
    // handle collapse/expand for tree_product
    $('#tree_product_collapse').click(function () {
        $('.tree-toggle', $('#tree_product > li > ul')).addClass("closed");
        $('.branch', $('#tree_product > li > ul')).removeClass("in");
    });

    $('#tree_product_expand').click(function () {
        $('.tree-toggle', $('#tree_product > li > ul')).removeClass("closed");
        $('.branch', $('#tree_product > li > ul')).addClass("in");
    });

    $("body").on("click.tree.data-api", "[data-toggle=branch]", function (e) {

        "use strict"; // jshint ;_;

        e.preventDefault()
        if ($(this).next(".branch").data("tree")) {
            $(this).next(".branch").data("tree", false);
        }
        return false
    })

    //This is a quick example of capturing the select event on tree leaves, not branches
    $("#tree_product").on("nodeselect.tree.data-api", "[data-role=leaf]", function (e) {
        // var output = "";

        //output += "Node nodeselect event fired:\n";
        //output += "Node Type: leaf\n";
        //output += "Value: " + ((e.node.value) ? e.node.value : e.node.el.text()) + "\n";
        //output += "Parentage: " + e.node.parentage.join("/");
        $(".tree ul").removeAttr('style');
        $(".tree ul li").removeAttr('style');
        $(".tree ul li a").removeAttr('style')
        //give style to selected node
        $(this).attr("style", "background-color : #95D0F4;");

        //edit product
        var id = e.node.value; //productId
        var isOptic = e.node.isoptic;
        var url;
        if (isOptic == 2) {
            url = "productControllerAjax.php?do=editoptid&id=" + id
        } else {
            url = "productControllerAjax.php?do=edit&id=" + id
        }
        $.ajax({
            url: url,
            type: "get",
            success: function (data) {
                // alert(data);
                $("#productEdit").html(data);
                $("#productCatformDiv").css("display", "none");//hide product categories form
                $("#productsformDiv").css("display", "none"); //hide products form
                $(".select2_custom").select2();
                $("#selectedId").val(id);
                $("#selectedClass").val("leaf");

                $("#addParent").css("display", "none"); //hide add product category button
                $("#addProduct").css("display", "none"); //hide add product button
                $(".awdatepicker").datepicker();
            },
            error: function () {
                $("#productEdit").html('لقد حدث خطأ أثناء إجراء العملية');
            }
        });



        // alert(output);
    });

    //This is a quick example of capturing the select event on tree branches, not leaves
    $("#tree_product").on("nodeselect.tree.data-api", "[role=branch]", function (e) {
        //alert("nodeselect");

        $(".tree ul").removeAttr('style');
        $(".tree ul li").removeAttr('style');
        $(".tree ul li a").removeAttr('style')
        //give style to selected node
        $(this).attr("style", "background-color : #95D0F4;");

        //user is selecting an product category
        //hide all divs
        $("#productCatformDiv").css("display", "none");//hide product categories form
        $("#productsformDiv").css("display", "none");//hide products form
        $("#productEdit").html('');//hide products edit form

        $("#selectedId").val(e.node.value);
        $("#selectedClass").val("branch");

        //show the appropriate button
        var selectedId = e.node.value;
        var selectedClass = "branch";
        check_for_selected_element_type(selectedId, selectedClass);

    });

    //Listening for the 'openbranch' event. Look for e.node, which is the actual node the user opens
    $("#tree_product").on("openbranch.tree", "[data-toggle=branch]", function (e) {

        // var output = "Node openbranch event fired:\n" + "Node Type: branch\n" + "Value: " + ((e.node.value) ? e.node.value : e.node.el.text()) + "\n" + "Parentage: " + e.node.parentage.join("/") + "\n"
        //alert("openbranch");
        //user is selecting an product category

        $(".tree ul").removeAttr('style');
        $(".tree ul li").removeAttr('style');
        $(".tree ul li a").removeAttr('style')
        //give style to selected node
        $(this).attr("style", "background-color : #95D0F4;");

        //hide all divs
        $("#productCatformDiv").css("display", "none");//hide product categories form
        $("#productsformDiv").css("display", "none");//hide products form
        $("#productEdit").html('');//hide products edit form
        $("#selectedId").val(e.node.value);
        $("#selectedClass").val("branch");

        //show the appropriate button
        var selectedId = e.node.value;
        var selectedClass = "branch";
        check_for_selected_element_type(selectedId, selectedClass);
        //alert(output);
    });


    //Listening for the 'closebranch' event. Look for e.node, which is the actual node the user closed
    $("#tree_product").on("closebranch.tree", "[data-toggle=branch]", function (e) {

        //var output = "Node closebranch event fired:\n" + "Node Type: branch\n" + "Value: " + ((e.node.value) ? e.node.value : e.node.el.text()) + "\n" + "Parentage: " + e.node.parentage.join("/") + "\n"
        //alert("closebranch");
        //user is selecting an product category

        $(".tree ul").removeAttr('style');
        $(".tree ul li").removeAttr('style');
        $(".tree ul li a").removeAttr('style')
        //give style to selected node
        $(this).attr("style", "background-color : #95D0F4;");

        //hide all divs
        $("#productCatformDiv").css("display", "none");//hide product categories form
        $("#productsformDiv").css("display", "none");//hide products form
        $("#productEdit").html('');//hide products edit form
        $("#selectedId").val(e.node.value);
        $("#selectedClass").val("branch");

        //show the appropriate button
        var selectedId = e.node.value;
        var selectedClass = "branch";
        check_for_selected_element_type(selectedId, selectedClass);
        //alert(output);
    });
    /*  }

     };

     }();*/
    function generateParcode(itr) {
        $.ajax({
            url: 'productControllerAjax.php?do=generate',
            type: "get",
            success: function (data) {
                document.getElementById("parcode" + itr).value = data;
            }
        });
    }
    /////////////////////////////////////////

    //add products
    $("#addProducts").click(function () {
        //alert(111);
        var today = $("#today").val();
        // alert(today);
        var catid = $("#productCatId").val();

        var productItr = $("#productItr").val();
        var itr = productItr;
        var unitsItr = 1;
        itr++;

        //# remove parcode
        var hidden_parcode = '';
        $('.check_tr').each(function (e) {
            var ths = $(this);
            if (ths.hasClass('hidden')) {
                hidden_parcode = 'hidden';
                return false;
            }
        });
        var hidden_period = '';
        $('.check_tr_period').each(function (e) {
            var ths = $(this);
            if (ths.hasClass('hidden')) {
                hidden_period = 'hidden';
                return false;
            }
        });
        var hidden_production = '';
        $('.check_tr_production').each(function (e) {
            var ths = $(this);
            if (ths.hasClass('hidden')) {
                hidden_production = 'hidden';
                return false;
            }
        });

        var hidden_description = '';
        $('.check_tr_description').each(function (e) {
            var ths = $(this);
            if (ths.hasClass('hidden')) {
                hidden_description = 'hidden';
                return false;
            }
        });

        var hidden_service = '';
        $('.check_tr_service').each(function (e) {
            var ths = $(this);
            if (ths.hasClass('hidden')) {
                hidden_service = 'hidden';
                return false;
            }
        });

        var hidden_date = '';
        $('.check_tr_date').each(function (e) {
            var ths = $(this);
            if (ths.hasClass('hidden')) {
                hidden_date = 'hidden';
                return false;
            }
        });

        var hidden_limitamount = '';
        $('.check_tr_limitamount').each(function (e) {
            var ths = $(this);
            if (ths.hasClass('hidden')) {
                hidden_limitamount = 'hidden';
                return false;
            }
        });

        var hidden_webApiId = '';
        $('.check_tr_webApiId').each(function (e) {
            var ths = $(this);
            if (ths.hasClass('hidden')) {
                hidden_webApiId = 'hidden';
                return false;
            }
        });

        var hidden_mesurunit = '';
        $('.check_tr_mesurunit').each(function (e) {
            var ths = $(this);
            if (ths.hasClass('hidden')) {
                hidden_mesurunit = 'hidden';
                return false;
            }
        });
        //get cat units
        //$("#catUnitsDiv").html("");
        getCatUnits(catid, itr, unitsItr);

        var price_precentage = $('#hide_precentage').val();
        var hide_precentage = '', price_width = '', price_AllPrice = '', price_HalfPrice = '', price_UnitPrice = "";
        var prices = '';
        var tprices = '';
        if (price_precentage == '1') {
            hide_precentage = " display:none; ";
            price_width = " width: 100% ;";
            price_AllPrice = "سعر الجملة";
            price_HalfPrice = "سعر نصف جملة ";
            price_UnitPrice = "سعر التجزئه";

        } else {
            price_width = " width: 50% !important;";
            price_AllPrice = "نسبة ربح الجملة";
            price_HalfPrice = "نسبة ربح  نصف جملة ";
            price_UnitPrice = "نسبة ربح التجزئه";
        }

        if ($('#showpriceall').val() == 1) {
            tprices += '<td style="width:15px" class="p0">' + price_AllPrice + '</td>';
            prices += '<td class="p0">'
                    + '<input style="' + price_width + ' ;float: left;"  name="productSellAllPrice' + itr + '" type="text" id="productSellAllPrice' + itr + '"  data-type="buytotal"  class="form-control  aw_m aw_mt prices aw_pp numberclic positivefloat enteraction numberinput buy_total' + itr + '" data-id="' + itr + '"  width="10"/>'
                    + '<input style="  ' + hide_precentage + ' width: 50%;"  name="buytotal_precentage' + itr + '" type="text" id="productBuyPrice' + itr + '"   data-type="buytotal"  tabindex="-1"  readonly  class="form-control  aw_m aw_mt aw_pp precentages success numberclic enteraction  numberinput positivefloat buytotal_precentage' + itr + '" data-id="' + itr + '" width="10"/>'
                    + '</td>';
        }
        if ($('#showpricehalf').val() == 1) {
            tprices += '<td style="width:15px" class="p0">' + price_HalfPrice + '</td>';
            prices += '<td class="p0">'
                    + '<input style="' + price_width + ' float: left;"  name="productSellHalfPrice' + itr + '" type="text" id="productSellHalfPrice' + itr + '" data-type="buyhalf" class="form-control prices aw_m aw_mt aw_pp numberclic positivefloat enteraction numberinput buy_hafe' + itr + '" data-id="' + itr + '"  width="20"/>'
                    + '<input style="  ' + hide_precentage + ' width: 50%;"  name="buyhalf_precentage' + itr + '" type="text" id="productBuyPrice' + itr + '"  data-type="buyhalf"  tabindex="-1"  readonly  class="form-control  aw_m aw_mt aw_pp precentages success numberclic enteraction  numberinput positivefloat buyhafe_precentage' + itr + '" data-id="' + itr + '" width="10"/>'
                    + '</td>';
        }
        if ($('#showpriceunit').val() == 1) {
            tprices += '<td style="width:15px" class="p0">' + price_UnitPrice + '</td>';
            prices += '<td class="p0">'
                    + '<input  style="' + price_width + ' float: left;"  name="productSellUnitPrice' + itr + '" type="text" id="productSellUnitPrice' + itr + '"  data-type="buypart"   class="form-control prices aw_m aw_mt aw_pp numberclic enteraction buy_part' + itr + ' numberinput" data-id="' + itr + '"  size="20"/>'
                    + '<input style=" ' + hide_precentage + ' width: 50%;"  name="buypart_precentage' + itr + '" type="text" id="productBuyPrice' + itr + '"   data-type="buypart"  tabindex="-1"  readonly   class="form-control  aw_m aw_mt aw_pp precentages success numberclic enteraction  numberinput positivefloat buypart_precentage' + itr + '" data-id="' + itr + '" width="10"/>'
                    + '</td>';
        }

        if ($('#showprice4').val() == 1) {
            tprices += ' <td style="width:15px" class="p0">سعر4</td>';
            prices += '<td class="p0">'
                    + '       <input  style=" width: 100%; float: left;"  name="price4_' + itr + '" type="text" id="price4_' + itr + '"  data-type="price4"   class="form-control prices aw_m aw_mt aw_pp numberclic enteraction price4_' + itr + ' numberinput" data-id="' + itr + '"  size="20"/>'
                    + ' </td>';
        }
        if ($('#showprice5').val() == 1) {
            tprices += ' <td style="width:15px" class="p0">سعر5</td>';
            prices += '<td class="p0">'
                    + '       <input  style=" width: 100%; float: left;"  name="price5_' + itr + '" type="text" id="price5_' + itr + '"  data-type="price5"   class="form-control prices aw_m aw_mt aw_pp numberclic enteraction price5_' + itr + ' numberinput" data-id="' + itr + '"  size="20"/>'
                    + ' </td>';
        }
        if ($('#showprice6').val() == 1) {
            tprices += ' <td style="width:15px" class="p0">سعر6</td>';
            prices += '<td class="p0">'
                    + '       <input  style=" width: 100%; float: left;"  name="price6_' + itr + '" type="text" id="price6_' + itr + '"  data-type="price6"   class="form-control prices aw_m aw_mt aw_pp numberclic enteraction price6_' + itr + ' numberinput" data-id="' + itr + '"  size="20"/>'
                    + ' </td>';
        }
        if ($('#showprice7').val() == 1) {
            tprices += ' <td style="width:15px" class="p0">سعر7</td>';
            prices += '<td class="p0">'
                    + '       <input  style=" width: 100%; float: left;"  name="price7_' + itr + '" type="text" id="price7_' + itr + '"  data-type="price7"   class="form-control prices aw_m aw_mt aw_pp numberclic enteraction price7_' + itr + ' numberinput" data-id="' + itr + '"  size="20"/>'
                    + ' </td>';
        }
        if ($('#showprice8').val() == 1) {
            tprices += ' <td style="width:15px" class="p0">سعر8</td>';
            prices += '<td class="p0">'
                    + '       <input  style=" width: 100%; float: left;"  name="price8_' + itr + '" type="text" id="price8_' + itr + '"  data-type="price8"   class="form-control prices aw_m aw_mt aw_pp numberclic enteraction price8_' + itr + ' numberinput" data-id="' + itr + '"  size="20"/>'
                    + ' </td>';
        }
        if ($('#showprice9').val() == 1) {
            tprices += ' <td style="width:15px" class="p0">سعر9</td>';
            prices += '<td class="p0">'
                    + '       <input  style=" width: 100%; float: left;"  name="price9_' + itr + '" type="text" id="price9_' + itr + '"  data-type="price9"   class="form-control prices aw_m aw_mt aw_pp numberclic enteraction price9_' + itr + ' numberinput" data-id="' + itr + '"  size="20"/>'
                    + ' </td>';
        }
        if ($('#showprice10').val() == 1) {
            tprices += ' <td style="width:15px" class="p0">سعر10</td>';
            prices += '<td class="p0">'
                    + '       <input  style=" width: 100%; float: left;"  name="price10_' + itr + '" type="text" id="price10_' + itr + '"  data-type="price10"   class="form-control prices aw_m aw_mt aw_pp numberclic enteraction price10_' + itr + ' numberinput" data-id="' + itr + '"  size="20"/>'
                    + ' </td>';
        }
        if ($('#showprice11').val() == 1) {
            tprices += ' <td style="width:15px" class="p0">سعر11</td>';
            prices += '<td class="p0">'
                    + '       <input  style=" width: 100%; float: left;"  name="price11_' + itr + '" type="text" id="price11_' + itr + '"  data-type="price11"   class="form-control prices aw_m aw_mt aw_pp numberclic enteraction price11_' + itr + ' numberinput" data-id="' + itr + '"  size="20"/>'
                    + ' </td>';
        }
        if ($('#showprice12').val() == 1) {
            tprices += ' <td style="width:15px" class="p0">سعر12</td>';
            prices += '<td class="p0">'
                    + '       <input  style=" width: 100%; float: left;"  name="price12_' + itr + '" type="text" id="price12_' + itr + '"  data-type="price12"   class="form-control prices aw_m aw_mt aw_pp numberclic enteraction price12_' + itr + ' numberinput" data-id="' + itr + '"  size="20"/>'
                    + ' </td>';
        }
        if ($('#showprice13').val() == 1) {
            tprices += ' <td style="width:15px" class="p0">سعر13</td>';
            prices += '<td class="p0">'
                    + '       <input  style=" width: 100%; float: left;"  name="price13_' + itr + '" type="text" id="price13_' + itr + '"  data-type="price13"   class="form-control prices aw_m aw_mt aw_pp numberclic enteraction price13_' + itr + ' numberinput" data-id="' + itr + '"  size="20"/>'
                    + ' </td>';
        }



        var realprice = $('#hide_realprice').val();
        var hide_realprice = '';
        if (realprice == '1') {
            hide_realprice = ' ; display : none ;';
        }

        var hide_isCaf = Number($('#hide_isCaf').val());
        var hide_isRestaurent = Number($('#hide_isRestaurent').val());
        var hidden_inMenu = '';
        if (hide_isCaf != 1 && hide_isRestaurent != 1) {
            hidden_inMenu = 'hidden';
        }

        var ebill = Number($('#ebill').val());
        var hidden_etaproduct = '';
        if (ebill != 1) {
            hidden_etaproduct = 'hidden';
        }

        var importproduct = Number($('#importproduct').val());
        var hidden_importproduct = '';
        if (importproduct != 1) {
            hidden_importproduct = 'hidden';
        }

        var hide_client = '';
        if ($('#addclienttoproduct').val() != 1) {
            hide_client = ' hidden';
        }

        var hide_nameE = '';
        if ($('#shownameE').val() != 1) {
            hide_nameE = ' hidden';
        }
        var hide_procode = '';
        if ($('#showprocode').val() != 1) {
            hide_procode = ' hidden';
        }
        var hide_partnumber = '';
        if ($('#showpartnumber').val() != 1) {
            hide_partnumber = ' hidden';
        }
        var hide_type = '';
        if ($('#showtype').val() != 1) {
            hide_type = ' hidden';
        }
        var hide_company = '';
        if ($('#showcompany').val() != 1) {
            hide_company = ' hidden';
        }
        var hide_weight = '';
        if ($('#showweight').val() != 1) {
            hide_weight = ' hidden';
        }
        var hide_origin = '';
        if ($('#showorigin').val() != 1) {
            hide_origin = ' hidden';
        }
        var hide_hscode = '';
        if ($('#showhscode').val() != 1) {
            hide_hscode = ' hidden';
        }
        var hide_expire = '';
        if ($('#showexpire').val() != 1) {
            hide_expire = ' hidden';
        }
        var hide_grantduration = '';
        if ($('#showgrantduration').val() != 1) {
            hide_grantduration = ' hidden';
        }
        var hide_online = '';
        if ($('#showonline').val() != 1) {
            hide_online = ' hidden';
        }
        var hide_minappear = '';
        if ($('#showminappear').val() != 1) {
            hide_minappear = ' hidden';
        }
        var hide_onlinecat = '';
        if ($('#showonlinecat').val() != 1) {
            hide_onlinecat = ' hidden';
        }

        var hide_sellpercent = '';
        if ($('#showsellpercentage').val() != 1) {
            hide_sellpercent = ' hidden';
        }
        var hide_buydiscount = '';
        if ($('#showbuydiscount').val() != 1) {
            hide_buydiscount = ' hidden';
        }

        var hide_searchfilter = '';
        if ($('#showsearchfilter').val() != 1) {
            hide_searchfilter = ' hidden';
        }

        $("#productsDiv").append(
                ' <div class="table-responsive">'
                + '     <!-----remove-product---->'
                + '  <a id="remove' + itr + '"  onclick="removeProduct(' + itr + ');" class="removeProduct pull-left btn btn-danger">حذف المنتج</a>'
                + '  <a id="etaproduct' + itr + '"  onclick="etaproduct(' + itr + ');" class="etaproduct pull-left btn btn-primary ' + hidden_etaproduct + '">الفاتوره الالكترونيه</a>'

                + '  <!-------- اضافه وحدة قياس------->'
                + '   <input class="addUnits btn btn-warning pull-left ' + hidden_mesurunit + '" onClick="addUnits(' + itr + ');" type="button"  value="إضافة وحدة قياس"/>'
                + '   <input name="unitsItr' + itr + '" id="unitsItr' + itr + '" type="hidden" value="1" />'
                + ' <table id="productsTable"  class="table table-black dataTable" style="background-color:#fff;color:#000!important">'

                + '  <tr >'
                + ' <td style="width:27px" class="p0">الإسم</td>'
                + '  <td style="width:27px" class="p0">سعر الشراء</td>'
                + '  <td style="width:27px ' + hide_realprice + '" class="p0">سعر الشراء الفعلى</td>'
                + tprices + ''
                + '  <td style="width:15px" class="p0">الكمية</td>'
                + '  <td style="width:15px" class="p0">صورة</td>'
                + '  <td style="width:27px" class="p0 ' + hidden_parcode + '">الباركود</td>'
                + '  <td style="width:27px" class="p0 ' + hidden_period + '"> تاريخ الصلاحية</td>'
                + ' <td style="width:27px" class="p0 ' + hidden_date + '">التاريخ</td>'
                + ' <td style="width:27px" class="p0 ' + hidden_limitamount + '">الحد الأدنى للمنتج</td>'
                + ' <td style="width:27px" class="p0 ' + hidden_webApiId + '">web Api Id</td>'
                + ' <td style="width:65px" class="p0 ' + ebillsettingClass + '">نوع الباركود الضريبى</td>'
                + ' <td style="width:27px" class="p0 ' + ebillsettingClass + '">الباركود الضريبى</td>'
                + ' <td style="width:27px" class="p0 ' + hidden_inMenu + '">فى المنيو</td>'
                + ' <td style="width:27px" class="p0 ' + hidden_production + '">التصنيع</td>'
                + '  <td style="width:30px!important" class="p0 ' + hidden_service + '">خدمة</td>'
                + '   <td style="width:100px!important" class="p0 ' + hidden_description + '">الوصف</td>'
                + ' <td class="p0 ' + hide_client + '">العميل</td>'
                + ' <td colspan="2" class="p0 ' + hide_onlinecat + '">تصنيف اونلاين</td>'
                + ' <td colspan="2" class="p0 ' + hide_searchfilter + '">فلاتر البحث</td>'
                + '  </tr>'
                + '  <tr>'
                + '    <td class="p0" style="width:150px"><input  name="productName' + itr + '" type="text" required="required" id="productName' + itr + '" width="100%"   onChange="checkProductName(this.value, ' + itr + ');" data-itra="' + itr + '" data-id="' + itr + '" class="form-control add_required_attr" /></td>'

                + '  <td class="p0"><input data-rowadded="0" data-id="' + itr + '" name="productBuyPrice' + itr + '" type="text" id="productBuyPrice' + itr + '"  class="form-control positivefloat  buy_price aw_m new_product aw_mt aw_pp numberclic enteraction numberinput" width="10"/></td>'


                + ' <td class="p0" style="' + hide_realprice + '">'
                + '        <input style=" width: 50%; float: left;" name="productbuypricereal' + itr + '" type="text" id="buypricereal' + itr + '"  data-type="pricereal"  class="form-control prices positivefloat buy_pricereal' + itr + ' aw_m aw_mt aw_pp numberclic enteraction numberinput" data-id="' + itr + '"  width="10"/>'
                + '        <input style="  width: 50%;"  name="buypricereal_precentage' + itr + '" type="text" id="productBuyPrice' + itr + '"  data-type="pricereal"   tabindex="-1"  readonly  class="form-control precentages success aw_m aw_mt aw_pp numberclic enteraction  numberinput positivefloat buypricereal_precentage' + itr + '" data-id="' + itr + '" width="10" />'
                + ' </td>'
                + prices + ''
                + ' <td class="p0"><input   name="productquantity' + itr + '" type="text" id="productquantity' + itr + '"   value="0" class="form-control aw_m aw_mt aw_pp numberclic enteraction numberinput" size="20" data-id="' + itr + '"/> </td>'
                + ' <td class="p0"><input type="file" name="logo' + itr + '" id="logo' + itr + '" class="form-control" placeholder="الشعار" accept="image/*" data-id="' + itr + '"/></td>'
                + '  <td class="p0 ' + hidden_parcode + '"><input name="parcode' + itr + '" onblur="checkbarcode(this.value, ' + itr + ');" type="text"   id="parcode' + itr + '" size="9" class="form-control" value="" size="50" data-id="' + itr + '"></td>'
                + '  <td class="p0 ' + hidden_period + '"><input name="expireDate' + itr + '" type="text"   id="expireDate' + itr + '" size="9" class="form-control" value="0"  style="width: 81%;" data-id="' + itr + '"> <span style="float: left;margin-top: -27px;color: white;font-size: 14px;font-weight: bold;padding-left: 2px;">يوم</span></td>'

                + ' <td class="p0 ' + hidden_date + '"><input name="productDate' + itr + '" type="text" id="productDate' + itr + '" size="9"  class="form-control awdatepicker" autocomplete="off"  data-date-format="yyyy-mm-dd" value="' + today + '"  width="27" data-id="' + itr + '"/></td>'
                + ' <td class="p0 ' + hidden_limitamount + '"><input name="limitamount' + itr + '" type="text" id="limitamount' + itr + '" value="0" class="form-control  aw_m aw_mt aw_pp numberclic enteraction numberinput" data-id="' + itr + '"/></td>'
                + ' <td class="p0 ' + hidden_webApiId + '"><input name="webApiId' + itr + '" type="text" id="webApiId' + itr + '" value="" class="form-control  aw_m aw_mt aw_pp numberclic enteraction numberinput" data-id="' + itr + '"/></td>'
                + ' <td class="p0 ' + ebillsettingClass + '">'
                + ' <div class="form-group" style="font-size:13px">'
                + '                                    <label class="color-black unsetBoldProp">'
                + '                                        <input value="GS1"  class="radioR" name="TypeOfBarcodeInTax' + itr + '" checked="checked"  type="radio"  data-id="' + itr + '"/>'
                + '                                        GS1 </label>'

                + '                                    <label class="color - black unsetBoldProp">'
                + '                                        <input value="EGS"  class="noradioR" name="TypeOfBarcodeInTax' + itr + '" type="radio" data-id="' + itr + '"/>'
                + '                                        EGS </label>'
                + ' </div>'
                + '  </td>'
                +'<td class="p0 ' + ebillsettingClass + '">'
                +'    <div class="form-group" style="font-size:13px">'
                +'        <input type="hidden" name="barcodeInTax' + itr + '" id="barcodeInTax' + itr + '"   data-itr="' + itr + '" />'
                +'    </div>'
                +'</td>'
                + '  <td  class="p0 ' + hidden_inMenu + '" style="width:60px">'
                + '     <div class="form-group" style="font-size:13px">'

                + ' <label>'
                + '   <input value="0"  class="radioR" name="inMenu' + itr + '"   type="radio" checked="checked" data-id="' + itr + '"/>'
                + '   نعم </label>'

                + ' <label>'
                + '     <input value="1"  class="noradioR" name="inMenu' + itr + '"  type="radio" data-id="' + itr + '"/>'
                + '    لا </label>'

                + '   </div></td>'


                + '  <td  class="p0 ' + hidden_production + '" style="width:60px">'
                + '     <div class="form-group" style="font-size:13px">'

                + ' <label>'
                + '   <input value="1"  class="radioR" name="type' + itr + '"   type="radio"  data-id="' + itr + '"/>'
                + '   نعم </label>'

                + ' <label>'
                + '     <input value="0"  class="noradioR" name="type' + itr + '"   checked="checked"  type="radio" data-id="' + itr + '"/>'
                + '    لا </label>'

                + '   </div></td>'

                + '  <td class="p0 ' + hidden_service + '" style="width:60px">'
                + '    <div class="form-group"  style="font-size:13px">'

                + ' <label>'

                + '          <input value="1"  class="radioR isservice" name="isservice' + itr + '"   type="radio" data-id="' + itr + '" />'
                + '         نعم </label>'

                + ' <label>'

                + '  <input value="0"  class="noradioR isservice" name="isservice' + itr + '"   checked="checked"  type="radio" data-id="' + itr + '"/>'
                + ' لا </label>'

                + ' </div>'
                + '  </td>'
                + '    <td class="p0 ' + hidden_description + '" style="width:130px"><textarea style="width:100%" onkeypress="onTestChange();" name="productDescription' + itr + '" id="productDescription' + itr + '"  class="form-control" data-id="' + itr + '"></textarea></td>'
                + '<td class="p0 ' + hide_client + '" style="width: 10%;"><input type="hidden" id="clientid' + itr + '" name="clientid' + itr + '" class="wdt100 select2-offscreen clientSelect" data-placeholder="اختر عميل"style="display: inline-block;" value="1" /></td>'
                + '    <td colspan="2" class="' + hide_onlinecat + '" style="width: 10%;">'
                + '        <input name="onlinecatid' + itr + '"   type="hidden" id="onlinecatid' + itr + '" width="100%"   class="selectSearchFilters" data-itra="' + itr + '" data-id="' + itr + '"/>'
                + '    </td>'
                + '    <td colspan="2" class="' + hide_searchfilter + '" style="width: 10%;">'
                + '        <input name="searchfiltersid' + itr + '[]"   type="hidden" id="searchfiltersid' + itr + '" width="100%"   class="selectSearchFilters" data-itra="' + itr + '" data-id="' + itr + '"/>'
                + '    </td>'
                + '   </tr>'
                + '   </table>'



                + '  <table>'
                + '  <tr class="' + hidden_importproduct + '"  >'
                + '    <td colspan="1" class="' + hide_nameE + '" style="width:250">E الإسم</td>'
                + '    <td colspan="1" class="' + hide_procode + '">الكود</td>'
                + '    <td colspan="1" class="' + hide_partnumber + '">رقم القطعة</td>'
                + '    <td colspan="1" class="' + hide_type + '">النوع</td>'
                + '    <td colspan="2" class="' + hide_company + '">الشركه المنتجه للصنف    </td>'
                + '    <td colspan="1" class="' + hide_weight + '">وزن</td>'
                + '    <td colspan="1" class="' + hide_origin + '">منشأ</td>'
                + '    <td colspan="1" class="' + hide_hscode + '">رمز النظام المنسق</td>'
                + '    <td colspan="1" class="' + hide_expire + '">صلاحيه</td>'
                + '    <td colspan="1" class="power' + itr + ' ' + hide_expire + '">تاريخ الانتاج</td>'
                + '    <td colspan="1" class="power' + itr + ' ' + hide_expire + '">مدة الصلاحيه</td>'
                + '    <td colspan="1" class="' + hide_grantduration + '">مدة الضمان</td>'
                + '    <td colspan="1" class="' + hide_online + '">اونلاين</td>'
                + '    <td colspan="1" class="' + hide_minappear + '">الحد الأدنى للظهور اونلاين</td>'
                + '    <td colspan="1"class="' + hide_sellpercent + '"> نسبة البيع: إضافة/خصم </td>'
                + '    <td colspan="1" class="sellpercentadd' + itr + ' ' + hide_sellpercent + '">نسبة اضافة بيع</td>'
                + '    <td colspan="1" class="sellpercentdiscount' + itr + '" style="display:none;">نسبة خصم بيع</td>'
                + '    <td colspan="1" class="' + hide_buydiscount + '">نسبة خصم الشراء</td>'
                + '  </tr>'
                + '   <tr class="' + hidden_importproduct + '"  >'

                + '    <td colspan="1" class="' + hide_nameE + '">'
                + '        <input name="productNameE' + itr + '"  type="text" id="productNameE' + itr + '" width="100%"   class="form-control" data-itra="' + itr + '" data-id="' + itr + '"/>'
                + '    </td>'
                + '    <td colspan="1" class="' + hide_procode + '">'
                + '        <input name="procode' + itr + '"  type="text" id="procode' + itr + '" width="100%"   class="form-control" data-itra="' + itr + '" data-id="' + itr + '"/>'
                + '    </td>'
                + '     <td colspan="1" class="' + hide_partnumber + '">'
                + '        <input name="partNumber' + itr + '"  type="text" id="partNumber' + itr + '" width="100%"   class="form-control positivefloat" data-itra="' + itr + '" data-id="' + itr + '"/>'
                + '    </td>'
                + '    <td colspan="1" class="' + hide_type + '">'
                + '        <input name="vehicleType' + itr + '"  type="hidden" id="vehicleType' + itr + '" width="100%"  data-itra="' + itr + '" data-id="' + itr + '"/>'
                + '    </td>'
                + '    <td colspan="2" class="' + hide_company + '">'
                + '        <input name="company' + itr + '"  type="hidden" id="company' + itr + '" width="100%" data-itra="' + itr + '" data-id="' + itr + '"/>'
                + '    </td>'
                + '    <td colspan="1" class="' + hide_weight + '">'
                + '        <input name="weight' + itr + '"  type="text" id="weight' + itr + '" width="100%"   class="form-control positivefloat" data-itra="' + itr + '" data-id="' + itr + '"/>'
                + '    </td>'
                + '      <td colspan="1" class="' + hide_origin + '">'
                + '        <input name="origin' + itr + '"  type="text" id="origin' + itr + '" width="100%"   class="form-control" data-itra="' + itr + '" data-id="' + itr + '"/>'
                + '    </td>'
                + '    <td colspan="1" class="' + hide_hscode + '">'
                + '        <input name="hscode' + itr + '"  type="text" id="hscode' + itr + '" width="100%"   class="form-control positivefloat" data-itra="' + itr + '" data-id="' + itr + '"/>'
                + '    </td>'
                + '    <td colspan="1" class="' + hide_expire + '">'
                + '        <div class="form-group" style="font-size:13px">'
                + '            <label class="color-black">'
                + '                <input value="0"  class="power" data-itra="' + itr + '" name="power' + itr + '" checked="checked"  type="radio"  data-id="' + itr + '"/>'
                + '                نعم </label>'
                + '           <label class="color-black">'
                + '                <input value="1"  class="power"  data-itra="' + itr + '" name="power' + itr + '" type="radio" data-id="' + itr + '"/>'
                + '                لا </label>'
                + '        </div>'
                + '    </td>'
                + '    <td colspan="1" class="power' + itr + ' ' + hide_expire + '">'
                + '        <input name="ProductionDate' + itr + '"  type="text" id="ProductionDate' + itr + '" width="100%"   class="form-control awdatepicker" data-date-format="yyyy-mm-dd"   data-itra="' + itr + '" data-id="' + itr + '"/>'
                + '    </td>'
                + '    <td colspan="1" class="power' + itr + ' ' + hide_expire + '">'
                + '        <input name="expiry' + itr + '"  type="text" id="expiry' + itr + '" width="100%"   class="form-control positivefloat" data-itra="' + itr + '" data-id="' + itr + '"/>'
                + '    </td>'
                + '<td colspan="1" class="' + hide_grantduration + '">'
                + '    <input name="grantduration' + itr + '"  type="text" id="grantduration' + itr + '" width="100%" class="form-control positivefloat" data-itra="' + itr + '" data-id="' + itr + '" />'
                + '</td>'
                + '<td colspan="1" class="' + hide_online + '">'
                + '<div class="form-group" style="font-size:13px">'
                + '  <label class="color-black">'
                + '      <input value="1" data-itra="' + itr + '" name="onlinepro' + itr + '" checked="checked" type="radio" data-id="' + itr + '" />'
                + '      نعم </label>'
                + '  <label class="color-black">'
                + '      <input value="0" data-itra="' + itr + '" name="onlinepro' + itr + '" type="radio" data-id="' + itr + '" />'
                + '      لا </label>'
                + '</div>'
                + '</td>'
                + '<td colspan="1" class="' + hide_minappear + '">'
                + '    <input name="minappearonline' + itr + '"  type="text" id="minappearonline' + itr + '" width="100%" class="form-control positivefloat" data-itra="' + itr + '" data-id="' + itr + '" />'
                + '</td>'
                + '    <td colspan="1" class="' + hide_sellpercent + '">'
                + '        <div class="form-group" style="font-size:13px">'
                + '            <label class="color-black">'
                + '                <input value="0"  class="sellpercenttype" data-itra="' + itr + '" name="sellpercenttype' + itr + '" checked="checked"  type="radio"  data-id="' + itr + '"/>'
                + '                إضافة </label>'
                + '           <label class="color-black">'
                + '                <input value="1"  class="sellpercenttype"  data-itra="' + itr + '" name="sellpercenttype' + itr + '" type="radio" data-id="' + itr + '"/>'
                + '                خصم </label>'
                + '        </div>'
                + '    </td>'
                + '<td colspan="1" class="sellpercentadd' + itr + ' ' + hide_sellpercent + '">'
                + '     <input name="selladdpercent' + itr + '"  type="text" id="selladdpercent' + itr + '" width="100%" class="form-control positivefloat" data-itra="' + itr + '" data-id="' + itr + '" />'
                + '</td>'
                + '<td colspan="1" class="sellpercentdiscount' + itr + '" style="display:none;">'
                + '     <input name="selldiscountpercent' + itr + '"  type="text" id="selldiscountpercent' + itr + '" width="100%" class="form-control positivefloat" data-itra="' + itr + '" data-id="' + itr + '" />'
                + ' </td>'
                + '<td colspan="1" class="' + hide_buydiscount + '">'
                + '     <input name="buydiscountpercent' + itr + '"  type="text" id="buydiscountpercent' + itr + '" width="100%" class="form-control positivefloat" data-itra="' + itr + '" data-id="' + itr + '" />'
                + '</td>'

                + '  </table>'

                + '  <!------------------------ وحدة قياس---------------------->'
                + '          <div id="addUnitsDiv' + itr + '_1" style=" " class="' + hidden_mesurunit + '">'
                + '            <table id="unitsTable' + itr + '" class="table" style="'
                + '                   width: 98%;'
                + '                box-shadow: 0px 3px 5px #a59f9f, -3px 0px 5px #fff;'
                + '               background-color: #999;">'
                + '           <tr style="display: none">'
                + '              <td>'
                + '                <div class="form-group">'
                + '                <label class="col-lg-4 control-label">اسم وحدة القياس</label>'
                + '               <div class="col-lg-8">'
                + '                 <select name="productunit' + itr + '_1" id="productunit' + itr + '_1" data-placeholder="اختر"  class="select2 wdt100 chosenproduct" >'
                + '                   <option value="-1">اختر وحدة القياس</option>'
                + ''//get units
                + '    </select>'
                + ' </div>'
                + '</div>'
                + '  </td>'
                + '  <td>'
                + '     <div class="form-group">'
                + '  <label class="col-lg-4 control-label">عدد الوحدات</label>'
                + '  <div class="col-lg-8">'
                + '     <input name="productnumber' + itr + '_1" id="productnumber' + itr + '_1" type="text" class="form-control numberinput" />'
                + '  </div>'
                + ' </div>'
                + '   </td>'
                + '   <td>'
                + '      <a id="remove1_1" onClick="removeUnits(' + itr + ', 1);" class="removeUnits">X</a>'
                + '   </td>'
                + ' </tr>'








                + '   </tr>'


                + ' </table>'
                + '   <!--end unitsTable-->'
                + '  </div>'
                + ' <!--end productsTable -->'

                + ' <div id="catUnitsDiv' + itr + '" style="display:none;">'

                + '   </div>'

                + '  </div>'
                );

        initSelect2($('#clientid' + itr));


        $("#vehicleType" + itr).select2({
            placeholder: "اختر",
            multiple: false,
            quietMillis: 100,
            ajax: {
                url: "vehicleType.php?do=vehicleTypes",
                dataType: 'json',
                data: function (term, page) {
                    return {
                        term: term, //search term
                        page_limit: 10, // page size
                    };
                },
                results: function (data) {
                    return {results: data};
                }
            },
            formatResult: formatResultFatma,
            initSelection: function (element, callback) {
                var item = element.val().split(':');
                var data = {id: item[0], text: item[1]};
                callback(data);
            }
        });


         $("#barcodeInTax" + itr).select2({
                placeholder: "اختر",
                multiple: false,
                ajax: {
                    url: "eBillRequests.php?do=barcodeInTax",
                    dataType: 'json',
                    data: function (term, page) {
                          var itr = $(this).attr('data-itr');
                         var TypeOfBarcodeInTax =  $('input[name="TypeOfBarcodeInTax'+itr+'"]:checked').val();
                        return {
                            term: term, //search term
                            TypeOfBarcodeInTax: TypeOfBarcodeInTax,
                        };
                    },
                    results: function (data) {
                        return {results: data};
                    }
                },
                formatResult: formatResultFatma,
                initSelection: function (element, callback) {
                    var item = element.val().split(':');
                    var data = {id: item[0], text: item[1]};
                    callback(data);
                }
            });

        $("#company" + itr).select2({
            placeholder: "اختر",
            multiple: false,
            quietMillis: 100,
            ajax: {
                url: "companyproduces.php?do=companyproduces",
                dataType: 'json',
                data: function (term, page) {
                    return {
                        term: term, //search term
                        page_limit: 10, // page size
                    };
                },
                results: function (data) {
                    return {results: data};
                }
            },
            formatResult: formatResultFatma,
            initSelection: function (element, callback) {
                var item = element.val().split(':');
                var data = {id: item[0], text: item[1]};
                callback(data);
            }
        });
        $("#onlinecatid" + itr).select2({
            placeholder: "اختر",
            multiple: false,
            quietMillis: 100,
            ajax: {
                url: "onlineCatController.php?do=getallSubFilters",
                dataType: 'json',
                data: function (term, page) {
                    return {
                        term: term, //search term
                        page_limit: 10, // page size
                    };
                },
                results: function (data) {
                    return {results: data};
                }
            },
            formatResult: function (data) {
                return data.text;
            },
            initSelection: function (element, callback) {
                var item = element.val().split(':');
                var data = {id: item[0], text: item[1]};
                callback(data);
            }
        });
        $("#searchfiltersid" + itr).select2({
            placeholder: "اختر",
            multiple: true,
            quietMillis: 100,
            ajax: {
                url: "searchFiltersController.php?do=getallSubFilters",
                dataType: 'json',
                data: function (term, page) {
                    return {
                        term: term, //search term
                        page_limit: 10, // page size
                    };
                },
                results: function (data) {
                    return {results: data};
                }
            },
            formatResult: function (data) {
                return data.text;
            },
            initSelection: function (element, callback) {
                var item = element.val().split(':');
                var data = {id: item[0], text: item[1]};
                callback(data);
            }
        });
        $('select.select2_custom').select2();
        $('.awdatepicker').datepicker();
        $('.numberinput').forceNumeric();
        //alert(itr);
        $("#productItr").val(itr); //assign new iteration value
        //generateParcode(itr);
        $(".positivefloat").forcepositivefloat();

        //# file precentages prices
        var last_level = $('#level').val();
        //# this check for getting [ productCatId ] from tree or from other adding products .
        if (typeof last_level !== 'undefined') {

            last_level = last_level - 1;

            var last_productCatId = $('#productCatId' + last_level + '').val();
            $('#productCatId').val(last_productCatId);

            //# fill buypricereal ,  buytotal , buyhalf , buypart
            var productCatId_level = $('#level').val();
            //console.log('level = '+productCatId_level);
            var i, last_level;
            for (i = 1; i <= productCatId_level; i++) {
                if (i == productCatId_level) {
                    last_level = productCatId_level - 1;
                }
            }
            var productCatId = $('#productCatId' + last_level + '').val();

        } else {
            productCatId = catid;
        }

        // console.log('productCatId_before = '+productCatId);

        console.log('productCatId_add = ' + productCatId + 'catid = ' + catid);
        $.post('productControllerAjax.php?do=get_prices', {productCatId: productCatId}, function (data) {
            data = JSON.parse(data);
            $('.buypricereal_precentage' + itr + '').val(data.buypricereal);
            $('.buytotal_precentage' + itr + '').val(data.buytotal);
            $('.buyhafe_precentage' + itr + '').val(data.buyhalf);
            $('.buypart_precentage' + itr + '').val(data.buypart);
        });


    });
    $("body").on('change', '.power', function () {
        var power = $(this).val();
        var itra = $(this).attr('data-itra');
        if (power == 0) {
            $('.power' + itra).show();
        } else {
            $('.power' + itra).hide();
        }
    });

    //# add required attribute
    $("body").on('focusout', '.add_required_attr', function () {
        var ths_val = $(this).val();
        var itra = $(this).data('itra');

        if (ths_val.length > 0) {
            $(this).attr('required', 'required');
            $('#productBuyPrice' + itra + '').attr('required', 'required');
            $('#productSellAllPrice' + itra + '').attr('required', 'required');
            $('#productSellHalfPrice' + itra + '').attr('required', 'required');
            $('#productSellUnitPrice' + itra + '').attr('required', 'required');
            $('#productquantity' + itra + '').attr('required', 'required');
            //$('#parcode' + itra + '').attr('required', 'required');
            $('#expireDate' + itra + '').attr('required', 'required');
            $('#productDate' + itra + '').attr('required', 'required');
        } else {
            $(this).removeAttr('required', 'required');
            $('#productBuyPrice' + itra + '').removeAttr('required', 'required');
            $('#productSellAllPrice' + itra + '').removeAttr('required', 'required');
            $('#productSellHalfPrice' + itra + '').removeAttr('required', 'required');
            $('#productSellUnitPrice' + itra + '').removeAttr('required', 'required');
            $('#productquantity' + itra + '').removeAttr('required', 'required');
            //$('#parcode' + itra + '').removeAttr('required', 'required');
            $('#expireDate' + itra + '').removeAttr('required', 'required');
            $('#productDate' + itra + '').removeAttr('required', 'required');
        }



    });

    //# add product by entering name .
    $("body").on('focusout', '.new_product', function () {
        var this_is = $(this);
        setTimeout(function () {//this time out to allow save button click and not to consider it as focusout



            var ths_val = this_is.val();
            var ths_rowadded = this_is.attr('data-rowadded');

            if (ths_val.length > 0 && ths_rowadded == '0') {
                //alert(111);
                var today = $("#today").val();
                // alert(today);
                var catid = $("#productCatId").val();

                var productItr = $("#productItr").val();
                var itr = productItr;
                var unitsItr = 1;
                itr++;

                //# remove parcode
                var hidden_parcode = '';
                $('.check_tr').each(function (e) {
                    var ths = $(this);
                    if (ths.hasClass('hidden')) {
                        hidden_parcode = 'hidden';
                        return false;
                    }
                });
                var hidden_period = '';
                $('.check_tr_period').each(function (e) {
                    var ths = $(this);
                    if (ths.hasClass('hidden')) {
                        hidden_period = 'hidden';
                        return false;
                    }
                });
                var hidden_production = '';
                $('.check_tr_production').each(function (e) {
                    var ths = $(this);
                    if (ths.hasClass('hidden')) {
                        hidden_production = 'hidden';
                        return false;
                    }
                });

                var hidden_description = '';
                $('.check_tr_description').each(function (e) {
                    var ths = $(this);
                    if (ths.hasClass('hidden')) {
                        hidden_description = 'hidden';
                        return false;
                    }
                });

                var hidden_service = '';
                $('.check_tr_service').each(function (e) {
                    var ths = $(this);
                    if (ths.hasClass('hidden')) {
                        hidden_service = 'hidden';
                        return false;
                    }
                });

                var hidden_date = '';
                $('.check_tr_date').each(function (e) {
                    var ths = $(this);
                    if (ths.hasClass('hidden')) {
                        hidden_date = 'hidden';
                        return false;
                    }
                });

                var hidden_limitamount = '';
                $('.check_tr_limitamount').each(function (e) {
                    var ths = $(this);
                    if (ths.hasClass('hidden')) {
                        hidden_limitamount = 'hidden';
                        return false;
                    }
                });

                var hidden_webApiId = '';
                $('.check_tr_webApiId').each(function (e) {
                    var ths = $(this);
                    if (ths.hasClass('hidden')) {
                        hidden_webApiId = 'hidden';
                        return false;
                    }
                });

                var hidden_mesurunit = '';
                $('.check_tr_mesurunit').each(function (e) {
                    var ths = $(this);
                    if (ths.hasClass('hidden')) {
                        hidden_mesurunit = 'hidden';
                        return false;
                    }
                });
                //get cat units
                //$("#catUnitsDiv").html("");
                getCatUnits(catid, itr, unitsItr);


                var price_precentage = $('#hide_precentage').val();
                var hide_precentage = '', price_width = '', price_AllPrice = '', price_HalfPrice = '', price_UnitPrice = "";
                var prices = tprices = '';
                if (price_precentage == '1') {
                    hide_precentage = " display:none; ";
                    price_width = " width: 100% ;";
                    price_AllPrice = "سعر الجملة";
                    price_HalfPrice = "سعر نصف جملة ";
                    price_UnitPrice = "سعر التجزئه";

                } else {
                    price_width = " width: 50% !important;";
                    price_AllPrice = "نسبة ربح الجملة";
                    price_HalfPrice = "نسبة ربح  نصف جملة ";
                    price_UnitPrice = "نسبة ربح التجزئه";
                }


                if ($('#showpriceall').val() == 1) {
                    tprices += '<td style="width:15px" class="p0">' + price_AllPrice + '</td>';
                    prices += '<td class="p0">'
                            + '<input style="' + price_width + ' ;float: left;"  name="productSellAllPrice' + itr + '" type="text" id="productSellAllPrice' + itr + '"  data-type="buytotal"  class="form-control  aw_m aw_mt prices aw_pp numberclic positivefloat enteraction numberinput buy_total' + itr + '" data-id="' + itr + '"  width="10"/>'
                            + '<input style="  ' + hide_precentage + ' width: 50%;"  name="buytotal_precentage' + itr + '" type="text" id="productBuyPrice' + itr + '"   data-type="buytotal"  tabindex="-1"  readonly  class="form-control  aw_m aw_mt aw_pp precentages success numberclic enteraction  numberinput positivefloat buytotal_precentage' + itr + '" data-id="' + itr + '" width="10"/>'
                            + '</td>';
                }
                if ($('#showpricehalf').val() == 1) {
                    tprices += '<td style="width:15px" class="p0">' + price_HalfPrice + '</td>';
                    prices += '<td class="p0">'
                            + '<input style="' + price_width + ' float: left;"  name="productSellHalfPrice' + itr + '" type="text" id="productSellHalfPrice' + itr + '" data-type="buyhalf" class="form-control prices aw_m aw_mt aw_pp numberclic positivefloat enteraction numberinput buy_hafe' + itr + '" data-id="' + itr + '"  width="20"/>'
                            + '<input style="  ' + hide_precentage + ' width: 50%;"  name="buyhalf_precentage' + itr + '" type="text" id="productBuyPrice' + itr + '"  data-type="buyhalf"  tabindex="-1"  readonly  class="form-control  aw_m aw_mt aw_pp precentages success numberclic enteraction  numberinput positivefloat buyhafe_precentage' + itr + '" data-id="' + itr + '" width="10"/>'
                            + '</td>';
                }
                if ($('#showpriceunit').val() == 1) {
                    tprices += '<td style="width:15px" class="p0">' + price_UnitPrice + '</td>';
                    prices += '<td class="p0">'
                            + '<input  style="' + price_width + ' float: left;"  name="productSellUnitPrice' + itr + '" type="text" id="productSellUnitPrice' + itr + '"  data-type="buypart"   class="form-control prices aw_m aw_mt aw_pp numberclic enteraction buy_part' + itr + ' numberinput" data-id="' + itr + '"  size="20"/>'
                            + '<input style=" ' + hide_precentage + ' width: 50%;"  name="buypart_precentage' + itr + '" type="text" id="productBuyPrice' + itr + '"   data-type="buypart"  tabindex="-1"  readonly   class="form-control  aw_m aw_mt aw_pp precentages success numberclic enteraction  numberinput positivefloat buypart_precentage' + itr + '" data-id="' + itr + '" width="10"/>'
                            + '</td>';
                }

                if ($('#showprice4').val() == 1) {
                    tprices += ' <td style="width:15px" class="p0">سعر4</td>';
                    prices += '<td class="p0">'
                            + '       <input  style=" width: 100%; float: left;"  name="price4_' + itr + '" type="text" id="price4_' + itr + '"  data-type="price4"   class="form-control prices aw_m aw_mt aw_pp numberclic enteraction price4_' + itr + ' numberinput" data-id="' + itr + '"  size="20"/>'
                            + ' </td>';
                }
                if ($('#showprice5').val() == 1) {
                    tprices += ' <td style="width:15px" class="p0">سعر5</td>';
                    prices += '<td class="p0">'
                            + '       <input  style=" width: 100%; float: left;"  name="price5_' + itr + '" type="text" id="price5_' + itr + '"  data-type="price5"   class="form-control prices aw_m aw_mt aw_pp numberclic enteraction price5_' + itr + ' numberinput" data-id="' + itr + '"  size="20"/>'
                            + ' </td>';
                }
                if ($('#showprice6').val() == 1) {
                    tprices += ' <td style="width:15px" class="p0">سعر6</td>';
                    prices += '<td class="p0">'
                            + '       <input  style=" width: 100%; float: left;"  name="price6_' + itr + '" type="text" id="price6_' + itr + '"  data-type="price6"   class="form-control prices aw_m aw_mt aw_pp numberclic enteraction price6_' + itr + ' numberinput" data-id="' + itr + '"  size="20"/>'
                            + ' </td>';
                }
                if ($('#showprice7').val() == 1) {
                    tprices += ' <td style="width:15px" class="p0">سعر7</td>';
                    prices += '<td class="p0">'
                            + '       <input  style=" width: 100%; float: left;"  name="price7_' + itr + '" type="text" id="price7_' + itr + '"  data-type="price7"   class="form-control prices aw_m aw_mt aw_pp numberclic enteraction price7_' + itr + ' numberinput" data-id="' + itr + '"  size="20"/>'
                            + ' </td>';
                }
                if ($('#showprice8').val() == 1) {
                    tprices += ' <td style="width:15px" class="p0">سعر8</td>';
                    prices += '<td class="p0">'
                            + '       <input  style=" width: 100%; float: left;"  name="price8_' + itr + '" type="text" id="price8_' + itr + '"  data-type="price8"   class="form-control prices aw_m aw_mt aw_pp numberclic enteraction price8_' + itr + ' numberinput" data-id="' + itr + '"  size="20"/>'
                            + ' </td>';
                }
                if ($('#showprice9').val() == 1) {
                    tprices += ' <td style="width:15px" class="p0">سعر9</td>';
                    prices += '<td class="p0">'
                            + '       <input  style=" width: 100%; float: left;"  name="price9_' + itr + '" type="text" id="price9_' + itr + '"  data-type="price9"   class="form-control prices aw_m aw_mt aw_pp numberclic enteraction price9_' + itr + ' numberinput" data-id="' + itr + '"  size="20"/>'
                            + ' </td>';
                }
                if ($('#showprice10').val() == 1) {
                    tprices += ' <td style="width:15px" class="p0">سعر10</td>';
                    prices += '<td class="p0">'
                            + '       <input  style=" width: 100%; float: left;"  name="price10_' + itr + '" type="text" id="price10_' + itr + '"  data-type="price10"   class="form-control prices aw_m aw_mt aw_pp numberclic enteraction price10_' + itr + ' numberinput" data-id="' + itr + '"  size="20"/>'
                            + ' </td>';
                }
                if ($('#showprice11').val() == 1) {
                    tprices += ' <td style="width:15px" class="p0">سعر11</td>';
                    prices += '<td class="p0">'
                            + '       <input  style=" width: 100%; float: left;"  name="price11_' + itr + '" type="text" id="price11_' + itr + '"  data-type="price11"   class="form-control prices aw_m aw_mt aw_pp numberclic enteraction price11_' + itr + ' numberinput" data-id="' + itr + '"  size="20"/>'
                            + ' </td>';
                }
                if ($('#showprice12').val() == 1) {
                    tprices += ' <td style="width:15px" class="p0">سعر12</td>';
                    prices += '<td class="p0">'
                            + '       <input  style=" width: 100%; float: left;"  name="price12_' + itr + '" type="text" id="price12_' + itr + '"  data-type="price12"   class="form-control prices aw_m aw_mt aw_pp numberclic enteraction price12_' + itr + ' numberinput" data-id="' + itr + '"  size="20"/>'
                            + ' </td>';
                }
                if ($('#showprice13').val() == 1) {
                    tprices += ' <td style="width:15px" class="p0">سعر13</td>';
                    prices += '<td class="p0">'
                            + '       <input  style=" width: 100%; float: left;"  name="price13_' + itr + '" type="text" id="price13_' + itr + '"  data-type="price13"   class="form-control prices aw_m aw_mt aw_pp numberclic enteraction price13_' + itr + ' numberinput" data-id="' + itr + '"  size="20"/>'
                            + ' </td>';
                }

                var realprice = $('#hide_realprice').val();
                var hide_realprice = '';
                if (realprice == '1') {
                    hide_realprice = ' ; display : none ;';
                }

                var hide_isCaf = Number($('#hide_isCaf').val());
                var hide_isRestaurent = Number($('#hide_isRestaurent').val());
                var hidden_inMenu = '';
                if (hide_isCaf != 1 && hide_isRestaurent != 1) {
                    hidden_inMenu = 'hidden';
                }

                var ebill = Number($('#ebill').val());
                var hidden_etaproduct = '';
                if (ebill != 1) {
                    hidden_etaproduct = 'hidden';
                }

                var importproduct = Number($('#importproduct').val());
                var hidden_importproduct = '';
                if (importproduct != 1) {
                    hidden_importproduct = 'hidden';
                }

                var hide_client = '';
                if ($('#addclienttoproduct').val() != 1) {
                    hide_client = ' hidden';
                }

                var hide_nameE = '';
                if ($('#shownameE').val() != 1) {
                    hide_nameE = ' hidden';
                }
                var hide_procode = '';
                if ($('#showprocode').val() != 1) {
                    hide_procode = ' hidden';
                }
                var hide_partnumber = '';
                if ($('#showpartnumber').val() != 1) {
                    hide_partnumber = ' hidden';
                }
                var hide_type = '';
                if ($('#showtype').val() != 1) {
                    hide_type = ' hidden';
                }
                var hide_company = '';
                if ($('#showcompany').val() != 1) {
                    hide_company = ' hidden';
                }
                var hide_weight = '';
                if ($('#showweight').val() != 1) {
                    hide_weight = ' hidden';
                }
                var hide_origin = '';
                if ($('#showorigin').val() != 1) {
                    hide_origin = ' hidden';
                }
                var hide_hscode = '';
                if ($('#showhscode').val() != 1) {
                    hide_hscode = ' hidden';
                }
                var hide_expire = '';
                if ($('#showexpire').val() != 1) {
                    hide_expire = ' hidden';
                }
                var hide_grantduration = '';
                if ($('#showgrantduration').val() != 1) {
                    hide_grantduration = ' hidden';
                }
                var hide_online = '';
                if ($('#showonline').val() != 1) {
                    hide_online = ' hidden';
                }
                var hide_minappear = '';
                if ($('#showminappear').val() != 1) {
                    hide_minappear = ' hidden';
                }
                var hide_onlinecat = '';
                if ($('#showonlinecat').val() != 1) {
                    hide_onlinecat = ' hidden';
                }
                var hide_sellpercent = '';
                if ($('#showsellpercentage').val() != 1) {
                    hide_sellpercent = ' hidden';
                }
                var hide_buydiscount = '';
                if ($('#showbuydiscount').val() != 1) {
                    hide_buydiscount = ' hidden';
                }

                var hide_searchfilter = '';
                if ($('#showsearchfilter').val() != 1) {
                    hide_searchfilter = ' hidden';
                }

                $("#productsDiv").append(
                        ' <div class="table-responsive">'
                        + '     <!-----remove-product---->'
                        + '  <a id="remove' + itr + '"  onclick="removeProduct(' + itr + ');" class="removeProduct pull-left btn btn-danger">حذف المنتج</a>'
                        + '  <a id="etaproduct' + itr + '"  onclick="etaproduct(' + itr + ');" class="etaproduct pull-left btn btn-primary ' + hidden_etaproduct + '">الفاتوره الالكترونيه</a>'

                        + '  <!-------- اضافه وحدة قياس------->'
                        + '   <input class="addUnits btn btn-warning pull-left ' + hidden_mesurunit + '" onClick="addUnits(' + itr + ');" type="button"  value="إضافة وحدة قياس"/>'
                        + '   <input name="unitsItr' + itr + '" id="unitsItr' + itr + '" type="hidden" value="1" />'
                        + ' <table id="productsTable"  class="table table-black dataTable" style="background-color:#fff;color:#000!important">'

                        + '  <tr >'
                        + ' <td style="width:27px" class="p0">الإسم</td>'
                        + '  <td style="width:27px" class="p0">سعر الشراء</td>'
                        + '  <td style="width:27px ' + hide_realprice + '" class="p0">سعر الشراء الفعلى</td>'
                        + tprices + ''
                        + '  <td style="width:15px" class="p0">الكمية</td>'
                        + '  <td style="width:15px" class="p0">صورة</td>'
                        + '  <td style="width:27px" class="p0 ' + hidden_parcode + '">الباركود</td>'
                        + '  <td style="width:27px" class="p0 ' + hidden_period + '"> تاريخ الصلاحية</td>'
                        + ' <td style="width:27px" class="p0 ' + hidden_date + '">التاريخ</td>'
                        + ' <td style="width:27px" class="p0 ' + hidden_limitamount + '">الحد الأدنى للمنتج</td>'
                        + ' <td style="width:27px" class="p0 ' + hidden_webApiId + '">web Api Id</td>'
                        + ' <td style="width:65px" class="p0 ' + ebillsettingClass + '">نوع الباركود الضريبى</td>'
                        + ' <td style="width:27px" class="p0 ' + ebillsettingClass + '">الباركود الضريبى</td>'
                        + ' <td style="width:27px" class="p0 ' + hidden_inMenu + '">فى المنيو</td>'
                        + ' <td style="width:27px" class="p0 ' + hidden_production + '">التصنيع</td>'
                        + '  <td style="width:30px!important" class="p0 ' + hidden_service + '">خدمة</td>'
                        + '   <td style="width:100px!important" class="p0 ' + hidden_description + '">الوصف</td>'
                        + ' <td class="p0 ' + hide_client + '">العميل</td>'
                        + ' <td colspan="2" class="p0 ' + hide_onlinecat + '">تصنيف اونلاين</td>'
                        + ' <td colspan="2" class="p0 ' + hide_searchfilter + '">فلاتر البحث</td>'
                        + '  </tr>'
                        + '  <tr>'
                        + '    <td class="p0" style="width:150px"><input name="productName' + itr + '"  type="text" required="required" id="productName' + itr + '" width="100%"  onChange="checkProductName(this.value, ' + itr + ');" data-itra="' + itr + '" class="form-control add_required_attr" /></td>'

                        + '  <td class="p0"><input data-rowadded="0" data-id="' + itr + '" name="productBuyPrice' + itr + '" type="text" id="productBuyPrice' + itr + '"  class="form-control  buy_price aw_m aw_mt aw_pp new_product numberclic enteraction  numberinput positivefloat" width="10"/></td>'



                        + ' <td class="p0" style="' + hide_realprice + '">'
                        + '        <input style=" width : 50% ; float: left;" name="productbuypricereal' + itr + '" type="text" id="buypricereal' + itr + '" data-type="pricereal" class="form-control prices positivefloat buy_pricereal' + itr + ' aw_m aw_mt aw_pp numberclic enteraction numberinput"  data-id="' + itr + '" width="10"/>'
                        + '        <input style=" width : 50% ; "  name="buypricereal_precentage' + itr + '" type="text" id="productBuyPrice' + itr + '"  data-type="pricereal"  tabindex="-1"  readonly  class="form-control precentages success aw_m aw_mt aw_pp numberclic enteraction  numberinput positivefloat buypricereal_precentage' + itr + '" data-id="' + itr + '" width="10" />'
                        + ' </td>'
                        + prices + ''
                        + ' <td class="p0"><input name="productquantity' + itr + '" type="text" id="productquantity' + itr + '"   value="0" class="form-control aw_m aw_mt aw_pp numberclic enteraction numberinput" size="20"/></td>'
                        + ' <td class="p0"><input type="file" name="logo' + itr + '" id="logo' + itr + '" class="form-control" placeholder="الشعار" accept="image/*"/></td>'
                        + '  <td class="p0 ' + hidden_parcode + '"><input name="parcode' + itr + '" onblur="checkbarcode(this.value, ' + itr + ');" type="text"   id="parcode' + itr + '" size="9" class="form-control" value="" size="50" ></td>'
                        + '  <td class="p0 ' + hidden_period + '"><input name="expireDate' + itr + '" type="text"   id="expireDate' + itr + '" size="9" class="form-control" value="0"  style="width: 81%;"><span style="float: left;margin-top: -27px;color: white;font-size: 14px;font-weight: bold;padding-left: 2px;">يوم</span></td>'

                        + ' <td class="p0 ' + hidden_date + '"><input name="productDate' + itr + '" type="text" id="productDate' + itr + '" size="9"  class="form-control awdatepicker" autocomplete="off"  data-date-format="yyyy-mm-dd" value="' + today + '"  width="27"/></td>'
                        + ' <td class="p0 ' + hidden_limitamount + '"><input name="limitamount' + itr + '" type="text" id="limitamount' + itr + '" value="0" class="form-control  aw_m aw_mt aw_pp numberclic enteraction numberinput"/></td>'
                        + ' <td class="p0 ' + hidden_webApiId + '"><input name="webApiId' + itr + '" type="text" id="webApiId' + itr + '" value="0" class="form-control  aw_m aw_mt aw_pp numberclic enteraction numberinput"/></td>'
                        + ' <td class="p0 ' + ebillsettingClass + '">'
                        + ' <div class="form-group" style="font-size:13px">'
                        + '                                    <label class="color-black unsetBoldProp">'
                        + '                                        <input value="GS1"  class="radioR" name="TypeOfBarcodeInTax' + itr + '" checked="checked"  type="radio"  data-id="' + itr + '"/>'
                        + '                                        GS1 </label>'

                        + '                                    <label class="color - black unsetBoldProp">'
                        + '                                        <input value="EGS"  class="noradioR" name="TypeOfBarcodeInTax' + itr + '" type="radio" data-id="' + itr + '"/>'
                        + '                                        EGS </label>'
                        + ' </div>'
                        + '  </td>'
                        +'<td class="p0 ' + ebillsettingClass + '">'
                        +'    <div class="form-group" style="font-size:13px">'
                        +'        <input type="hidden" name="barcodeInTax' + itr + '" id="barcodeInTax' + itr + '"   data-itr="' + itr + '" />'
                        +'    </div>'
                        +'</td>'
                        + '  <td  class="p0 ' + hidden_inMenu + '" style="width:60px">'
                        + '     <div class="form-group" style="font-size:13px">'


                        + ' <label>'
                        + '   <input value="0"  class="radioR" name="inMenu' + itr + '"   type="radio" checked="checked" />'
                        + '   نعم </label>'

                        + ' <label>'
                        + '     <input value="1"  class="noradioR" name="inMenu' + itr + '"  type="radio" />'
                        + '    لا </label>'

                        + '   </div></td>'


                        + '  <td  class="p0 ' + hidden_production + '" style="width:60px">'
                        + '     <div class="form-group" style="font-size:13px">'

                        + ' <label>'
                        + '   <input value="1"  class="radioR" name="type' + itr + '"   type="radio"  />'
                        + '   نعم </label>'

                        + ' <label>'
                        + '     <input value="0"  class="noradioR" name="type' + itr + '"   checked="checked"  type="radio" />'
                        + '    لا </label>'

                        + '   </div></td>'

                        + '  <td class="p0 ' + hidden_service + '" style="width:60px">'
                        + '    <div class="form-group"  style="font-size:13px">'

                        + ' <label>'

                        + '          <input value="1"  class="radioR isservice" name="isservice' + itr + '"   type="radio" />'
                        + '         نعم </label>'

                        + ' <label>'

                        + '  <input value="0"  class="noradioR isservice" name="isservice' + itr + '"   checked="checked"  type="radio" />'
                        + ' لا </label>'

                        + ' </div>'
                        + '  </td>'
                        + '     <td class="p0 ' + hidden_description + '" style="width:130px"><textarea style="width:100%" name="productDescription' + itr + '" id="productDescription' + itr + '"  class="form-control"></textarea></td>'
                        + '     <td class="p0 ' + hide_client + '" style="width: 10%;"><input type="hidden" id="clientid' + itr + '" name="clientid' + itr + '" class="wdt100 select2-offscreen clientSelect" data-placeholder="اختر عميل"style="display: inline-block;" value="1" /></td>'
                        + '    <td colspan="2" class="' + hide_onlinecat + '" style="width: 10%;">'
                        + '        <input name="onlinecatid' + itr + '"   type="hidden" id="onlinecatid' + itr + '" width="100%"   class="selectSearchFilters" data-itra="' + itr + '" data-id="' + itr + '"/>'
                        + '    </td>'
                        + '    <td colspan="2" class="' + hide_searchfilter + '" style="width: 10%;">'
                        + '        <input name="searchfiltersid' + itr + '[]"   type="hidden" id="searchfiltersid' + itr + '" width="100%"   class="selectSearchFilters" data-itra="' + itr + '" data-id="' + itr + '"/>'
                        + '    </td>'
                        + '   </tr>'
                        + '   </table>'



                        + '  <table>'
                        + '  <tr class="' + hidden_importproduct + '"  >'
                        + '    <td colspan="1" class="' + hide_nameE + '" style="width:250">E الإسم</td>'
                        + '    <td colspan="1" class="' + hide_procode + '">الكود</td>'
                        + '    <td colspan="1" class="' + hide_partnumber + '">رقم القطعة</td>'
                        + '    <td colspan="1" class="' + hide_type + '">النوع</td>'
                        + '    <td colspan="2" class="' + hide_company + '">الشركه المنتجه للصنف    </td>'
                        + '    <td colspan="1" class="' + hide_weight + '">وزن</td>'
                        + '    <td colspan="1" class="' + hide_origin + '">منشأ</td>'
                        + '    <td colspan="1" class="' + hide_hscode + '">رمز النظام المنسق</td>'
                        + '    <td colspan="1" class="' + hide_expire + '">صلاحيه</td>'
                        + '    <td colspan="1" class="power' + itr + ' ' + hide_expire + '">تاريخ الانتاج</td>'
                        + '    <td colspan="1" class="power' + itr + ' ' + hide_expire + '">مدة الصلاحيه</td>'
                        + '    <td colspan="1" class="' + hide_grantduration + '">مدة الضمان</td>'
                        + '    <td colspan="1" class="' + hide_online + '">اونلاين</td>'
                        + '    <td colspan="1" class="' + hide_minappear + '">الحد الأدنى للظهور اونلاين</td>'
                        + '     <td colspan="1"class="' + hide_sellpercent + '"> نسبة البيع: إضافة/خصم </td>'
                        + '    <td colspan="1" class="sellpercentadd' + itr + ' ' + hide_sellpercent + '">نسبة اضافة بيع</td>'
                        + '    <td colspan="1" class="sellpercentdiscount' + itr + '" style="display:none;">نسبة خصم بيع</td>'
                        + '    <td colspan="1" class="' + hide_buydiscount + '">نسبة خصم الشراء</td>'
                        + '  </tr>'
                        + '   <tr class="' + hidden_importproduct + '"  >'

                        + '    <td colspan="1" class="' + hide_nameE + '">'
                        + '        <input name="productNameE' + itr + '" type="text" id="productNameE' + itr + '" width="100%"   class="form-control" data-itra="' + itr + '" data-id="' + itr + '"/>'
                        + '    </td>'
                        + '    <td colspan="1" class="' + hide_procode + '">'
                        + '        <input name="procode' + itr + '"  type="text" id="procode' + itr + '" width="100%"   class="form-control" data-itra="' + itr + '" data-id="' + itr + '"/>'
                        + '    </td>'
                        + '     <td colspan="1" class="' + hide_partnumber + '">'
                        + '        <input name="partNumber' + itr + '"  type="text" id="partNumber' + itr + '" width="100%"   class="form-control positivefloat" data-itra="' + itr + '" data-id="' + itr + '"/>'
                        + '    </td>'
                        + '    <td colspan="1" class="' + hide_type + '">'
                        + '        <input name="vehicleType' + itr + '"   type="hidden" id="vehicleType' + itr + '" width="100%"   class="vehicleTypes"vehicleTypes data-itra="' + itr + '" data-id="' + itr + '"/>'
                        + '    </td>'
                        + '    <td colspan="2" class="' + hide_company + '">'
                        + '        <input name="company' + itr + '"   type="hidden" id="company' + itr + '" width="100%"   class="companyproduces" data-itra="' + itr + '" data-id="' + itr + '"/>'
                        + '    </td>'
                        + '    <td colspan="1" class="' + hide_weight + '">'
                        + '        <input name="weight' + itr + '"  type="text" id="weight' + itr + '" width="100%"   class="form-control positivefloat" data-itra="' + itr + '" data-id="' + itr + '"/>'
                        + '    </td>'
                        + '      <td colspan="1" class="' + hide_origin + '">'
                        + '        <input name="origin' + itr + '"  type="text" id="origin' + itr + '" width="100%"   class="form-control" data-itra="' + itr + '" data-id="' + itr + '"/>'
                        + '    </td>'
                        + '    <td colspan="1" class="' + hide_hscode + '">'
                        + '        <input name="hscode' + itr + '"  type="text" id="hscode' + itr + '" width="100%"   class="form-control positivefloat" data-itra="' + itr + '" data-id="' + itr + '"/>'
                        + '    </td>'
                        + '    <td colspan="1" class="' + hide_expire + '">'
                        + '        <div class="form-group" style="font-size:13px">'
                        + '            <label class="color-black">'
                        + '                <input value="0"  class="power" data-itra="' + itr + '" name="power' + itr + '" checked="checked"  type="radio"  data-id="' + itr + '"/>'
                        + '                نعم </label>'
                        + '           <label class="color-black">'
                        + '                <input value="1"  class="power"  data-itra="' + itr + '" name="power' + itr + '" type="radio" data-id="' + itr + '"/>'
                        + '                لا </label>'
                        + '        </div>'
                        + '    </td>'
                        + '    <td colspan="1" class="power' + itr + ' ' + hide_expire + '">'
                        + '        <input name="ProductionDate' + itr + '"   type="text" id="ProductionDate' + itr + '" width="100%"    class="form-control awdatepicker" data-date-format="yyyy-mm-dd"   data-itra="' + itr + '" data-id="' + itr + '"/>'
                        + '    </td>'
                        + '    <td colspan="1" class="power' + itr + ' ' + hide_expire + '">'
                        + '        <input name="expiry' + itr + '"  type="text" id="expiry' + itr + '" width="100%"   class="form-control positivefloat" data-itra="' + itr + '" data-id="' + itr + '"/>'
                        + '    </td>'
                        + '<td colspan="1" class="' + hide_grantduration + '">'
                        + '    <input name="grantduration' + itr + '"  type="text" id="grantduration' + itr + '" width="100%" class="form-control positivefloat" data-itra="' + itr + '" data-id="' + itr + '" />'
                        + '</td>'
                        + '<td colspan="1" class="' + hide_online + '">'
                        + '<div class="form-group" style="font-size:13px">'
                        + '  <label class="color-black">'
                        + '      <input value="1" data-itra="' + itr + '" name="onlinepro' + itr + '" checked="checked" type="radio" data-id="' + itr + '" />'
                        + '      نعم </label>'
                        + '  <label class="color-black">'
                        + '      <input value="0" data-itra="' + itr + '" name="onlinepro' + itr + '" type="radio" data-id="' + itr + '" />'
                        + '      لا </label>'
                        + '</div>'
                        + '</td>'
                        + '<td colspan="1" class="' + hide_minappear + '">'
                        + '    <input name="minappearonline' + itr + '"  type="text" id="minappearonline' + itr + '" width="100%" class="form-control positivefloat" data-itra="' + itr + '" data-id="' + itr + '" />'
                        + '</td>'
                        + '    <td colspan="1" class="' + hide_sellpercent + '">'
                        + '        <div class="form-group" style="font-size:13px">'
                        + '            <label class="color-black">'
                        + '                <input value="0"  class="sellpercenttype" data-itra="' + itr + '" name="sellpercenttype' + itr + '" checked="checked"  type="radio"  data-id="' + itr + '"/>'
                        + '                إضافة </label>'
                        + '           <label class="color-black">'
                        + '                <input value="1"  class="sellpercenttype"  data-itra="' + itr + '" name="sellpercenttype' + itr + '" type="radio" data-id="' + itr + '"/>'
                        + '                خصم </label>'
                        + '        </div>'
                        + '    </td>'

                        + '<td colspan="1" class="sellpercentadd' + itr + ' ' + hide_sellpercent + '">'
                        + '     <input name="selladdpercent' + itr + '"  type="text" id="selladdpercent' + itr + '" width="100%" class="form-control positivefloat" data-itra="' + itr + '" data-id="' + itr + '" />'
                        + '</td>'
                        + '<td colspan="1" class="sellpercentdiscount' + itr + '" style="display:none;">'
                        + '     <input name="selldiscountpercent' + itr + '"  type="text" id="selldiscountpercent' + itr + '" width="100%" class="form-control positivefloat" data-itra="' + itr + '" data-id="' + itr + '" />'
                        + ' </td>'
                        + '<td colspan="1" class="' + hide_buydiscount + '">'
                        + '     <input name="buydiscountpercent' + itr + '"  type="text" id="buydiscountpercent' + itr + '" width="100%" class="form-control positivefloat" data-itra="' + itr + '" data-id="' + itr + '" />'
                        + '</td>'

                        + '   </tr>'


                        + '  </table>'

                        + '  <!------------------------ وحدة قياس---------------------->'
                        + '          <div id="addUnitsDiv' + itr + '_1" style=" " class="' + hidden_mesurunit + '">'
                        + '            <table id="unitsTable' + itr + '" class="table" style="'
                        + '                   width: 98%;'
                        + '                box-shadow: 0px 3px 5px #a59f9f, -3px 0px 5px #fff;'
                        + '               background-color: #999;">'
                        + '           <tr style="display: none">'
                        + '              <td>'
                        + '                <div class="form-group">'
                        + '                <label class="col-lg-4 control-label">اسم وحدة القياس</label>'
                        + '               <div class="col-lg-8">'
                        + '                 <select name="productunit' + itr + '_1" id="productunit' + itr + '_1" data-placeholder="اختر"  class="select2 wdt100 chosenproduct" >'
                        + '                   <option value="-1">اختر وحدة القياس</option>'
                        + ''//get units
                        + '    </select>'
                        + ' </div>'
                        + '</div>'
                        + '  </td>'
                        + '  <td>'
                        + '     <div class="form-group">'
                        + '  <label class="col-lg-4 control-label">عدد الوحدات</label>'
                        + '  <div class="col-lg-8">'
                        + '     <input name="productnumber' + itr + '_1" id="productnumber' + itr + '_1" type="text" class="form-control numberinput" />'
                        + '  </div>'
                        + ' </div>'
                        + '   </td>'
                        + '   <td>'
                        + '      <a id="remove1_1" onClick="removeUnits(' + itr + ', 1);" class="removeUnits">X</a>'
                        + '   </td>'
                        + ' </tr>'
                        + ' </table>'
                        + '   <!--end unitsTable-->'
                        + '  </div>'
                        + ' <!--end productsTable -->'

                        + ' <div id="catUnitsDiv' + itr + '" style="display:none;">'

                        + '   </div>'

                        + '  </div>'
                        );

                initSelect2($('#clientid' + itr));

                $("#vehicleType" + itr).select2({
                    placeholder: "اختر",
                    multiple: false,
                    ajax: {
                        url: "vehicleType.php?do=vehicleTypes",
                        dataType: 'json',
                        data: function (term, page) {
                            return {
                                term: term, //search term
                                page_limit: 10, // page size
                            };
                        },
                        results: function (data) {
                            return {results: data};
                        }
                    },
                    formatResult: formatResultFatma,
                    initSelection: function (element, callback) {
                        var item = element.val().split(':');
                        var data = {id: item[0], text: item[1]};
                        callback(data);
                    }
                });


                $("#barcodeInTax" + itr).select2({
                    placeholder: "اختر",
                    multiple: false,
                    ajax: {
                        url: "eBillRequests.php?do=barcodeInTax",
                        dataType: 'json',
                        data: function (term, page) {
                              var itr = $(this).attr('data-itr');
                                 var TypeOfBarcodeInTax =  $('input[name="TypeOfBarcodeInTax'+itr+'"]:checked').val();
                                return {
                                    term: term, //search term
                                    TypeOfBarcodeInTax: TypeOfBarcodeInTax,
                                };
                        },
                        results: function (data) {
                            return {results: data};
                        }
                    },
                    formatResult: formatResultFatma,
                    initSelection: function (element, callback) {
                        var item = element.val().split(':');
                        var data = {id: item[0], text: item[1]};
                        callback(data);
                    }
                });

                $("#company" + itr).select2({
                    placeholder: "اختر",
                    multiple: false,
                    quietMillis: 100,
                    ajax: {
                        url: "companyproduces.php?do=companyproduces",
                        dataType: 'json',
                        data: function (term, page) {
                            return {
                                term: term, //search term
                                page_limit: 10, // page size
                            };
                        },
                        results: function (data) {
                            return {results: data};
                        }
                    },
                    formatResult: formatResultFatma,
                    initSelection: function (element, callback) {
                        var item = element.val().split(':');
                        var data = {id: item[0], text: item[1]};
                        callback(data);
                    }
                });
                $("#onlinecatid" + itr).select2({
                    placeholder: "اختر",
                    multiple: false,
                    quietMillis: 100,
                    ajax: {
                        url: "onlineCatController.php?do=getallSubFilters",
                        dataType: 'json',
                        data: function (term, page) {
                            return {
                                term: term, //search term
                                page_limit: 10, // page size
                            };
                        },
                        results: function (data) {
                            return {results: data};
                        }
                    },
                    formatResult: function (data) {
                        return data.text;
                    },
                    initSelection: function (element, callback) {
                        var item = element.val().split(':');
                        var data = {id: item[0], text: item[1]};
                        callback(data);
                    }
                });
                $("#searchfiltersid" + itr).select2({
                    placeholder: "اختر",
                    multiple: true,
                    quietMillis: 100,
                    ajax: {
                        url: "searchFiltersController.php?do=getallSubFilters",
                        dataType: 'json',
                        data: function (term, page) {
                            return {
                                term: term, //search term
                                page_limit: 10, // page size
                            };
                        },
                        results: function (data) {
                            return {results: data};
                        }
                    },
                    formatResult: function (data) {
                        return data.text;
                    },
                    initSelection: function (element, callback) {
                        var item = element.val().split(':');
                        var data = {id: item[0], text: item[1]};
                        callback(data);
                    }
                });
                $('select.select2_custom').select2();
                $('.awdatepicker').datepicker();
                $('.numberinput').forceNumeric();
                //alert(itr);
                $("#productItr").val(itr); //assign new iteration value
                //generateParcode(itr);
                $(".positivefloat").forcepositivefloat();

                var last_level = $('#level').val();
                if (typeof last_level !== 'undefined') {

                    last_level = last_level - 1;

                    var last_productCatId = $('#productCatId' + last_level + '').val();
                    $('#productCatId').val(last_productCatId);

                    //# fill buypricereal ,  buytotal , buyhalf , buypart
                    var productCatId_level = $('#level').val();
                    //console.log('level = '+productCatId_level);
                    var i, last_level;
                    for (i = 1; i <= productCatId_level; i++) {
                        if (i == productCatId_level) {
                            last_level = productCatId_level - 1;
                        }
                    }
                    var productCatId = $('#productCatId' + last_level + '').val();

                } else {
                    productCatId = catid;
                }
                $.post('productControllerAjax.php?do=get_prices', {productCatId: productCatId}, function (data) {
                    data = JSON.parse(data);
                    $('.buypricereal_precentage' + itr + '').val(data.buypricereal);
                    $('.buytotal_precentage' + itr + '').val(data.buytotal);
                    $('.buyhafe_precentage' + itr + '').val(data.buyhalf);
                    $('.buypart_precentage' + itr + '').val(data.buypart);
                });

                this_is.attr('data-rowadded', '1');
            }



        }, 500);

    });
    ////////////////////////////////////////////////////////////////////////
    //add category with modal

    $('.conformdel').click(function (e) {
        e.preventDefault();
        emptyModalForm();//clear inputs

        $('#catModal').modal('show');

    });

    $('.savemodel_barcode').on('click', function () {
        // do something…
        $('#myModa_barcode').modal('hide');
        var pos = $(this).attr('data-position');
        var id = $(this).attr('data-id');
        var itr = $(this).attr('data-itr');


        var newbarcod = document.getElementById("newbarcod").value;

        //	alert(pos+'&id='+id+'&newbarcod='+newbarcod);
        //window.location.href =pos+'&id='+id+'&newbarcod='+newbarcod;


        $.ajax({
            url: pos + '&id=' + id + '&newbarcod=' + newbarcod,
            type: "get",
            //data: {parent:parent, productCatName:productCatName, productCatDescription:productCatDescription},
            success: function (data) {
                if (data != "") {
                    document.getElementById("newbarcod").value = "";
                    $("#updatebarcod" + itr).html('')
                    document.getElementById("productbarcode" + itr).value = data;
                    //document.getElementById("productbarcode"+itr).value=data;
                }

            },
            error: function (request, status, error) {
                //alert(request);
                // $("#result").html('لقد حدث خطأ أثناء إجراء العملية');
            }
        });

    });



    //# m7md products form
    $('body').on('keyup', '.buy_price', function () {
        var ths_val = $(this).val();
        var ths_id = $(this).attr('data-id');

        var buypricereal = $('.buypricereal_precentage' + ths_id + '').val();
        var buytotal = $('.buytotal_precentage' + ths_id + '').val();
        var buyhalf = $('.buyhafe_precentage' + ths_id + '').val();
        var buypart = $('.buypart_precentage' + ths_id + '').val();
                var price4 = $('.price4_precentage' + ths_id + '').val() ?? 0;
                var price5 = $('.price5_precentage' + ths_id + '').val() ?? 0;
                var price6 = $('.price6_precentage' + ths_id + '').val() ?? 0;
                var price7 = $('.price7_precentage' + ths_id + '').val() ?? 0;
                var price8 = $('.price8_precentage' + ths_id + '').val() ?? 0;


        var b_pricereal = (((Number(buypricereal) * Number(ths_val)) / 100) - Number(ths_val)) * -1;
        var b_total = ((Number(buytotal) * Number(ths_val)) / 100) + Number(ths_val);
        var b_hafe = ((Number(buyhalf) * Number(ths_val)) / 100) + Number(ths_val);
        var b_part = ((Number(buypart) * Number(ths_val)) / 100) + Number(ths_val);
        var b_price4 = ((Number(price4) * Number(ths_val)) / 100) + Number(ths_val);
        var b_price5 = ((Number(price5) * Number(ths_val)) / 100) + Number(ths_val);
        var b_price6 = ((Number(price6) * Number(ths_val)) / 100) + Number(ths_val);
        var b_price7 = ((Number(price7) * Number(ths_val)) / 100) + Number(ths_val);
        var b_price8 = ((Number(price8) * Number(ths_val)) / 100) + Number(ths_val);

        $('.buy_pricereal' + ths_id + '').val(b_pricereal);
        $('.buy_total' + ths_id + '').val(b_total);
        $('.buy_hafe' + ths_id + '').val(b_hafe);
        $('.buy_part' + ths_id + '').val(b_part);
        $('.price4_' + ths_id + '').val(b_price4);
        $('.price5_' + ths_id + '').val(b_price5);
        $('.price6_' + ths_id + '').val(b_price6);
        $('.price7_' + ths_id + '').val(b_price7);
        $('.price8_' + ths_id + '').val(b_price8);

        /*    var productCatId_level = $('#level').val();
         console.log('level = '+productCatId_level);
         var i , last_level;
         for( i = 1 ;  i <= productCatId_level ;  i++){
         if( i == productCatId_level ){
         last_level =  productCatId_level - 1;
         }
         }
         var productCatId = $('#productCatId'+last_level+'').val();
         console.log('productCatId = '+productCatId);
         //# get buytotal , buyhalf , buypart
         $.post('productControllerAjax.php?do=get_prices',{ productCatId:productCatId },function(data){
         data = JSON.parse(data);

         var b_pricereal = ( ( Number(data.buypricereal) * Number(ths_val) ) /100) + Number(ths_val) ;
         var b_total = ( ( Number(data.buytotal) * Number(ths_val) ) /100) + Number(ths_val) ;
         var b_hafe  = ( ( Number(data.buyhalf)* Number(ths_val) )  /100) + Number(ths_val) ;
         var b_part  = ( ( Number(data.buypart) * Number(ths_val) ) /100) + Number(ths_val) ;
         // console.log('b_total = '+b_total);
         $('.buy_pricereal'+ths_id+'').val(b_pricereal);
         $('.buy_total'+ths_id+'').val(b_total);
         $('.buy_hafe'+ths_id+'').val(b_hafe);
         $('.buy_part'+ths_id+'').val(b_part);
         });*/



    });
    //# m7md products form //and fatma
    $('body').on('keyup', '[class*="buy_total"]', function () {//any class containing buy_total not only #buy_total1 as there is itrations
        var ths_val = $(this).val();
        var ths_id = $(this).attr('data-id');


        var buyhalf = $('.buyhafe_precentage' + ths_id + '').val();
        var buypart = $('.buypart_precentage' + ths_id + '').val();



        var b_hafe = ((Number(buyhalf) * Number(ths_val)) / 100) + Number(ths_val);
        var b_part = ((Number(buypart) * Number(ths_val)) / 100) + Number(ths_val);


        $('.buy_hafe' + ths_id + '').val(b_hafe);
        $('.buy_part' + ths_id + '').val(b_part);
        $('.price4_' + ths_id + '').val(b_part);
        $('.price5_' + ths_id + '').val(b_part);
        $('.price6_' + ths_id + '').val(b_part);
        $('.price7_' + ths_id + '').val(b_part);
        $('.price8_' + ths_id + '').val(b_part);

        /*    var productCatId_level = $('#level').val();
         console.log('level = '+productCatId_level);
         var i , last_level;
         for( i = 1 ;  i <= productCatId_level ;  i++){
         if( i == productCatId_level ){
         last_level =  productCatId_level - 1;
         }
         }
         var productCatId = $('#productCatId'+last_level+'').val();
         console.log('productCatId = '+productCatId);
         //# get buytotal , buyhalf , buypart
         $.post('productControllerAjax.php?do=get_prices',{ productCatId:productCatId },function(data){
         data = JSON.parse(data);

         var b_pricereal = ( ( Number(data.buypricereal) * Number(ths_val) ) /100) + Number(ths_val) ;
         var b_total = ( ( Number(data.buytotal) * Number(ths_val) ) /100) + Number(ths_val) ;
         var b_hafe  = ( ( Number(data.buyhalf)* Number(ths_val) )  /100) + Number(ths_val) ;
         var b_part  = ( ( Number(data.buypart) * Number(ths_val) ) /100) + Number(ths_val) ;
         // console.log('b_total = '+b_total);
         $('.buy_pricereal'+ths_id+'').val(b_pricereal);
         $('.buy_total'+ths_id+'').val(b_total);
         $('.buy_hafe'+ths_id+'').val(b_hafe);
         $('.buy_part'+ths_id+'').val(b_part);
         });*/



    });
    //# convert prices
    $('body').on('keyup', '.precentages', function () {
        var ths_val = $(this).val();
        var ths_id = $(this).attr('data-id');
        var productBuyPrice = $('#productBuyPrice' + ths_id + '').val();
        var ths_type = $(this).attr('data-type');

        switch (ths_type) {
            case 'pricereal':
                var b_pricereal = (((Number(ths_val) * Number(productBuyPrice)) / 100) - Number(productBuyPrice)) * -1;
                $('.buy_pricereal' + ths_id + '').val(b_pricereal);
                break;
            case 'buytotal':
                var b_pricereal = (((Number(ths_val) * Number(productBuyPrice)) / 100) + Number(productBuyPrice));
                $('.buy_total' + ths_id + '').val(b_pricereal);
                break;
            case 'buyhalf':
                var b_pricereal = (((Number(ths_val) * Number(productBuyPrice)) / 100) + Number(productBuyPrice));
                $('.buy_hafe' + ths_id + '').val(b_pricereal);
                break;
            case 'buypart':
                var b_pricereal = (((Number(ths_val) * Number(productBuyPrice)) / 100) + Number(productBuyPrice));
                $('.buy_part' + ths_id + '').val(b_pricereal);
                break;
            default:
                break;

        }
    });


    //# convert precentages
    $('body').on('keyup', '.prices', function () {
        var ths_val = $(this).val();
        var ths_id = $(this).attr('data-id');
        var productBuyPrice = $('#productBuyPrice' + ths_id + '').val();
        var ths_type = $(this).attr('data-type');


        switch (ths_type) {
            case 'pricereal':
                if (productBuyPrice == '') {
                    b_pricereal = 0;
                } else {
                    var b_pricereal = ((Number(ths_val) - Number(productBuyPrice)) * 100) / Number(productBuyPrice);
                    b_pricereal = b_pricereal;//.toFixed(2);
                }
                $('.buypricereal_precentage' + ths_id + '').val(b_pricereal);
                break;
            case 'buytotal':
                if (productBuyPrice == '') {
                    b_pricereal = 0;
                } else {
                    var b_pricereal = ((Number(ths_val) - Number(productBuyPrice)) * 100) / Number(productBuyPrice);
                    b_pricereal = parseFloat(b_pricereal);//.toFixed(2);
                }
                $('.buytotal_precentage' + ths_id + '').val(b_pricereal.toFixed(2));
                break;
            case 'buyhalf':
                if (productBuyPrice == '') {
                    b_pricereal = 0;
                } else {
                    var b_pricereal = ((Number(ths_val) - Number(productBuyPrice)) * 100) / Number(productBuyPrice);
                    b_pricereal = parseFloat(b_pricereal);//.toFixed(2);
                }
                $('.buyhafe_precentage' + ths_id + '').val(b_pricereal.toFixed(2));
                break;
            case 'buypart':
                if (productBuyPrice == '') {
                    b_pricereal = 0;
                } else {
                    var b_pricereal = ((Number(ths_val) - Number(productBuyPrice)) * 100) / Number(productBuyPrice);
                    b_pricereal = parseFloat(b_pricereal);//.toFixed(2);
                }
                $('.buypart_precentage' + ths_id + '').val(b_pricereal.toFixed(2));
                break;
            case 'price4':
                if (productBuyPrice == '') {
                    b_pricereal = 0;
                } else {
                    var b_pricereal = ((Number(ths_val) - Number(productBuyPrice)) * 100) / Number(productBuyPrice);
                    b_pricereal = parseFloat(b_pricereal);//.toFixed(2);
                }
                $('.price4_precentage' + ths_id + '').val(b_pricereal.toFixed(2));
                break;
            case 'price5':
                if (productBuyPrice == '') {
                    b_pricereal = 0;
                } else {
                    var b_pricereal = ((Number(ths_val) - Number(productBuyPrice)) * 100) / Number(productBuyPrice);
                    b_pricereal = parseFloat(b_pricereal);//.toFixed(2);
                }
                $('.price5_precentage' + ths_id + '').val(b_pricereal.toFixed(2));
                break;
            case 'price6':
                if (productBuyPrice == '') {
                    b_pricereal = 0;
                } else {
                    var b_pricereal = ((Number(ths_val) - Number(productBuyPrice)) * 100) / Number(productBuyPrice);
                    b_pricereal = parseFloat(b_pricereal);//.toFixed(2);
                }
                $('.price6_precentage' + ths_id + '').val(b_pricereal.toFixed(2));
                break;
            case 'price7':
                if (productBuyPrice == '') {
                    b_pricereal = 0;
                } else {
                    var b_pricereal = ((Number(ths_val) - Number(productBuyPrice)) * 100) / Number(productBuyPrice);
                    b_pricereal = parseFloat(b_pricereal);//.toFixed(2);
                }
                $('.price7_precentage' + ths_id + '').val(b_pricereal.toFixed(2));
                break;
            case 'price8':
                if (productBuyPrice == '') {
                    b_pricereal = 0;
                } else {
                    var b_pricereal = ((Number(ths_val) - Number(productBuyPrice)) * 100) / Number(productBuyPrice);
                    b_pricereal = parseFloat(b_pricereal);//.toFixed(2);
                }
                $('.price8_precentage' + ths_id + '').val(b_pricereal.toFixed(2));
                break;
            default:
                break;

        }
    });

    //# update data from show page .
    var focusInVal = '';//old value
    $('body').on('focusin', '.m_product', function () {
        focusInVal = $(this).val();
    });
    $('body').on('focusout', '.m_product', function () {
        var pro_id = $(this).attr('data-id');
        var type = $(this).attr('data-type');
        var isOptic = $(this).attr('data-isOptic');
        var tr = $(this).closest('tr');
        var changeBuyPriceChangeSellInProductCtrl = $('#changeBuyPriceChangeSellInProductCtrl').val();

        var columupdated;
        var columupdatedvalue = $(this).val();


        switch (type) {
            case 'name':
                var pro_name = $(this).val();
                columupdated = 'الاسم : ';
                break;
            case 'allprice':
                var pro_allprice = $(this).val();
                if ($(this).attr('data-editOther') == 1) {
                    var pro_halfprice = $(this).val();
                    var pro_unitPrice = $(this).val();
                    tr.find('#halfpriceNew_' + pro_id + '').val(pro_allprice);//we use this as we may have same id for 2 elements one with data-optic=0 and data-optic=2
                    tr.find('#unitPriceNew_' + pro_id + '').val(pro_allprice);//we use this as we may have same id for 2 elements one with data-optic=0 and data-optic=2
                    //                    $('#halfpriceNew_' + pro_id + '').val(pro_allprice);
                    //                    $('#unitPriceNew_' + pro_id + '').val(pro_allprice);
                }
                columupdated = 'سعر الجمله : ';
                break;
            case 'halfprice':
                var pro_halfprice = $(this).val();
                columupdated = 'سعر النصف جمله : ';
                break;
            case 'unitPrice':
                var pro_unitPrice = $(this).val();
                columupdated = 'سعر التجزئه :';
                break;
            case 'buyprice':
                var pro_buyprice = $(this).val();
                columupdated = 'سعر الشراء : ';
                break;
        }
        if (typeof pro_name === "undefined") {
            pro_name = ''
        }
        if (typeof pro_allprice === "undefined") {
            pro_allprice = ''
        }
        if (typeof pro_halfprice === "undefined") {
            pro_halfprice = ''
        }
        if (typeof pro_unitPrice === "undefined") {
            pro_unitPrice = ''
        }
        if (typeof pro_buyprice === "undefined") {
            pro_buyprice = ''
        }

        $("#columupdated").html(columupdated);
        $("#columupdatedvalue").html(columupdatedvalue);


        $.post('productControllerAjax.php?do=m_productUpdate', {pro_id: pro_id, type: type, value: columupdatedvalue, isOptic: isOptic}, function (data) {
            // console.log(data);
            //$('#sucessmodel').modal('show');
        });





        var newBuyPrice = Number(columupdatedvalue);
        var oldBuyPrice = Number(focusInVal);
        if (type == "buyprice" && changeBuyPriceChangeSellInProductCtrl != 0 && newBuyPrice != oldBuyPrice) {//when change buyprice change sell prices too
            var sellTypesArr = ['allprice', 'halfprice', 'unitPrice'];
            var sellTypesArrInputsIds = ['allpriceNew_' + pro_id, 'halfpriceNew_' + pro_id, 'unitPriceNew_' + pro_id];

            for (var i = 0; i < sellTypesArr.length; i++) {
                type = sellTypesArr[i];
                var oldSellVal = Number(tr.find('#' + sellTypesArrInputsIds[i]).val());//we use this as we may have same id for 2 elements one with data-optic=0 and data-optic=2
                var newSellVal = 0;
                if (changeBuyPriceChangeSellInProductCtrl == 1) {//by value
                    var diff = newBuyPrice - oldBuyPrice;
                    newSellVal = oldSellVal + diff;
                }
                if (changeBuyPriceChangeSellInProductCtrl == 2) {//by percentage
                    var percentage = newBuyPrice / oldBuyPrice;
                    newSellVal = (oldSellVal * percentage).toFixed(2);
                }
                updateSellPriceAjax_withBuyChange(pro_id, type, newSellVal, isOptic, sellTypesArrInputsIds[i], tr);
            }
        }
    });
    function updateSellPriceAjax_withBuyChange(pro_id, type, newSellVal, isOptic, sellInputsId, tr) {
        tr.find('#' + sellInputsId).first().attr('disabled', 'disabled');
        $.post('productControllerAjax.php?do=m_productUpdate', {pro_id: pro_id, type: type, value: newSellVal, isOptic: isOptic}, function (data) {
            tr.find('#' + sellInputsId).first().val(newSellVal);//we use this as we may have same id for 2 elements one with data-optic=0 and data-optic=2
            tr.find('#' + sellInputsId).first().removeAttr('disabled');
        });
    }

    //update sell prices if buy price updated in edit
    //    $('body').on('focusout', '#productBuyPrice1', function () {
    //        var changeBuyPriceChangeSellInProductCtrl = $('#changeBuyPriceChangeSellInProductCtrl').val();
    //        var oldBuyPrice = Number($('#productBuyPrice1Old').val());
    //        var newBuyPrice = Number($(this).val());
    //        if (changeBuyPriceChangeSellInProductCtrl != 0 && oldBuyPrice != newBuyPrice) {
    //            var sellTypesArrInputsIds = ['productSellAllPrice', 'productSellHalfPrice', 'productSellUnitPrices'];
    //            for (var i = 0; i < sellTypesArrInputsIds.length; i++) {
    //                console.log('fatmaaaaaaa');
    //                console.log(sellTypesArrInputsIds[i]);
    //                var oldSellVal = Number($('#' + sellTypesArrInputsIds[i]).val());
    //                var newSellVal = 0;
    //                if (changeBuyPriceChangeSellInProductCtrl == 1) {//by value
    //                    var diff = newBuyPrice - oldBuyPrice;
    //                    newSellVal = oldSellVal + diff;
    //                }
    //                if (changeBuyPriceChangeSellInProductCtrl == 2) {//by percentage
    //                    var percentage = newBuyPrice / oldBuyPrice;
    //                    newSellVal = (oldSellVal * percentage).toFixed(2);
    //                }
    //
    //                $('#' + sellTypesArrInputsIds[i]).val(newSellVal);
    //            }
    //        }
    //    });

    //# update productCat data from show page .
    $('body').on('change', '.m_productCat', function () {
        var pro_catid = $(this).val();
        var isOptic = $(this).attr('data-isOptic');
        //alert('pro_catid = ' + pro_catid);
        var pro_id = $(this).attr('data-id');

        $.post('productControllerAjax.php?do=m_productUpdate', {pro_id: pro_id, type: 'pro_catid', value: pro_catid, isOptic: isOptic}, function (data) {
            console.log(data);
        });
    });

    //# update data from show page .
    $('body').on('focusout', '.m_productNew', function () {
        var irt = $(this).data('itra')
        var pro_id = $(this).attr('data-id');
        var type = $(this).attr('data-type');
        var isOptic = $(this).attr('data-isOptic');
        var tr = $(this).closest('tr');

        var columupdated;
        var columupdatedvalue = $(this).val();

        switch (type) {
            case 'nameNew':
                var pro_name = $(this).val();
                columupdated = 'الاسم : ';
                break;
            case 'allpriceNew':
                //# if allprice change then change all prices [ halfprice , unitPrice ] .
                var pro_allprice = $(this).val();

                if ($(this).attr('data-editOther') == 1) {
                    var pro_halfprice = $(this).val();
                    var pro_unitPrice = $(this).val();
                    tr.find('#halfpriceNew_' + pro_id + '').val(pro_allprice);//we use this as we may have same id for 2 elements one with data-optic=0 and data-optic=2
                    tr.find('#unitPriceNew_' + pro_id + '').val(pro_allprice);//we use this as we may have same id for 2 elements one with data-optic=0 and data-optic=2
                    //                    $('#halfpriceNew_' + pro_id + '').val(pro_allprice);
                    //                    $('#unitPriceNew_' + pro_id + '').val(pro_allprice);
                }

                columupdated = 'سعر الجمله : ';
                break;
            case 'halfpriceNew':
                var pro_halfprice = $(this).val();
                columupdated = 'سعر النصف جمله : ';
                break;
            case 'unitPriceNew':
                var pro_unitPrice = $(this).val();
                columupdated = 'سعر التجزئه :';
                break;
            case 'buypriceNew':
                var pro_buyprice = $(this).val();
                columupdated = 'سعر الشراء : ';
                break;


            case 'DescriptionNew':
                var pro_Description = $(this).val();
                columupdated = 'الوصف : ';
                var username = $('#pro_username').val();
                break;

            case 'online':
                var pro_online = $(this).val();
                columupdated = 'معلومات تنزيل : ';
                break;
        }
        if (typeof pro_name === "undefined") {
            pro_name = ''
        }
        if (typeof pro_allprice === "undefined") {
            pro_allprice = ''
        }
        if (typeof pro_halfprice === "undefined") {
            pro_halfprice = ''
        }
        if (typeof pro_unitPrice === "undefined") {
            pro_unitPrice = ''
        }
        if (typeof pro_buyprice === "undefined") {
            pro_buyprice = ''
        }
        if (typeof pro_Image === "undefined") {
            pro_Image = ''
        }
        if (typeof pro_Description === "undefined") {
            pro_Description = ''
        }
        if (typeof pro_online === "undefined") {
            pro_online = ''
        }
        console.log('pro_allprice' + pro_allprice);
        console.log('pro_halfprice' + pro_halfprice);
        console.log('pro_unitPrice' + pro_unitPrice);



        $.post('productControllerAjax.php?do=m_productUpdate', {pro_id: pro_id, type: type, value: columupdatedvalue, username: username, isOptic: isOptic}, function (data) {
            // alert(data)
            // console.log(data);
            //$('#sucessmodel').modal('show');
        });
    });
    //azmy
    $('.ImageNew').change(function () {
        var irt = $(this).data('itra')
        var itracolum = $(this).data('itracolum')
        var pro_id = $('#pro_id_' + irt).val();
        var formname = $('#Image_' + irt + '_' + itracolum).attr('name');
        var username = $('#pro_username').val();
        var photo = new FormData($("#form1")[0]);
        photo.append('file_name', formname);
        photo.append('pro_id', pro_id);
        photo.append('itracolum', itracolum);
        photo.append('username', username);

        $.ajax({
            url: "productControllerAjax.php?do=A_productUpdate",
            type: "POST",
            data: photo,
            async: false,
            cache: false,
            contentType: false,
            processData: false,
            success: function (data) {
                $('.iamge_' + irt + '_' + itracolum).removeAttr('src');
                $('.iamge_' + irt + '_' + itracolum).attr('src', '../views/default/images/product_image/' + data);


            }
        });

    });
    //azmy





    //# start tarek 22-07-2018


    $('.changeBtn').click(function () {

        var operationChange = $('#operationChange').val();
        var buypriceChange = Number($('#buypriceChange').val()); //# سعر الشراء
        var allpriceChange = Number($('#allpriceChange').val()); //# سعر الجملة
        var halfpriceChange = Number($('#halfpriceChange').val()); //# سعر نصف جملة
        var unitPriceChange = Number($('#unitPriceChange').val()); //# سعر التجزئة

        console.log('operationChange = ' + operationChange);
        if (operationChange == 1) {
            //# نسبة
            //# سعر الشراء
            if (buypriceChange != '') {

                var buypriceNew_len = $('.buypriceNew').length;
                for (var i = 1; i <= buypriceNew_len; i++) {
                    var row_val = Number($('.buyPrice_' + i + '').val()); //# get row value .
                    var new_val = (buypriceChange / 100) * row_val; //# calculate precentage of this value .
                    new_val = new_val + row_val;
                    $('.buyPrice_' + i + '').val(new_val);  //# assign new value to row .
                    var row_id = $('.buyPrice_' + i + '').attr('id');
                    console.log('row_id = ' + row_id);
                    //# call this function .
                    changeVals(row_id);
                }
            }

            //# سعر الجملة
            if (allpriceChange != '') {

                var allpriceNew_len = $('.allpriceNew').length;
                for (var i = 1; i <= allpriceNew_len; i++) {
                    var row_val = Number($('.allprice_' + i + '').val()); //# get row value .
                    var new_val = (allpriceChange / 100) * row_val; //# calculate precentage of this value .
                    new_val = new_val + row_val;
                    $('.allprice_' + i + '').val(new_val);  //# assign new value to row .
                    var row_id = $('.allprice_' + i + '').attr('id');
                    console.log('row_id = ' + row_id);
                    //# call this function .
                    changeVals(row_id);
                }
            }

            //# سعر نصف جملة
            if (halfpriceChange != '') {

                var halfpriceNew_len = $('.halfpriceNew').length;
                for (var i = 1; i <= halfpriceNew_len; i++) {
                    var row_val = Number($('.halfprice_' + i + '').val()); //# get row value .
                    var new_val = (halfpriceChange / 100) * row_val; //# calculate precentage of this value .
                    new_val = new_val + row_val;
                    $('.halfprice_' + i + '').val(new_val);  //# assign new value to row .
                    var row_id = $('.halfprice_' + i + '').attr('id');
                    console.log('row_id = ' + row_id);
                    //# call this function .
                    changeVals(row_id);
                }
            }

            //# سعرالتجزئة
            if (unitPriceChange != '') {

                var unitPriceNew_len = $('.unitPriceNew').length;
                for (var i = 1; i <= unitPriceNew_len; i++) {
                    var row_val = Number($('.unitPrice_' + i + '').val()); //# get row value .
                    var new_val = (unitPriceChange / 100) * row_val; //# calculate precentage of this value .
                    new_val = new_val + row_val;
                    $('.unitPrice_' + i + '').val(new_val);  //# assign new value to row .
                    var row_id = $('.unitPrice_' + i + '').attr('id');
                    console.log('row_id = ' + row_id);
                    //# call this function .
                    changeVals(row_id);
                }
            }
        } else {
            //# مباشر
            //# سعر الشراء
            if (buypriceChange != '') {
                $('.buypriceNew').each(function (index, e) {
                    var id = $(this).attr('data-id');
                    var newPrice = Number($('#buypriceNew_' + id).val()) + buypriceChange;
                    $('#buypriceNew_' + id).val(newPrice);
                    var row_id = $(this).attr('id');
                    //# call this function .
                    changeVals(row_id);
                });
            }

            //# سعر الجملة
            if (allpriceChange != '') {
                $('.allpriceNew').each(function (index, e) {
                    var id = $(this).attr('data-id');
                    var newPrice = Number($('#allpriceNew_' + id).val()) + allpriceChange;
                    $('#allpriceNew_' + id).val(newPrice);
                    var row_id = $(this).attr('id');
                    //# call this function .
                    changeVals(row_id);
                });
            }

            //# سعر نصف جملة
            if (halfpriceChange != '') {
                $('.halfpriceNew').each(function (index, e) {
                    var id = $(this).attr('data-id');
                    var newPrice = Number($('#halfpriceNew_' + id).val()) + halfpriceChange;
                    $('#halfpriceNew_' + id).val(newPrice);
                    var row_id = $(this).attr('id');
                    //# call this function .
                    changeVals(row_id);
                });
            }

            //# سعرالتجزئة
            if (unitPriceChange != '') {
                $('.unitPriceNew').each(function (index, e) {
                    var id = $(this).attr('data-id');
                    var newPrice = Number($('#unitPriceNew_' + id).val()) + unitPriceChange;
                    $('#unitPriceNew_' + id).val(newPrice);
                    var row_id = $(this).attr('id');
                    //# call this function .
                    changeVals(row_id);
                });
            }

        }
    });

    function changeVals(row_id) {
        var pro_id = $('#' + row_id + '').attr('data-id');
        var type = $('#' + row_id + '').attr('data-type');
        var isOptic = $('#' + row_id + '').attr('data-isOptic');

        switch (type) {
            case 'nameNew':
                var pro_name = $('#' + row_id + '').val();
                //columupdated = 'الاسم : ';
                break;
            case 'allpriceNew':
                var pro_allprice = $('#' + row_id + '').val();
                //columupdated = 'سعر الجمله : ';
                break;
            case 'halfpriceNew':
                var pro_halfprice = $('#' + row_id + '').val();
                //columupdated = 'سعر النصف جمله : ';
                break;
            case 'unitPriceNew':
                var pro_unitPrice = $('#' + row_id + '').val();
                //columupdated = 'سعر التجزئه :';
                break;
            case 'buypriceNew':
                var pro_buyprice = $('#' + row_id + '').val();
                //columupdated = 'سعر الشراء : ';
                break;
        }
        if (typeof pro_name === "undefined") {
            pro_name = ''
        }
        if (typeof pro_allprice === "undefined") {
            pro_allprice = ''
        }
        if (typeof pro_halfprice === "undefined") {
            pro_halfprice = ''
        }
        if (typeof pro_unitPrice === "undefined") {
            pro_unitPrice = ''
        }
        if (typeof pro_buyprice === "undefined") {
            pro_buyprice = ''
        }
        console.log('pro_buyprice' + pro_buyprice);
        console.log('pro_allprice' + pro_allprice);
        console.log('pro_halfprice' + pro_halfprice);
        console.log('pro_unitPrice' + pro_unitPrice);



        $.post('productControllerAjax.php?do=m_productUpdate', {pro_id: pro_id, type: type, value: $('#' + row_id + '').val(), isOptic: isOptic}, function (data) {
            // console.log(data);
            //$('#sucessmodel').modal('show');


        });

    }

    $('#operationChange').on('change', function () {
        var thsVal = $(this).val();
        if (thsVal != '') {

            $('.changeBtn').removeAttr('disabled');
        } else {

            $('.changeBtn').attr('disabled');
        }
    });
    //# end tarek 22-07-2018
});



function emptyModalForm() {

    $('#catModal').find(':input').each(function () {
        var type = this.type, tag = this.tagName.toLowerCase();
        if (type == 'text' || type == 'password' || tag == 'textarea')
            this.value = '';
        else if (type == 'checkbox' || type == 'radio')
            this.checked = false;
        else if (tag == 'select')
            this.value = '-1';
    })

}


function checkbarcode(barcod, itr) {

    //alert("productControllerAjax.php?do=checkbarcode&barcod="+barcod);
    $.ajax({
        url: "productControllerAjax.php?do=checkbarcode&barcod=" + barcod,
        type: "get",
        success: function (data) {
            //alert(data)
            if (data == 1) {
                // alert('oldbarcod'+oldbarcod);
                alert('هذا الباركود موجود من قبل');
                $("#parcode" + itr).val('');

                //$('#parcode' + itr).focus();

            } else if (data == 2) {


            }

        }
    });
}


function checkbarcodewithid(barcod, itr) {
    //alert('productId'+$("#productId").val())
    var productId = $("#productId").val();
    $.ajax({
        url: "productControllerAjax.php?do=checkbarcodewithid&id=" + productId + "&barcod=" + barcod,
        type: "get",
        success: function (data) {
            //	alert(data);
            if (data == 1) {
                alert('هذا الباركود موجود من قبل');
                $("#parcode" + itr).val('');

                //$('#parcode' + itr).focus();
                return false;
            } else if (data == 2) {

            }

        }
    });
}

$('[id^="proUnitParcode"]').live('keypress', function (e) {
    if (e.which == 13) { //Enter
        e.preventDefault();
        //get pro itr//unitsTable1
        var proItr = $(this).parents('table').first().attr('id').substring(10);
        var val = $(this).val();
        if (val != "") {
            addUnits(proItr);
        }
        //unitsItr3

        return false
    }
})
function checkUnitbarcode(barcod, itr) {
    $.ajax({
        url: "productControllerAjax.php?do=checkUnitbarcode&barcod=" + barcod,
        type: "get",
        success: function (data) {
            //alert(data)
            if (data == 1) {
                // alert('oldbarcod'+oldbarcod);
                alert('هذا الباركود موجود من قبل');
                $("#proUnitParcode" + itr).val('');
            }

        }
    });
}

function checkUnitbarcodewithid(barcod, unitIditr, unitItr) {
    var id = $('#productunitid' + unitIditr).val();
    $.ajax({
        url: "productControllerAjax.php?do=checkUnitbarcodewithid&id=" + id + "&barcod=" + barcod,
        type: "get",
        success: function (data) {
            if (data == 1) {
                alert('هذا الباركود موجود من قبل');
                $("#proUnitParcode" + unitItr).val('');
                return false;
            }
        }
    });
}

function conformdel_barcode(id) {
    // this for add barcod to product

    //e.preventDefault();
    //alert(id);
    var elemid = $('.conformdel_barcode' + id).attr("data-id");
    // alert(elemid);
    var elemposition = $('.conformdel_barcode' + id).attr("data-position");
    var elemitr = $('.conformdel_barcode' + id).attr("data-itr");

    $("#myModa_barcode").find(".savemodel_barcode").attr('data-id', elemid);
    $("#myModa_barcode").find(".savemodel_barcode").attr('data-position', elemposition);
    $("#myModa_barcode").find(".savemodel_barcode").attr('data-itr', elemitr);
    $('#myModa_barcode').modal('show');
}


function check_for_selected_element_type(selectedId, selectedClass) {
    //الفكرة: التصنيف ياإما يبقى تحته تصنيفات ياإما منتجات وليس الإثنين معاً.

    $.ajax({
        url: "productControllerAjax.php?do=isParent&id=" + selectedId,
        type: "get",
        success: function (datau) {

            data = datau.replace(/(\r\n|\n|\r)/gm, "");
            var getback = datau;

            if (data === "isParent")//if this category has parent categories
            {
                if (selectedClass == "branch") //user is selecting a parent category
                {
                    //alert("1");
                    $("#addProduct").css("display", "none"); //hide add product button
                    $("#addParent").css("display", "block"); //show add product category button
                    //alert("2");
                }
            } else if (data === 'isNotParent')//if this category has not parent categories
            {

                //check if this category has products associated with it, if not so it will be applicable to add product OR a category.
                $.ajax({
                    url: "productControllerAjax.php?do=hasProducts&id=" + selectedId,
                    type: "get",
                    success: function (datacx) {
                        //alert('datac'+datacx);
                        datac = datacx.replace(/(\r\n|\n|\r)/gm, "");
                        if (datac == "yes") {
                            // alert(datac);
                            $("#addProduct").css("display", "block"); //show add product button
                            $("#addParent").css("display", "none"); //hide add product category button
                        } else if (datac == "no") {
                            $("#addParent").css("display", "block"); //show add product category button
                            $("#addProduct").css("display", "block"); //show add product button
                        }
                    },
                    error: function () {
                        $("#productEdit").html('لقد حدث خطأ أثناء إجراء العملية');
                    }
                });
            }
        },
        error: function () {
            $("#productEdit").html('لقد حدث خطأ أثناء إجراء العملية');
        }
    });
}


function addParent() {
    $("#addProduct").css("display", "none"); //hide add product button
    // var selectedId = $("#selectedId").val();
    // var selectedClass = $("#selectedClass").val();
    var selectedClass = "branch";
    var selectedId = $("#productCatId0").val();

    //alert("selectedId: "+selectedId);
    $.ajax({
        url: "productControllerAjax.php?do=isParent&id=" + selectedId,
        type: "get",
        success: function (data) {
            //alert(data);
            if (selectedClass == "branch") //user is selecting a parent category
            {

                $("#parent").val(selectedId);
                $("#productCatId").val(selectedId);

                if (data == "isParent") {
                    $("#productCatformDiv").css("display", "block"); //show product categories form
                    $("#productsformDiv").css("display", "none"); //hide products form
                    $("#productEdit").html(''); //hide products edit form
                }
            } else {
                $("#productCatformDiv").css("display", "none");
            }
        },
        error: function () {
            $("#productEdit").html('لقد حدث خطأ أثناء إجراء العملية');
        }
    });
}

function addProduct() {
    $("#addParent").css("display", "none"); //hide add product category button

    $("#addProduct").css("display", "none"); //hide add product button
    //var selectedClass = $("#selectedClass").val();
    var selectedClass = "branch";
    var productIndexType = $('#productIndexType').val();
    if (productIndexType == 0) {
        var selectedId = $("#productCatId0").val();
    } else {
        var selectedId = $("#selectedId").val();
    }
    if ($('#level').val() > 0) {
        level = $('#level').val() - 1;
        var selectedId = $("#productCatId" + level).val();
    }
    console.log('selectedId = ' + selectedId);
    //alert("selectedId: "+selectedId);
    //alert("selectedClass: "+selectedClass);
    //NOTE: products must be added in an productCat which is not a parent for any other product categories.
    //check if selected item has child product categories in it. If true, prevent user from adding products directly in it
    $.ajax({
        url: "productControllerAjax.php?do=isParent&id=" + selectedId,
        type: "get",
        success: function (data) {
            //alert(data);

            var data = data.replace(/(\r\n|\n|\r)/gm, "");
            // if (data == "isNotParent")
            //{
            if (selectedClass == "branch") //user is selecting a product category
            {
                //alert("if");
                $("#parent").val(selectedId);
                $("#productCatId").val(selectedId);
                //alert(selectedId);
                $productItr = 1; //because it is the first product
                $unitItr = 1;
                getCatUnits(selectedId, $productItr, $unitItr);

                $("#productCatformDiv").css("display", "none");//hide product categories form
                $("#productsformDiv").css("display", "block");//show products form
                $("#productEdit").html('');//hide products edit form

            } else {
                //alert("else");
                $("#productsformDiv").css("display", "none");

                //$("#productsformDiv").css("display","block");//show products form

            }
            //}
        },
        error: function () {
            $("#productEdit").html('لقد حدث خطأ أثناء إجراء العملية');
        }
    });

    //#
    //# fill buypricereal ,  buytotal , buyhalf , buypart
    var productCatId_level = $('#level').val();
    //console.log('level = '+productCatId_level);
    var i, last_level;
    for (i = 1; i <= productCatId_level; i++) {
        if (i == productCatId_level) {
            last_level = productCatId_level - 1;
        }
    }
    var productCatId = $('#productCatId' + last_level + '').val();
    if (typeof productCatId === 'undefined') {
        productCatId = selectedId;
    }
    console.log('productCatId = ' + productCatId);
    $.post('productControllerAjax.php?do=get_prices', {productCatId: productCatId}, function (data) {
        data = JSON.parse(data);
        $('.buypricereal_precentage1').val(data.buypricereal);
        $('.buytotal_precentage1').val(data.buytotal);
        $('.buyhafe_precentage1').val(data.buyhalf);
        $('.buypart_precentage1').val(data.buypart);
    });
}

function getCatUnits(catid, productItr, unitItr) {
    ////////////
    $.ajax({
        url: "productControllerAjax.php?do=catUnits&catid=" + catid + "&productItr=" + productItr + "&unitItr=" + unitItr,
        type: "get",
        success: function (data) {
            //alert(data);
            $("#unitsTable" + productItr).html(data);
            $("#unitsItr" + productItr).val($("#hidden_unitItr" + productItr).val());
            $("#catUnitsDiv").html(data)
            $("select").select2();
        },
        error: function () {
            $("#productEdit").html('لقد حدث خطأ أثناء إجراء العملية');
        }
    });
    $()
    //////////
}


function addCat() {
    /* get some values from elements on the page: */
    //	var parent = $("#parent").val();
    //	var productCatName = $("#productCatName").val();
    //	var productCatDescription = $("#productCatDescription").val();
    //	var values = $(catForm).serialize();
    //	/* Send the data using post and put the results in a div */
    //	$.ajax({
    //		url: "productControllerAjax.php?do=addCat",
    //		type: "post",
    //		data: values,
    //		success: function(dataa){
    //			//alert("ajax");
    //		//alert(dataa);
    //		 //refresh the page so tree can be repopulated with new changes
    //		// document.location.reload(true);
    //		},
    //		error:function(request, status, error) {
    //       		//alert(request);
    //		  $("#result").html('لقد حدث خطأ أثناء إجراء العملية');
    //		}
    //	});

    $.ajax({
        type: 'POST',
        url: "productControllerAjax.php?do=addCat",
        data: $("#catForm").serialize(),
        success: function (results) {
            //alert(results);
            if (results == '2') {
                alert(" هذا الاسم موجود من قبل");
                $("#productCatName").val("");
            } else {
                if (results != "1") //not error
                {
                    //refresh the page so tree can be repopulated with new changes
                    document.location.reload(true);
                } else {
                    alert("يرجى إدخال البيانات بشكل صحيح");
                }
            }

        }

        ,
        error: function (request, status, error) {
            //alert(request);
            $("#result").html('لقد حدث خطأ أثناء إجراء العملية');
        }


    });

}



$("#ss").on('click', function () {

    $('.add_required_attr').each(function () {
        var thsVal = $(this).val();
        if (thsVal == '') {

            var itra = $(this).attr('data-itra');
            var productBuyPrice = $('#productBuyPrice' + itra).val();
            var productSellAllPrice = $('#productSellAllPrice' + itra).val();
            var productSellHalfPrice = $('#productSellHalfPrice' + itra).val();
            var productSellUnitPrice = $('#productSellUnitPrice' + itra).val();

            if (productBuyPrice == '' && productSellAllPrice == '' && productSellHalfPrice == '' && productSellUnitPrice == '') {
                $(this).removeAttr('required');
                //  $(this).removeClass('add_required_attr');
            }

            if (productBuyPrice != '' || productSellAllPrice != '' || productSellHalfPrice != '' || productSellUnitPrice != '') {
                console.log('add class');
                $(this).attr('required', 'required');
                // $(this).addClass('add_required_attr');
            }
        }
    });

    //
    var pricesFlag = markNonValidatePrices();
    if (pricesFlag == 1) {
        var retVal = confirm("بعض اسعار البيع اقل من سعر الشراء.متابعة؟");
    } else {
        retVal = true;
    }
    if (retVal == true) {
        if ($('#myProductForm').validate().form()) {
            $(this).attr('disabled', 'disabled');
            $('#myProductForm').submit();
        } else {
            event.preventDefault();
        }
    } else {
        event.preventDefault();
    }
});
function markNonValidatePrices() {
    var pricesFlag = 0;
    $('.add_required_attr').each(function () {
        var thsVal = $(this).val();
        //    if (thsVal == '') {

        var itra = $(this).attr('data-itra');
        var productBuyPrice = Number($('#productBuyPrice' + itra).val());
        var productSellAllPrice = Number($('#productSellAllPrice' + itra).val());
        var productSellHalfPrice = Number($('#productSellHalfPrice' + itra).val());
        var productSellUnitPrice = Number($('#productSellUnitPrice' + itra).val());

        if (pricesFlag == 0) {
            if (productSellAllPrice < productBuyPrice || productSellHalfPrice < productBuyPrice || productSellUnitPrice < productBuyPrice) {
                pricesFlag = 1;
            }
        }

        if (productSellAllPrice < productBuyPrice) {
            $('#productSellAllPrice' + itra).css('background-color', 'yellow');
        } else {
            $('#productSellAllPrice' + itra).css('background-color', 'white');
        }


        if (productSellHalfPrice < productBuyPrice) {
            $('#productSellHalfPrice' + itra).css('background-color', 'yellow');
        } else {
            $('#productSellHalfPrice' + itra).css('background-color', 'white');
        }

        if (productSellUnitPrice < productBuyPrice) {
            $('#productSellUnitPrice' + itra).css('background-color', 'yellow');
        } else {
            $('#productSellUnitPrice' + itra).css('background-color', 'white');
        }

        //    }
    });
    return pricesFlag;
}



function submitEditForm(event, form) {
    //alert("dd");
    /* stop form from submitting normally */
    event.preventDefault();

    /*clear result div*/
    $("#result").html('');

    /* get some values from elements on the page: */
    var values = $(form).serialize();
    //alert(values);
    /* Send the data using post and put the results in a div */
    $.ajax({
        url: "productControllerAjax.php?do=update",
        type: "post",
        data: values,
        success: function (dataa) {

            //refresh the page so tree can be repopulated with new changes
            document.location.reload(true);
        },
        error: function () {
            $("#result").html('لقد حدث خطأ أثناء إجراء العملية');
        }
    });

}


////////////////// Ensure that the product name will not be repeated ////////////
function checkProductName(name, itr) {
    var repeatedFlag = 0;
    var productItr = Number($('#productItr').val());
    for (i = 1; i <= productItr; i++) {
        if ($('#productName' + i)) {
            if (name === $('#productName' + i).val() && i != itr) {
                $('#productName' + itr).val("");
                $('#productName' + itr).focus();
                alert("هذا الإسم موجود من قبل");
                repeatedFlag = 1;
                return false;
            }
        }
    }
    //alert(name);
    ////alert(itr);
    if (repeatedFlag == 0) {
        //check if there is a product with the same name in this category or not.
        if ($("#productAddMultiCatLevel").length > 0) {
            var catid = $(".productCatt:last").val();
        } else {
            var catid = $("#productCatId").val();
        }

        //alert('checkRedundantNames.php?name='+name+'&tablename=product&catid='+catid);
        $.ajax({
            url: 'checkRedundantNames.php?name=' + name + '&tablename=product&catid=' + catid,
            async: false,
            success: function (data) {
                //  alert("data: "+data);
                if (data == '0') {
                } else if (data == '1') {
                    $('#productName' + itr).val("");
                    $('#productName' + itr).focus();
                    alert("هذا الإسم موجود من قبل");
                }
            }
        });
    }
}


function checkProductNameForEdit(name, id, catid) {
    $.ajax({
        async: false,
        url: 'checkRedundantNames.php?do=checkNameWithId&name=' + name + '&id=' + id + '&catid=' + catid + '&tablename=product',
        success: function (data) {
            // alert("data: "+data);
            if (data == '0') {
            } else if (data == '1') {
                $("#productName1").focus();
                $("#productName1").val("");
                alert("هذا الإسم موجود من قبل");
            }
        }
    });
}

////////////////////////////////////////////////////////////////////////////////

function populateSellPrice(productItr) {
    $("#productSellHalfPrice" + productItr).val($("#productSellAllPrice" + productItr).val());
    $("#productSellUnitPrice" + productItr).val($("#productSellAllPrice" + productItr).val());
    $("#price4_" + productItr).val($("#productSellAllPrice" + productItr).val());
    $("#price5_" + productItr).val($("#productSellAllPrice" + productItr).val());
    $("#price6_" + productItr).val($("#productSellAllPrice" + productItr).val());
    $("#price7_" + productItr).val($("#productSellAllPrice" + productItr).val());
    $("#price8_" + productItr).val($("#productSellAllPrice" + productItr).val());
}

//add product units
function addUnits(itr) {

    //var productItr = $("#productItr").val();
    var unitsItr = $("#unitsItr" + itr).val();
    unitsItr++;

    var prices = '';
    if ($('#showpriceall').val() == 1) {
        prices += '<td width="13%">'
                + '     <div>'
                + '         <label class="control-label">سعر الجملة</label>'
                + '         <input name="proUnitSellAllPrice' + itr + unitsItr + '" id="proUnitSellAllPrice' + itr + unitsItr + '" type="text" class="form-control positivefloat" />'
                + '     </div>'
                + '</td>';
    }
    if ($('#showpricehalf').val() == 1) {
        prices += '<td width="13%">'
                + '     <div>'
                + '         <label class="control-label">سعر نص جملة</label>'
                + '         <input name="proUnitSellHalfPrice' + itr + unitsItr + '" id="proUnitSellHalfPrice' + itr + unitsItr + '" type="text" class="form-control positivefloat" />'
                + '     </div>'
                + '</td>';
    }
    if ($('#showpriceunit').val() == 1) {
        prices += '<td width="13%">'
                + '     <div>'
                + '         <label class="control-label">سعر قطاعى</label>'
                + '         <input name="proUnitSellUnitPrice' + itr + unitsItr + '" id="proUnitSellUnitPrice' + itr + unitsItr + '" type="text" class="form-control positivefloat" />'
                + '     </div>'
                + '</td>';
    }

    if ($('#showprice4').val() == 1) {
        prices += '<td>'
                + '     <div>'
                + '         <label class="control-label">سعر4</label>'
                + '         <input name="proUnitprice4_' + itr + unitsItr + '" id="proUnitprice4_' + itr + unitsItr + '" type="text" class="form-control positivefloat" />'
                + '     </div>'
                + '</td>';
    }
    if ($('#showprice5').val() == 1) {
        prices += '<td>'
                + '     <div>'
                + '         <label class="control-label">سعر5</label>'
                + '         <input name="proUnitprice5_' + itr + unitsItr + '" id="proUnitprice5_' + itr + unitsItr + '" type="text" class="form-control positivefloat" />'
                + '     </div>'
                + '</td>';
    }
    if ($('#showprice6').val() == 1) {
        prices += '<td>'
                + '     <div>'
                + '         <label class="control-label">سعر6</label>'
                + '         <input name="proUnitprice6_' + itr + unitsItr + '" id="proUnitprice6_' + itr + unitsItr + '" type="text" class="form-control positivefloat" />'
                + '     </div>'
                + '</td>';
    }
    if ($('#showprice7').val() == 1) {
        prices += '<td>'
                + '     <div>'
                + '         <label class="control-label">سعر7</label>'
                + '         <input name="proUnitprice7_' + itr + unitsItr + '" id="proUnitprice7_' + itr + unitsItr + '" type="text" class="form-control positivefloat" />'
                + '     </div>'
                + '</td>';
    }
    if ($('#showprice8').val() == 1) {
        prices += '<td>'
                + '     <div>'
                + '         <label class="control-label">سعر8</label>'
                + '         <input name="proUnitprice8_' + itr + unitsItr + '" id="proUnitprice8_' + itr + unitsItr + '" type="text" class="form-control positivefloat" />'
                + '     </div>'
                + '</td>';
    }
    if ($('#showprice9').val() == 1) {
        prices += '<td>'
                + '     <div>'
                + '         <label class="control-label">سعر9</label>'
                + '         <input name="proUnitprice9_' + itr + unitsItr + '" id="proUnitprice9_' + itr + unitsItr + '" type="text" class="form-control positivefloat" />'
                + '     </div>'
                + '</td>';
    }
    if ($('#showprice10').val() == 1) {
        prices += '<td>'
                + '     <div>'
                + '         <label class="control-label">سعر10</label>'
                + '         <input name="proUnitprice10_' + itr + unitsItr + '" id="proUnitprice10_' + itr + unitsItr + '" type="text" class="form-control positivefloat" />'
                + '     </div>'
                + '</td>';
    }
    if ($('#showprice11').val() == 1) {
        prices += '<td>'
                + '     <div>'
                + '         <label class="control-label">سعر11</label>'
                + '         <input name="proUnitprice11_' + itr + unitsItr + '" id="proUnitprice11_' + itr + unitsItr + '" type="text" class="form-control positivefloat" />'
                + '     </div>'
                + '</td>';
    }
    if ($('#showprice12').val() == 1) {
        prices += '<td>'
                + '     <div>'
                + '         <label class="control-label">سعر12</label>'
                + '         <input name="proUnitprice12_' + itr + unitsItr + '" id="proUnitprice12_' + itr + unitsItr + '" type="text" class="form-control positivefloat" />'
                + '     </div>'
                + '</td>';
    }
    if ($('#showprice13').val() == 1) {
        prices += '<td>'
                + '     <div>'
                + '         <label class="control-label">سعر13</label>'
                + '         <input name="proUnitprice13_' + itr + unitsItr + '" id="proUnitprice13_' + itr + unitsItr + '" type="text" class="form-control positivefloat" />'
                + '     </div>'
                + '</td>';
    }
    //$('.select2_custom1').select2();
    $("#unitsTable" + itr).append(
            '<tr>'
            + '      <td><div>'
            + '           <label class="control-label"> وحدة القياس</label>'
            + '           <select name="productunit' + itr + unitsItr + '" id="productunit' + itr + unitsItr + '" class="select2_custom1 chosenproduct"  >'
            + $("#productUnitsDiv").html()
            + '           </select>'
            + '      </div></td>'
            + '      <td width="13%"><div>'
            + '           <label class="control-label">عدد الوحدات</label>'
            + '           <input name="productnumber' + itr + unitsItr + '" id="productnumber' + itr + unitsItr + '" class="form-control" type="text" />'
            + '           </div>'
            + '       </td>'
            + '       <td class="' + ebillsettingClass + '">'
            + '         <label class="control-label">وحدة القياس الضريبية</label>'
            + '         <input type="hidden" name="unitInTax' + itr + unitsItr + '" id="unitInTax' + itr + unitsItr + '" data-id="' + itr + unitsItr + '">'
            + '       </td>'
            + '       <td>'
            + '         <div>'
            + '             <label class="control-label">الباركود</label>'
            + '             <input name="proUnitParcode' + itr + unitsItr + '" id="proUnitParcode' + itr + unitsItr + '" type="text" class="form-control numberinput positiveNo" onblur="checkUnitbarcode(this.value, ' + itr + unitsItr + ');"/>'
            + '         </div>'
            + '       </td>'
            + '       <td width="13%">'
            + '         <div>'
            + '             <label class="control-label">سعر الشراء</label>'
            + '             <input name="proUnitBuyPrice' + itr + unitsItr + '" id="proUnitBuyPrice' + itr + unitsItr + '" type="text" class="form-control positivefloat" />'
            + '         </div>'
            + '       </td>'
            + prices + ''
            + '       <td>'
            + '         <a id="remove' + itr + unitsItr + '" onclick="removeUnits(' + itr + ',' + unitsItr + ');"  class="removeUnits">X</a>'
            + '		  </td>'
            + '</tr>'
            );
    $('select.select2_custom1').select2();
    $('#unitInTax' + itr + unitsItr).select2({
        placeholder: "اختر",
        minimumInputLength: 0, // document.getElementById("searchvalue").value,
        multiple: false,
        quietMillis: 100,
        ajax: {
            url: "eBillRequests.php?do=unit-types",
            dataType: 'json',
            data: function (term, page) {
                return {
                    term: term, //search term
                };
            },
            results: function (data) {
                return {results: data};
            }
        },
        formatResult: function (data) {
            return data.text;
        },
        initSelection: function (element, callback) {
            var item = element.val().split(':');
            //  var data = {id: item[0], text: item[1]};
            var data = {id: item[0], text: item[1]};
            callback(data);
        },
        //dropdownCssClass: "bigdrop", // apply css that makes the dropdown taller
    });
    $("#unitsItr" + itr).val(unitsItr); //assign new iteration value
    $('#unitInTax' + itr + unitsItr).select2('data', {id: $('#eunitInTax').val(), text: $('#eunitInTax').val()});

}

function removeUnits(productItr, unitItr) {
    // delete by parents
    $("#remove" + productItr + unitItr).parent().parent().remove();
    return false;
}

function removeProduct(productItr) {
    // delete by parents
    $("#remove" + productItr).parent().remove();
    return false;
}



function etaproduct(productItr) {
    // $("#etaproductform")[0].reset();
    $("#etaproductitr").val(productItr);
    $("#etaproductModal").modal('show');

}


// $('body').on('click', '#etaproductsearch', function () {
//     var etacodetype = $("#etacodetype").val().trim();
//     var etacodelookupvalue = $("#etacodelookupvalue").val().trim();
//     var etaparentlevelname = $("#etaparentlevelname").val().trim();
//     var etaproductitr = $("#etaproductitr").val().trim();
//         $.post("eBillRequests.php?do=search_code", {etacodetype: etacodetype,  etacodelookupvalue: etacodelookupvalue,
//             etaparentlevelname: etaparentlevelname,etaproductitr: etaproductitr}, function (result) {
//             if(result.codeTypeNamePrimaryLang == 'GS1'){
//                  $("input[name='TypeOfBarcodeInTax"+etaproductitr+"'][value='0']").prop("checked", true);
//             }else{
//                  $("input[name='TypeOfBarcodeInTax"+etaproductitr+"'][value='1']").prop("checked", true);
//             }
//             $("#barcodeInTax"+etaproductitr).val(result.codeID);
//         });

// });




$('body').on('click', '#etaproductsearch', function () {
    var etacodetype = $("#etacodetype").val();
    var etaCodeLookupValue = $("#etaCodeLookupValue").val();
    var etaParentCodeLookupValue = $("#etaParentCodeLookupValue").val();
    var etaCodeID = $("#etaCodeID").val();
    var etaCodeName = $("#etaCodeName").val();
    var etaCodeDescription = $("#etaCodeDescription").val();
    var etaTaxpayerRIN = $("#etaTaxpayerRIN").val();
    var etaParentCodeID = $("#etaParentCodeID").val();
    var etaproductitr = $("#etaproductitr").val();
    $.post("productControllerAjax.php?do=search_code", {
        etacodetype: etacodetype, etaCodeLookupValue: etaCodeLookupValue,
        etaParentCodeLookupValue: etaParentCodeLookupValue, etaCodeID: etaCodeID, etaCodeName: etaCodeName,
        etaCodeDescription: etaCodeDescription, etaTaxpayerRIN: etaTaxpayerRIN, etaParentCodeID: etaParentCodeID
    }, function (result) {
        $("#etaproductbody").html(result);
    });

});

$('body').on('change', '.checkboxcode', function () {

    var codetypenameprimarylang = $(this).attr('data-codetypenameprimarylang');
    var codeLookupValue = $(this).attr('data-codeLookupValue');
    var etaproductitr = $("#etaproductitr").val();
    if (codetypenameprimarylang == 'GS1') {
        $("input[name='TypeOfBarcodeInTax" + etaproductitr + "'][value='GS1']").prop("checked", true);
    } else {
        $("input[name='TypeOfBarcodeInTax" + etaproductitr + "'][value='EGS']").prop("checked", true);
    }
    $("#barcodeInTax" + etaproductitr).val(codeLookupValue);
    $("#etaproductModal").modal('hide');
});



function removebarcodProduct(productItr) {

    // delete by parents
    //alert(document.getElementById("productbarcode"+productItr).value);
    $("#productbarcode" + productItr).parent().parent().remove();
    return false;
}
function addproduct() {

    var itr = Number(document.getElementById("itr").value) + 1;
    // alert('fff');
    $("#producttabel").append(
            '<tr>'
            + '<td> '
            + '<div class="form-group">'
            + '<label class="col-lg-2 control-label">اختر المنتج</label>'
            + '<div class="col-lg-4" style="width:300px">'
            /*	+'<select  class="select2 wdt100" style="width:300px"  name="productId'+itr+'" id="productId'+itr+'"     onChange="getbarcode(this.value,'+itr+')">'
             +' <option value="-1"></option>'
             +  $("#productdiv").html()

             +'</select>'*/
            + '<input type="hidden" class="select2product' + itr + ' wdt300"     name="product' + itr + '"  id="product' + itr + '"  data-placeholder="اختر منتج"  />'
            + '</div>'
            + ' </div>'
            + '    <div id="divname' + itr + '" style="display:none">'
            + ' <input  name="productname' + itr + '"  id="productname' + itr + '"    type="text">'
            + ' <input name="price' + itr + '"  id="price' + itr + '" type="text">'
            + ' <input name="pricen' + itr + '"  id="pricen' + itr + '" type="text">'
            + ' <input name="pricenen' + itr + '"  id="pricenen' + itr + '" type="text">'
            + ' <input name="catname' + itr + '"  id="catname' + itr + '" type="text">'
            + ' </div>'
            + '</td>'
            + '<td><input name="productbarcode' + itr + '" id="productbarcode' + itr + '" type="text" onkeypress="getproductbyParcode(event, this.value, ' + itr + ');">'
            + '<div id="updatebarcod' + itr + '"> </div> </td>'
            + '<td><input name="productnum' + itr + '" type="text" value="1">  <div id="seraildiv' + itr + '"style="display:none" ></div></td>'
            + '<td><input name="commentpro' + itr + '" type="text" value=""></td>'
            + '<td><a  onClick="javascript:removebarcodProduct(' + itr + ')" type="button" class="btn btn-default btn-lg removeicon"></a></td>'

            + '</tr>');

    $(".select2product" + itr).select2({
        placeholder: "إسم المنتج",
        minimumInputLength: document.getElementById("searchvalue").value,
        //minimumInputLength: 3,
        multiple: false,
        quietMillis: 100,
        ajax: {
            url: "sellbillAjaxController.php?do=getProducts",
            dataType: 'json',
            data: function (term, page) {
                return {
                    term: term, //search term
                    page_limit: 10, // page size
                    storeid: $("#storeid").val(),
                };
            },
            results: function (data) {
                return {results: data};
            }
        },
        formatResult: formatResultFatma,
        initSelection: function (element, callback) {
            var item = element.val().split(':');
            var data = {id: item[0], text: item[1]};
            callback(data);
        }
    });






    //$('.select2product').select2();





    $("#product" + itr).change(function () {


        var theselectedvalue = $(this).val();
        getbarcode(theselectedvalue, itr);

    });
    document.getElementById("itr").value = itr;




}
function addproductdetailed() {

    var itr = Number(document.getElementById("itr").value) + 1;
    // alert('fff');
    $("#producttabeldetailed").append(
            '<tr>'
            + '<td> '
            + '<div class="form-group">'
            + '<div class="col-lg-4">'
            /*	+'<select  class="select2 wdt100" style="width:300px"  name="productId'+itr+'" id="productId'+itr+'"     onChange="getbarcode(this.value,'+itr+')">'
             +' <option value="-1"></option>'
             +  $("#productdiv").html()

             +'</select>'*/
            + '<input type="hidden" class="select2product' + itr + ' wdt300"     name="product' + itr + '"  id="product' + itr + '"  data-placeholder="اختر منتج"  />'
            + '</div>'
            + ' </div>'
            + '    <div id="divname' + itr + '" style="display:none">'
            + ' <input  name="productname' + itr + '"  id="productname' + itr + '"    type="text">'
            + ' <input name="price' + itr + '"  id="price' + itr + '" type="text">'
            + ' <input name="pricen' + itr + '"  id="pricen' + itr + '" type="text">'
            + ' <input name="pricenen' + itr + '"  id="pricenen' + itr + '" type="text">'
            + ' <input name="catname' + itr + '"  id="catname' + itr + '" type="text">'
            + ' </div>'
            + '</td>'
            + '<td><input name="productbarcode' + itr + '" id="productbarcode' + itr + '" type="text" class="productbarcodeinput" onkeypress="getproductbyParcode(event, this.value, ' + itr + ');">'
            + '<div id="updatebarcod' + itr + '"> </div> </td>'
            + '<td><input name="productsize' + itr + '" type="text" value="" class="productsizeinput"></td>'
            + '<td><input name="pk' + itr + '" type="text" value="" class="pkinput"></td>'
            + '<td><input name="ref' + itr + '" type="text" value="" class="refinput"></td>'
            + '<td><input name="madein' + itr + '" type="text" value="" class="madeininput"></td>'
            + '<td><input name="productnum' + itr + '" type="text" value="1" class="productnuminput">  <div id="seraildiv' + itr + '"style="display:none" ></div></td>'
            + '<td><a  onClick="javascript:removebarcodProduct(' + itr + ')" type="button" class="btn btn-default btn-lg removeicon"></a></td>'

            + '</tr>');

    $(".select2product" + itr).select2({
        placeholder: "إسم المنتج",
        minimumInputLength: document.getElementById("searchvalue").value,
        //minimumInputLength: 3,
        multiple: false,
        quietMillis: 100,
        ajax: {
            url: "sellbillAjaxController.php?do=getProducts",
            dataType: 'json',
            data: function (term, page) {
                return {
                    term: term, //search term
                    page_limit: 10, // page size
                    storeid: $("#storeid").val(),
                };
            },
            results: function (data) {
                return {results: data};
            }
        },
        formatResult: formatResultFatma,
        initSelection: function (element, callback) {
            var item = element.val().split(':');
            var data = {id: item[0], text: item[1]};
            callback(data);
        }
    });











    //$('.select2product').select2();





    $("#product" + itr).change(function () {


        var theselectedvalue = $(this).val();
        getbarcode(theselectedvalue, itr);

    });

    $('[name=productsize' + itr + ']').val(localStorage.getItem("detailedproductsize"));
    $('[name=pk' + itr + ']').val(localStorage.getItem("detailedparcodepk"));
    $('[name=ref' + itr + ']').val(localStorage.getItem("detailedparcoderef"));
    $('[name=madein' + itr + ']').val(localStorage.getItem("detailedparcodemadein"));


    document.getElementById("itr").value = itr;




}






function getbarcode(productid, itr) {

    // alert("productControllerAjax.php?do=getproductbarcode&id="+productid);
    $.ajax({
        url: "productControllerAjax.php?do=getproductdataForPrintParcode&id=" + productid + "&parcodeTypeToPrint=" + localStorage.getItem("parcodeTypeToPrint"),
        type: "get",
        async: false,
        //data: {parent:parent, productCatName:productCatName, productCatDescription:productCatDescription},
        success: function (data) {
            if (data) {
                data = JSON.parse(data);
                document.getElementById("productbarcode" + itr).value = data.parcode;
                $("#updatebarcod" + itr).html('');

                document.getElementById("productname" + itr).value = data.productName;
                document.getElementById("price" + itr).value = data.getproductprice;
                document.getElementById("pricen" + itr).value = data.getproductpricen;
                document.getElementById("pricenen" + itr).value = data.getproductpricenen;
                document.getElementById("catname" + itr).value = data.cat;
            } else {

                $("#updatebarcod" + itr).html('<a type="button" onclick="conformdel_barcode(' + itr + ');" class="conformdel_barcode' + itr + '" data-position="productControllerAjax.php?do=updatebarcode" data-id="' + productid + '" data-itr="' + itr + '">تعديل المنتج</a>')
            }
        },
        error: function (request, status, error) {
            //alert(request);
            // $("#result").html('لقد حدث خطأ أثناء إجراء العملية');
        }
    });
    /*$.ajax({
     url: "productControllerAjax.php?do=getproductbarcode&id=" + productid + "&parcodeTypeToPrint=" + localStorage.getItem("parcodeTypeToPrint"),
     type: "get",
     //data: {parent:parent, productCatName:productCatName, productCatDescription:productCatDescription},
     success: function (data) {
     if (data != "")
     {


     document.getElementById("productbarcode" + itr).value = data;
     $("#updatebarcod" + itr).html('')
     } else
     {

     $("#updatebarcod" + itr).html('<a type="button" onclick="conformdel_barcode(' + itr + ');" class="conformdel_barcode' + itr + '" data-position="productControllerAjax.php?do=updatebarcode" data-id="' + productid + '" data-itr="' + itr + '">تعديل المنتج</a>')
     }
     },
     error: function (request, status, error) {
     //alert(request);
     // $("#result").html('لقد حدث خطأ أثناء إجراء العملية');
     }
     });


     $.ajax({
     url: "productControllerAjax.php?do=getproductname&id=" + productid,
     type: "get",
     //data: {parent:parent, productCatName:productCatName, productCatDescription:productCatDescription},
     success: function (data) {
     if (data != "")
     {
     //	alert(data);

     document.getElementById("productname" + itr).value = data;
     // $("#updatebarcod"+itr).html('')
     }
     }
     });


     $.ajax({
     url: "productControllerAjax.php?do=getproductprice&id=" + productid,
     type: "get",
     //data: {parent:parent, productCatName:productCatName, productCatDescription:productCatDescription},
     success: function (data) {
     if (data != "")
     {
     document.getElementById("price" + itr).value = data;
     // $("#updatebarcod"+itr).html('')
     }
     }
     });


     $.ajax({
     url: "productControllerAjax.php?do=getproductpricen&id=" + productid,
     type: "get",
     //data: {parent:parent, productCatName:productCatName, productCatDescription:productCatDescription},
     success: function (data) {
     if (data != "")
     {
     document.getElementById("pricen" + itr).value = data;
     // $("#updatebarcod"+itr).html('')
     }
     }
     });
     $.ajax({
     url: "productControllerAjax.php?do=getproductpricenen&id=" + productid,
     type: "get",
     //data: {parent:parent, productCatName:productCatName, productCatDescription:productCatDescription},
     success: function (data) {
     if (data != "")
     {
     document.getElementById("pricenen" + itr).value = data;
     // $("#updatebarcod"+itr).html('')
     }
     }
     });

     $.ajax({
     url: "productControllerAjax.php?do=getproductcat&id=" + productid,
     type: "get",
     //data: {parent:parent, productCatName:productCatName, productCatDescription:productCatDescription},
     success: function (data) {
     if (data != "")
     {
     document.getElementById("catname" + itr).value = data;
     // $("#updatebarcod"+itr).html('')
     }
     }
     });*/

    // alert("productControllerAjax.php?do=getproductserial&id="+productid);
    $.ajax({
        url: "productControllerAjax.php?do=getproductserial&itr=" + itr + "&id=" + productid,
        type: "get",
        async: false,
        //data: {parent:parent, productCatName:productCatName, productCatDescription:productCatDescription},
        success: function (data) {
            if (data != "") {
                //alert(data);
                $("#seraildiv" + itr).html(data)
            }
        }
    });





}

//if ($('#opticproduct').val() == 1)//i comment it to work with ajax
{
    $('.removethis').live('click', function () {
        $(this).parent().parent().remove();
    });
    $('#addOpticUnit').live('click', function () {
        var itr = $('#unitsitr').val();
        $('#opticUnitsTable').append('<tr>' +
                '<td>' +
                '<select name="unitid' + itr + '" id="unitid' + itr + '" class="select2 unitClass wdt100">' +
                $("#unitsDiv").html() +
                '</select>' +
                '</td>' +
                '<td><input type="text" name="unitno' + itr + '" id="unitno' + itr + '" class="form-control unitnoClass positiveNo"></td>' +
                '<td><a class="btn btn-default btn-lg removeicon removethis"></a></td>' +
                '</tr>');

        $("#unitid" + itr).select2();
        $(".positiveNo").forcepositiveNum();
        itr++;
        $('#unitsitr').val(itr);
    });
    $('#addSizeColorUnit').live('click', function () {
        var itr = $('#unitsItr1').val();
        $('#opticUnitsTable').append('<tr>' +
                '<td>' +
                '<select name="productunit1' + itr + '" id="productunit1' + itr + '" class="select2 unitClass wdt100">' +
                $("#unitsDiv").html() +
                '</select>' +
                '</td>' +
                '<td><input type="text" name="productnumber1' + itr + '" id="productnumber1' + itr + '" class="form-control unitnoClass positiveNo"></td>' +
                '<td><a class="btn btn-default btn-lg removeicon removethis"></a></td>' +
                '</tr>');

        $("#productunit1" + itr).select2();
        $(".positiveNo").forcepositiveNum();
        itr++;
        $('#unitsItr1').val(itr);
    });
    $('#addOpticSizeColor').live('click', function () {
        //# remove parcode
        var hidden = '';
        $('.check_tr').each(function (e) {
            var ths = $(this);
            if (ths.hasClass('hidden')) {
                hidden = 'hidden';
                return false;
            }
        });
        //        $.post("productControllerAjax.php?do=generate", function (data) {
        var itr = $('#sizecoloritr').val();
        $('#opticSizeColorTable').append('<tr>' +
                '<td><input type="text" name="sizecolorname' + itr + '" id="sizecolorname' + itr + '" class="form-control sizecolorname"></td>' +
                '<td class="' + hidden + '"><input type="text" name="parcode' + itr + '" id="parcode' + itr + '" class="form-control parcodec" value=""></td>' + //value="' + data + '"
                '<td><input type="text" name="quantity' + itr + '" id="quantity' + itr + '" class="form-control positiveNo quantity" value="0"></td>' +
                '<td><textarea name="comment' + itr + '" id="comment' + itr + '" rows="2" class="form-control"></textarea></td>' +
                '<td><a class="btn btn-default btn-lg removeicon removethis"></a></td>' +
                '</tr>');

        $(".positiveNo").forcepositiveNum();
        itr++;
        $('#sizecoloritr').val(itr);
        //        });
    });
    $('#changeType').live('click', function () {
        $('#productDiv').toggle('show');
        $('#sizecolorDiv').toggle('show');
        //if ($('#productDiv').css('display') == "none")
        //if ($('#productDiv').is(":hidden") == true)
        setTimeout(function () {
            if ($('#productDiv').css('display') == 'none') {
                //size and color
                $("#currentType").val("0");
                $('#changeType').text('منتج بدون مقاسات اوالوان');
            } else {
                //product data
                $("#currentType").val("1");
                $('#changeType').text('منتج بمقاسات اوالوان');
            }
        }, 500);
    });
    $('#saveOpticProduct').live('click', function () {
        $flag = validateForm();
        if ($flag != false) {
            if ($('#currentType').val() == 0) {
                //1- check if dublicated here not in db
                $localfalg = 1;
                $('.parcodec').each(function () {
                    var myvalue = $(this).val();
                    var times = 0;
                    $('.parcodec').each(function () {
                        if ($(this).val() == myvalue) {
                            times++;
                            if (times > 1) {
                                alert('عفوا سيريال مكرر');
                                $(this).val("");
                                $(this).focus();
                                $localfalg = 0;
                                return false;
                            }
                        }
                    });

                });

                if ($localfalg == 1) {
                    //2-check in db
                    var itr = $('.parcodec').length;
                    var verified = 0;
                    $('.parcodec').each(function () {
                        var barcod = $(this).val();
                        var thisitr = $(this).attr('id').substr(7);
                        var url;
                        if ($('#product_hideid' + thisitr).length > 0) {
                            var id = $('#product_hideid' + thisitr).val();
                            url = "productControllerAjax.php?do=checkbarcodewithid&barcod=" + barcod + "&thisitr=" + thisitr + "&id=" + id;
                        } else {
                            url = "productControllerAjax.php?do=checkbarcode&barcod=" + barcod + "&thisitr=" + thisitr;
                        }

                        $.ajax({
                            url: url,
                            type: "post",
                            //data: {parent:parent, productCatName:productCatName, productCatDescription:productCatDescription},
                            success: function (data) {
                                data = data.split(",");
                                $flag = data[0];
                                $ajaxitr = data[1];
                                if ($flag == "1") {
                                    alert('عفوا سيريال مكرر');
                                    $('#parcode' + $ajaxitr).val("");
                                    $('#parcode' + $ajaxitr).focus();
                                }
                                if ($flag == "2") {
                                    verified++;
                                    if (verified == itr) {

                                        if ($('#catid_hide').length > 0) {
                                            var url = $('#opticproduct-form').attr("action");
                                            $.post(url, $('#opticproduct-form').serialize(), function (data) {
                                                //alert(data);
                                                //console.log(data);
                                                if (data == 1) {
                                                    alert("تم الحفظ");
                                                    if ($('#gotoshow').val() == 1) {
                                                        window.location.href = "productController.php";
                                                    }
                                                } else if (data == 2) {
                                                    alert("عفوا حدث خطأ");
                                                }
                                            })
                                        } else {
                                            $('#opticproduct-form').submit();
                                        }
                                    }
                                }
                            }
                        });

                    });
                }
            } else if ($('#currentType').val() == 1) {
                var barcod = $('#productparcode').val();
                $.ajax({
                    url: "productControllerAjax.php?do=checkbarcode&barcod=" + barcod,
                    type: "post",
                    //data: {parent:parent, productCatName:productCatName, productCatDescription:productCatDescription},
                    success: function (data) {
                        $flag = data;
                        if ($flag == "1") {
                            alert('عفوا سيريال مكرر');
                            $('#productparcode').val("");
                            $('#productparcode').focus();
                        }
                        if ($flag == "2") {
                            if ($('#catid_hide').length > 0) {
                                var url = $('#opticproduct-form').attr("action");
                                $.post(url, $('#opticproduct-form').serialize(), function (data) {
                                    if (data == 1) {
                                        alert("تم الحفظ");
                                    } else if (data == 2) {
                                        alert("عفوا حدث خطأ");
                                    }
                                })
                            } else {
                                $('#opticproduct-form').submit();
                            }
                        }
                    }
                });
            }


        }
    });

    function validateForm() {

        //
        var opticproductcatid = $("#opticproductcatid").val();
        if (opticproductcatid == "") {
            alert('عفوا لم تقم باختيار التصنيف');
            return false;
        }
        //
        var name = $("#name").val();
        if (name == "") {
            alert('عفوا لم تدخل الاسم');
            return false;
        }

        $flag = 1;
        if ($("#currentType").val() == "1") {
            $('.limit, .proprice, #productQuantity').each(function () {
                var val = $(this).val();
                if (val == "") {
                    $flag = 0;
                    $(this).css('background-color', 'yellow');
                } else {
                    $(this).css('background-color', 'white');
                }
            });
        }
        if ($("#currentType").val() == "0") {
            $('.limit, .proprice, .quantity').each(function () {
                var val = $(this).val();
                if (val == "") {
                    $flag = 0;
                    $(this).css('background-color', 'yellow');
                } else {
                    $(this).css('background-color', 'white');
                }
            });
        }


        $('.unitnoClass').each(function () {
            var val = $(this).val();
            if (val == "") {
                $flag = 0;
                //alert('عفوا لم تدخل كل عدد القطع');
                //$(this).focus();
                //return false;
                $(this).css('background-color', 'yellow');
            } else {
                $(this).css('background-color', 'white');
            }
        });

        /////////////////////////////
        if ($flag == 1) {
            $flag2 = 1;
            $('select.unitClass').each(function () {
                var val = $(this).val();
                if (val == "") {
                    $flag2 = 0;
                    alert('عفوا لم تقم باختيار كل الوحدات');
                    $(this).focus();
                    return false;
                }
            });
            if ($flag2 == 1) {
                if ($("#currentType").val() == "0") {
                    if ($('.sizecolorname').length < 1) {
                        alert('عفوا لم تدخل المقاسات او الالوان ');
                        return false;
                    } else {
                        $('.sizecolorname').each(function () {
                            var val = $(this).val();
                            if (val == "") {
                                //                        alert('عفوا لم تدخل اسماء المقاسات او الالوان ');
                                //                        $(this).focus();
                                //                        return false;
                                $(this).css('background-color', 'yellow');
                            } else {
                                $(this).css('background-color', 'white');
                            }
                        });
                    }
                }
            }

        } else {
            return false;
        }
    }
}

$('.productCat').live('change', function () {
    var id = $(this).val();
    var level = Number($(this).attr('data-level'));
    level = level + 1;
    $('#level').val(level);
    $.post('salesreportajax.php?do=getsubcat', {id: id, level: level}, function (data) {
        $('.productCat').each(function () {
            var thisLevel = Number($(this).attr('data-level'));
            if (thisLevel >= level) {
                $(this).parent('div').remove();
            }
        });
        $('#productIdDiv').remove();
        if (data != "-1") {
            $('#manyParents').append(data);
        }
    });

});

$('.productCatt').live('change', function () {
    var id = $(this).val();
    var level = Number($(this).attr('data-level'));
    level = level + 1;
    $('#level').val(level);
    $.post('salesreportajax.php?do=getsubcat2', {id: id, level: level}, function (data) {
        $('.productCatt').each(function () {
            var thisLevel = Number($(this).attr('data-level'));
            if (thisLevel >= level) {
                $(this).parent('div').remove();
            }
        });
        $('#productIdDiv_').remove();
        if (data != "-1") {
            $('#manyParents').append(data);
        } else {
            if ($('#dontLoadProducts').length > 0 && $('#dontLoadProducts').val() == 1) {
            } else {
                $.post('salesreportajax.php?do=getproductsbills', {id: id}, function (data) {
                    //that part is needed @productController.php?do=showNew  for using parcode input to get product
                    if ($('#parcode').length > 0)
                        $('#parcode').val("")
                    if ($('#product').length == 1)//remove old
                        $('#product').remove();


                    $('#manyParents').append(data);
                });
            }
        }
    });

});

//details of each row of datatable products
$(document).ready(function () {
    //Row details is from https://datatables.net/examples/server_side/row_details.html
    function formatit(d) {
        //d is product id
        var html;
        if ($('#sizecolordetails' + d).length > 0 && $('#sizecolordetails' + d).val() != "" && d.includes("SAC")) {//size and color
            var sizecolordetails = JSON.parse($('#sizecolordetails' + d).val());
            var html = '<table class="table table-black">' +
                    '    <thead>' +
                    '        <tr>' +
                    '            <th>اللون</th>' +
                    '            <th>المقاس</th>' +
                    '            <th>الباركود</th>' +
                    '            <th>الكمية</th>' +
                    '        </tr>' +
                    '    </thead>' +
                    '    <tbody>';
            if (sizecolordetails.length > 0) {
                sizecolordetails.forEach(function (arrayItem) {
                    html += '        <tr>' +
                            '            <td>' +
                            '                <input type="text" class="form-control copyMe" readonly="readonly" style="width:99%" value="' + arrayItem.colorName + '">' +
                            '            </td>' +
                            '            <td>' +
                            '                <input type="text" class="form-control copyMe" readonly="readonly" style="width:99%" value="' + arrayItem.sizeName + '">' +
                            '            </td>' +
                            '            <td>' +
                            '                <input type="text" class="form-control copyMe" readonly="readonly" style="width:99%" value="' + arrayItem.parcode + '">' +
                            '            </td>' +
                            '            <td>' +
                            '                <input type="text" class="form-control copyMe" readonly="readonly" style="width:99%" value="' + arrayItem.quantity + '">' +
                            '            </td>' +
                            '        </tr>';
                });
            } else {
                html += '        <tr>' +
                        '            <td colspan="3"> لا يوجد بيانات</td>' +
                        '        </tr>';
            }
            html += '    </tbody>' +
                    '</table>';
            return html;
        } else if ($('#sizecolordetails' + d).length > 0 && $('#sizecolordetails' + d).val() != "" && d.includes("SOC")) {//size or color
            var sizecolordetails = JSON.parse($('#sizecolordetails' + d).val());
            var html = '<table class="table table-black">' +
                    '    <thead>' +
                    '        <tr>' +
                    '            <th>اللون / المقاس</th>' +
                    '            <th>الباركود</th>' +
                    '            <th>الكمية</th>' +
                    '        </tr>' +
                    '    </thead>' +
                    '    <tbody>';
            if (sizecolordetails.length > 0) {
                sizecolordetails.forEach(function (arrayItem) {
                    html += '        <tr>' +
                            '            <td>' +
                            '                <input type="text" class="form-control" disabled="disabled" style="width:99%" value="' + arrayItem.productName + '">' +
                            '            </td>' +
                            '            <td>' +
                            '                <input type="text" class="form-control" disabled="disabled" style="width:99%" value="' + arrayItem.parcode + '">' +
                            '            </td>' +
                            '            <td>' +
                            '                <input type="text" class="form-control" disabled="disabled" style="width:99%" value="' + arrayItem.sumProductQuantity + '">' +
                            '            </td>' +
                            '        </tr>';
                });
            } else {
                html += '        <tr>' +
                        '            <td colspan="3"> لا يوجد بيانات</td>' +
                        '        </tr>';
            }
            html += '    </tbody>' +
                    '</table>';
            return html;
        } else if ($('#sizecolordetails' + d).length > 0 && $('#sizecolordetails' + d).val() != "" && d.includes("ING")) {//Ingridients  "collective product"
            var sizecolordetails = JSON.parse($('#sizecolordetails' + d).val());
            var html = '<table class="table table-black">' +
                    '    <thead>' +
                    '        <tr>' +
                    '            <th>المنتجات الخام</th>' +
                    '            <th>وحدة القياس</th>' +
                    '            <th>عدد الوحدات</th>' +
                    '        </tr>' +
                    '    </thead>' +
                    '    <tbody>';
            if (sizecolordetails.length > 0) {
                sizecolordetails.forEach(function (arrayItem) {
                    html += '        <tr>' +
                            '            <td>' +
                            '                <input type="text" class="form-control" disabled="disabled" style="width:99%" value="' + arrayItem.productName + '">' +
                            '            </td>' +
                            '            <td>' +
                            '                <input type="text" class="form-control" disabled="disabled" style="width:99%" value="' + arrayItem.unitName + '">' +
                            '            </td>' +
                            '            <td>' +
                            '                <input type="text" class="form-control" disabled="disabled" style="width:99%" value="' + arrayItem.quantity + '">' +
                            '            </td>' +
                            '        </tr>';
                });
            } else {
                html += '        <tr>' +
                        '            <td colspan="3"> لا يوجد بيانات</td>' +
                        '        </tr>';
            }
            html += '    </tbody>' +
                    '</table>';
            return html;
        } else {
            //html = 'منتج بلا مقاسات و الوان';
            return false;
            //var html = '<table class="table table-black"></table>';
            //return html;
        }




    }
    initSelect2($('#clientid1'));
    /*-- data table of products ----------------------------------------------*/
    if ($('#productsTable').length > 0) {
        var dt = $('#productsTable').dataTable({
            dom: 'Bfrtip',
            buttons: [//'csv', 'pdf'
                {
                    extend: "print",
                    className: "btn dark btn-outline",
                    text: "طباعه<i class='fa fa-print'></i>",
                    exportOptions: {
                        //columns: '.show-print'
                        columns: ':visible'
                    },
                    customize: function (win) {
                        $(win.document.body).find('table')
                                //.addClass('compact')
                                .css('direction', 'rtl');
                    }
                }, {
                    extend: "copy",
                    className: "btn red btn-outline",
                    text: "نسخ",
                    exportOptions: {
                        //columns: '.show-print'
                        columns: ':visible'
                    }
                }, {
                    extend: "excel",
                    className: "btn yellow btn-outline ",
                    text: "اكسل",
                    exportOptions: {
                        //columns: '.show-print'
                        columns: ':visible'
                    }
                }, {
                    extend: "colvis",
                    className: "btn dark btn-outline",
                    text: "المكونات"
                }
            ],
            "bStateSave": true,
            "language": {
                "aria": {
                    "sortAscending": ": Used to order Ascending",
                    "sortDescending": ": Used to order Descending"
                },
                "emptyTable": "لا يوجد بيانات",
                "info": "عرض _START_ من _END_ الى _TOTAL_ عناصر",
                "infoEmpty": "لا يوجد بيانات",
                "infoFiltered": "(تنقيه _MAX_ من الاجمالى)",
                "lengthMenu": " _MENU_ عنصر",
                "search": "البحث:",
                "zeroRecords": "لا يوجد بيانات تشابه البحث"
            },
            responsive: !0,
            "columnDefs": [
                {
                    "targets": [0],
                    "searchable": false,
                    "className": "details-control show-print"
                },
                {"targets": [1], "className": "show-print"},
                {"targets": [2], "className": "show-print"},
                {"targets": [3], "className": "show-print"},
                {"targets": [4], "className": "show-print"},
                {"targets": [5], "className": "show-print"},
                {"targets": [6], "className": "show-print"},
                {"targets": [7], "className": "show-print"},
                {"targets": [8], "className": "show-print"},
                {"targets": [9], "className": "show-print"},
                {"targets": [10], "className": "show-print"},
                {"targets": [11], "className": "show-print"},
                {"targets": [12], "className": "show-print"},
                        //            {"targets": [13], "className": "show-print"},
                        //{targets: '_all', "className": 'show-print'}
            ],
            order: [
                [0, "asc"]
            ],
            "paging": false,
            dom: "<'row' <'col-md-12'B>><'row'<'col-md-6 col-sm-12'l><'col-md-6 col-sm-12'f>r><'table-scrollable't><'row'<'col-md-5 col-sm-12'i><'col-md-7 col-sm-12'p>>"
        });
        $('#productsTable td').css("height", "30px");
        // Array to track the ids of the details displayed rows
        var detailRows = [];
        $('#productsTable tbody').on('click', 'tr td.details-control', function () {
            var tr = $(this).closest('tr');
            var row = dt.api().row(tr);
            var idx = $.inArray(tr.attr('id'), detailRows);
            if (row.child.isShown()) {
                //hide
                tr.removeClass('details');
                row.child.hide();
                // Remove from the 'open' array
                detailRows.splice(idx, 1);
            } else {
                //show
                tr.addClass('details');
                //row.child(formatit(row.data())).show();
                row.child(formatit(tr.attr('data-pro'))).show();
                // Add to the 'open' array
                if (idx === -1) {
                    detailRows.push(tr.attr('id'));
                }
            }
        });
        $('#toggleAll').click(function () {
            var status = $(this).attr('data-status');
            $('#productsTable tbody tr td.details-control').each(function () {
                var tr = $(this).closest('tr');
                var row = dt.api().row(tr);
                var idx = $.inArray(tr.attr('id'), detailRows);
                if (status == "opend") {
                    //hide
                    tr.removeClass('details');
                    row.child.hide();
                    // Remove from the 'open' array
                    detailRows.splice(idx, 1);
                } else if (status == "closed") {
                    //show
                    tr.addClass('details');
                    //row.child(formatit(row.data())).show();
                    row.child(formatit(tr.attr('data-pro'))).show();
                    // Add to the 'open' array
                    if (idx === -1) {
                        detailRows.push(tr.attr('id'));
                    }
                }
            });
            if (status == "opend") {
                $('#toggleAll').attr('data-status', 'closed');
            } else if (status == "closed") {
                $('#toggleAll').attr('data-status', 'opend');
            }
        });
    }
    /*-----------------------------------------------------------*/
    // On each draw, loop over the `detailRows` array and show any child rows
    //        dt.on('draw', function () {
    //            $.each(detailRows, function (i, id) {
    //                $('#' + id + ' td.details-control').trigger('click');
    //            });
    //        });
});

////////////////// Product with size And Color ////////////
//get size and color
var sizes;
var colors;
function getSizeColorArrays() {
    sizes = new Array();
    colors = new Array();
    if ($('#sizes').val()) {
        if ($('#sizes').val().indexOf("-1") !== false && $('#sizes').val().indexOf("-1") > -1) {//want to use all sizes
            $('#sizes option').each(function () {
                if (Number(this.value) > 0) {
                    sizes.push({'id': this.value, 'text': this.text});
                }
            });
        } else {
            $('#sizes option:selected').each(function () {
                if (Number(this.value) > 0) {
                    sizes.push({'id': this.value, 'text': this.text});
                }
            });
        }
    }
    if ($('#colors').val()) {
        if ($('#colors').val().indexOf("-1") !== false && $('#colors').val().indexOf("-1") > -1) {//want to use all colors
            $('#colors option').each(function () {
                if (Number(this.value) > 0) {
                    colors.push({'id': this.value, 'text': this.text});
                }
            });
        } else {
            $('#colors option:selected').each(function () {
                if (Number(this.value) > 0) {
                    colors.push({'id': this.value, 'text': this.text});
                }
            });
        }
    }
}
function drawSizeColor() {
    if (sizes.length > 0 && colors.length > 0) {
        var itr = 1;
        var html = '';
        sizes.forEach(function (itemSize) {//console.log(item.id + "-" + item.text);
            colors.forEach(function (itemColor) {
                html += '<tr>' +
                        '   <input type="hidden" name="size_detail' + itr + '" id="size_detail' + itr + '" value="' + itemSize.id + '"/>' +
                        '   <input type="hidden" name="color_detail' + itr + '" id="color_detail' + itr + '" value="' + itemColor.id + '"/>' +
                        '   <td><input type="text" class="form-control" name="parcode_detail' + itr + '" id="parcode_detail' + itr + '" value=""/></td>' +
                        '   <td><input type="text" class="form-control" readonly value="' + itemSize.text + '"/></td>' +
                        '   <td><input type="text" class="form-control" readonly value="' + itemColor.text + '"/></td>';
                if ($('#productId').length > 0) {//this is edit no quantity to change

                } else {//in add show quantity
                    html += '   <td><input type="text" class="form-control positivefloat sizeColorQuantity" name="quantity_detail' + itr + '" value="0"/></td>';
                }


                html += '   <td><a class="btn btn-default btn-lg removeicon removethis"></a></td>' +
                        '</tr>';
                //
                itr++;
            });
        });
        $('#SizeColorTB').html(html);
        $('#sizeColorItr').val(itr);
    }
}
function drawSizeColor_onlyNew() {
    var itr = Number($('#sizeColorItr').val());
    if (sizes.length > 0 && colors.length > 0) {
        var html = '';
        sizes.forEach(function (itemSize) {//console.log(item.id + "-" + item.text);
            colors.forEach(function (itemColor) {
                var alreadyExist = checkIfExist(itemSize, itemColor);
                if (alreadyExist != 1) {
                    html += '<tr>' +
                            '   <input type="hidden" name="size_detail' + itr + '" id="size_detail' + itr + '" value="' + itemSize.id + '"/>' +
                            '   <input type="hidden" name="color_detail' + itr + '" id="color_detail' + itr + '" value="' + itemColor.id + '"/>' +
                            '   <td><input type="text" class="form-control" name="parcode_detail' + itr + '" id="parcode_detail' + itr + '" value=""/></td>' +
                            '   <td><input type="text" class="form-control" readonly value="' + itemSize.text + '"/></td>' +
                            '   <td><input type="text" class="form-control" readonly value="' + itemColor.text + '"/></td>';
                    if ($('#productId').length > 0) {//this is edit no quantity to change

                    } else {//in add show quantity
                        html += '   <td><input type="text" class="form-control positivefloat sizeColorQuantity" name="quantity_detail' + itr + '" value="0"/></td>';
                    }


                    html += '   <td><a class="btn btn-default btn-lg removeicon removethis"></a></td>' +
                            '</tr>';
                    //
                    itr++;
                }
            });
        });
        $('#SizeColorTB').append(html);
        $('#sizeColorItr').val(itr);
    }
}
function checkIfExist(itemSize, itemColor) {
    var rowsNo = Number($('#sizeColorItr').val());
    var flag = 0;//dontexist
    for (var i = 1; i <= rowsNo; i++) {
        var rowSize = $('#size_detail' + i).val();
        var rowColor = $('#color_detail' + i).val();
        if (rowSize == itemSize.id && rowColor == itemColor.id) {
            flag = 1;
            return flag;//so that it wont continue looping
        }
    }
    return flag;
}
$('#SizeColorQuantity').on('click', function () {//this one draw all as new
    getSizeColorArrays();
    //make sure ther are  sizes and colors selected
    if (sizes.length > 0 && colors.length > 0) {
        drawSizeColor();
        $('#quantity_div').show();
    } else {
        alert('عفوا تاكد من اختيار لون و مقاس على الاقل');
    }

});
$('#SizeColorQuantity_onlyNew').on('click', function () {//this one keeps old rows and draw new
    getSizeColorArrays();
    //make sure ther are  sizes and colors selected
    if (sizes.length > 0 && colors.length > 0) {
        drawSizeColor_onlyNew();
        $('#quantity_div').show();
    } else {
        alert('عفوا تاكد من اختيار لون و مقاس على الاقل');
    }

});

$('#saveSizeColor').on('click', function () {
    if ($('.sizeColorQuantity').length > 0) {
        //its okay there is quantity
    } else {
        //draw it and keep it hidden
        getSizeColorArrays();
        if (sizes.length > 0 && colors.length > 0) {
            drawSizeColor();
        }
    }

});

function onTestChange() {
    var key = window.event.keyCode;

    // If the user has pressed enter
    if (key === 13) {
        document.getElementById("txtArea").value = document.getElementById("txtArea").value + "\n";
        return false;
    } else {
        return true;
    }
}

//choose parcode to print before submit
$('#printParcodeForm').on('submit', function () {
    var parcodeTypeToPrint = localStorage.getItem('parcodeTypeToPrint');
    if (parcodeTypeToPrint == 0) {
        $(this).attr('action', 'printparcode.php');
    } else if (parcodeTypeToPrint == 1) {
        $(this).attr('action', 'printparcodenew.php');
    }
});


$('body').on('focusout', '.productCatDescription', function () {

    var pro_id = $(this).attr('data-id');
    var type = $(this).attr('data-type');

    var columupdated;
    var columupdatedvalue = $(this).val();

    switch (type) {
        case 'productCatDescription':
            var pro_CatDescription = $(this).val();
            columupdated = 'وصف التصنيف : ';
            break;
    }

    if (typeof pro_CatDescription === "undefined") {
        pro_CatDescription = ''
    }

    $.post('productControllerAjax.php?do=UpdateCatDescription', {pro_id: pro_id, type: type, value: columupdatedvalue}, function (data) {

    });
});

$('.copyMe').live('click', function () {
    copyToClipboard($(this).val());
})

function initSelect2(element) {
    element.select2({
        placeholder: "اختر عميل ",
        minimumInputLength: 0,
        //  minimumInputLength: 3,
        multiple: false,
        quietMillis: 100,
        //width: '120%',
        ajax: {
            url: "billsajax.php?do=getclients&noadd=1",
            dataType: 'json',
            data: function (term, page) {
                //  alert(term);
                return {
                    term: term, //search term
                    page_limit: 10, // page size
                };
            },
            results: function (data) {
                data.unshift({id: "0", text: "كل العملاء"});
                return {results: data};
            }
        },
        initSelection: function (element, callback) {
            var item = element.val().split(':');
            var data = {id: item[0], text: item[1]};
            callback(data);
        }
    });
    element.select2("data", {id: "0", text: "كل العملاء"});
}

$("body").on('change', '.sellpercenttype', function () {
    var type = $(this).val();
    var itra = $(this).attr('data-itra');
    if (type == 0) {
        $('.sellpercentadd' + itra).show();
        $('.sellpercentdiscount' + itra).hide();
    } else {
        $('.sellpercentdiscount' + itra).show();
        $('.sellpercentadd' + itra).hide();
    }
});

$('body').on('click', '#copyProduct', function () {
    var itr = $("#productItr").val();
    if ($('#productName' + itr).val()) {
        itr++;
        $('#addProducts').trigger('click');
    }
    var id = $('#product').val();
    if (id > 0) {
        $.post('productControllerAjax.php?do=getProductData', {id: id}, function (data) {
            data = JSON.parse(data);
            $('#productName' + itr).val(data.productName + '-copy');
            $('#productBuyPrice' + itr).val(data.productBuyPrice);
            $('#buypricereal' + itr).val(data.productbuypricereal);
            $('#buypricereal_precentage' + itr).val(data.buypricereal_precentage);
            $('#productSellAllPrice' + itr).val(data.productSellAllPrice);
            $('#buytotal_precentage' + itr).val(data.buytotal_precentage);
            $('#productSellHalfPrice' + itr).val(data.productSellHalfPrice);
            $('#buyhalf_precentage' + itr).val(data.buyhalf_precentage);
            $('#productSellUnitPrice' + itr).val(data.productSellUnitPrice);
            $('#buypart_precentage1' + itr).val(data.buypart_precentage);
            $('#price4_' + itr).val(data.price4);
            $('#price5_' + itr).val(data.price5);
            $('#price6_' + itr).val(data.price6);
            $('#price7_' + itr).val(data.price7);
            $('#price8_' + itr).val(data.price8);
            $('#productquantity' + itr).val(data.productquantity);
            $('#expireDate' + itr).val(data.expireDate);
            $('#productDate' + itr).val(data.productDate);
            $('#limitamount' + itr).val(data.limitamount);
            $('input[name=TypeOfBarcodeInTax' + itr + '][value=' + data.TypeOfBarcodeInTax + ']').attr('checked', true);
            $('#barcodeInTax' + itr).val(data.barcodeInTax);
            $('input[name=inMenu' + itr + '][value=' + data.inMenu + ']').attr('checked', true);
            $('input[name=type' + itr + '][value=' + data.type + ']').attr('checked', true);
            $('input[name=isservice' + itr + '][value=' + data.isService + ']').attr('checked', true);
            $('#productDescription' + itr).html(data.productDescription);
            $('#clientid' + itr).val(data.clientid);
            $('#clientid' + itr).select2();
            $('#onlinecatid' + itr).val(data.onlinecatid);
            $('#onlinecatid' + itr).select2();
            $('#searchfiltersid' + itr).val(data.searchfiltersid);
            $('#searchfiltersid' + itr).select2();
            $('#productNameE' + itr).val(data.productNameE);
            $('#procode' + itr).val(data.procode);
            $('#partNumber' + itr).val(data.partNumber);
            $('#vehicleType' + itr).val(data.vehicleType);
            $('#company' + itr).val(data.company);
            $('#weight' + itr).val(data.weight);
            $('#origin' + itr).val(data.origin);
            $('#hscode' + itr).val(data.hscode);
            $('#ProductionDate' + itr).val(data.ProductionDate);
            $('#expiry' + itr).val(data.expiry);
            $('#grantduration' + itr).val(data.grantduration);
            $('#minappearonline' + itr).val(data.minappearonline);
            $('#selladdpercent' + itr).val(data.selladdpercent);
            $('#selldiscountpercent' + itr).val(data.selldiscountpercent);
            $('#buydiscountpercent' + itr).val(data.buydiscountpercent);
            $('input[name=power' + itr + '][value=' + data.power + ']').attr('checked', true);
            $('input[name=onlinepro' + itr + '][value=' + data.onlinepro + ']').attr('checked', true);
            $('input[name=sellpercenttype' + itr + '][value=' + data.sellpercenttype + ']').attr('checked', true);
            $('#addProducts').trigger('click');
        });
    } else {
        alert('اختر منتج أولاً');
    }
});
$('body').on('change', '#operation', function () {
    var val = Number($(this).val());
    if (val == 4) {
        $('#MultiUpdateDiv').show();
    } else {
        $('#MultiUpdateDiv').hide();
    }
});