
$(document).ready(function (e) {


    /*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");
    });

    //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
        //alert(id);
        $.ajax({
            url: "productControllerAjax.php?do=edit&id=" + id,
            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 () {



        var catid = $("#productCatId").val();

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

        //get cat units
        //$("#catUnitsDiv").html("");
        getCatUnits(catid, itr, unitsItr);

        $("#productsDiv").append(
                '<table  class="table table-black bg-theme-white" ><tr>'
                + '                      <td colspan="2">الإسم</td>'
                + '                      <td>سعر الشراء</td>'
                + '                      <td>سعر بيع الجمله</td>'
                + '                      <td>سعر بيع الجمله التجزئة</td>'
                + '                      <td>سعر بيع الوحده</td>'
                + '                    </tr>'
                + '                    <tr>'
                + '                      <td colspan="2"><input name="productName' + itr + '" type="text" id="productName' + itr + '" size="80" required onChange="checkProductName(this.value, ' + itr + ');" class="form-control" /></td>'

                + '                      <td><input name="productBuyPrice' + itr + '" type="text" id="productBuyPrice' + itr + '" required class="form-control wd50 aw_m aw_mt aw_pp numberclic enteraction numberinput" width="20"/></td>'
                + '                      <td><input name="productSellAllPrice' + itr + '" type="text" id="productSellAllPrice' + itr + '" onKeyUp="populateSellPrice(' + itr + ');" required class="form-control wd50 aw_m aw_mt aw_pp numberclic enteraction numberinput" width="20"/></td>'
                + '                      <td><input name="productSellHalfPrice' + itr + '" type="text" id="productSellHalfPrice' + itr + '" required class="form-control wd50 aw_m aw_mt aw_pp numberclic enteraction numberinput" width="20"/></td>'
                + '                      <td><input name="productSellUnitPrice' + itr + '" type="text" id="productSellUnitPrice' + itr + '" required class="form-control wd50 aw_m aw_mt aw_pp numberclic enteraction numberinput "  width="20"/></td>'

                + '                    </tr>'
                + '                    <tr>'
                + '                     <td colspan="2">الباركود</td>'
                + '                      <td >الكمية</td>'
                + '                     <td colspan="2">التاريخ</td>'
                + '                      <td>الحد الأدنى للمنتج</td>'

                + '                    </tr>'
                + '                    <tr>'
                + '                      <td colspan="2"><input name="parcode' + itr + '" required type="text" id="parcode' + itr + '" size="9" class="form-control" size="50" onmouseover="checkbarcode(this.value,' + itr + ');" /></td>'
                + '                      <td><input name="productquantity' + itr + '" type="text" id="productquantity' + itr + '"  required="required" value="0" class="form-control wd50 aw_m aw_mt aw_pp numberclic enteraction numberinput" size="20"/></td>'
                + '                    <td colspan="2"><input name="productDate' + itr + '" type="text" id="productDate' + itr + '" size="9" required class="form-control awdatepicker" autocomplete="off"  data-date-format="yyyy-mm-dd"/></td>'
                + '                      <td><input name="limitamount' + itr + '" type="text" id="limitamount' + itr + '" value="0" class="form-control wd50 aw_m aw_mt aw_pp numberclic enteraction numberinput"/></td>'
                + '                '
                + '                    </tr>'
                + '                    <tr>'
                + '                    <td colspan="3">التعليق</td>'
                + '                   <td colspan="3">تصنيع</td>'
                + '                    </tr>'
                + '                    <tr>'
                + '                          <td colspan="3"><textarea name="productDescription' + itr + '" id="productDescription' + itr + '" cols="5" rows="2" class="form-control"></textarea></td>'
                + '<td colspan="3"> <div class="form-group">  <div class="col-lg-4">'

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

                + '                 نعم </label>'
                + '             </div>'
                + '             <div class="radio-inline">'
                + '               <label>'
                + '                 <input value="0"  class="noradioR" name="type' + itr + '"   checked="checked"  type="radio" />'
                + '                 لا </label>'
                + '             </div></div></div>'

                + '  			</td>'
                + '                    </tr>'
                + '                    <tr>'
                + '	     <!--------------------------------  adding type للتصنيع   ----------------------------->'




                + '	     <!--------------------------------  adding units   ----------------------------->'
                + '	     '
                + '	    <tr><td colspan="10"> <div id="addUnitsDiv' + itr + '" >'
                + '	         <table id="unitsTable' + itr + '"  class="table table-black bg-theme-white">'

                + $("#catUnitsDiv").html()
                + '	         </table><!--end unitsTable-->'
                + '	     </div>'
                + '	     <input class="addUnits btn btn-warning" onclick="addUnits(' + itr + ');" type="button" value="إضافة وحدة قياس"/>'
                + '	     <input name="unitsItr' + itr + '" id="unitsItr' + itr + '" type="hidden" value="1" />'
                + '	     '
                + '	     <!-------------------------------- end adding units   -------------------------->'

                + '	    <a id="remove' + itr + '"  onclick="removeProduct(' + itr + ');" class="removeProduct pull-left btn btn-danger">حذف المنتج</a>'
                + '	</td></tr>'

                + '	</table>'
                );
        $('select.select2_custom').select2();
        $('.awdatepicker').datepicker();
        $('.numberinput').forceNumeric();
        //alert(itr);
        $("#productItr").val(itr); //assign new iteration value
        generateParcode(itr);
    });



////////////////////////////////////////////////////////////////////////
//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('لقد حدث خطأ أثناء إجراء العملية');
            }
        });

    });



    var formatResult;


    formatResult = function (data) {
        //alert(data);
        return  data.text;
    }

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


    $("#productId1").change(function () {


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

    });

});

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)
{

    $.ajax({
        url: "productControllerAjax.php?do=checkbarcode&barcod=" + barcod,
        type: "get",
        success: function (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) {

            if (data == 1)
            {



                alert('هذا الباركود موجود من قبل');
                $("#parcode" + itr).val('');

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

            }

        }
    });
}

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 (data) {
            alert(data);
            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
            {
                alert(222);
                //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 (data) {

                        alert(data);
                        if (data == "yes")
                        {
                            $("#addProduct").css("display", "block"); //show add product button
                            $("#addParent").css("display", "none"); //hide add product category button
                        }
                        else if (data == "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 selectedClass = $("#selectedClass").val();
    var selectedId = $("#selectedId").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 selectedId = $("#selectedId").val();
    //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);
            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('لقد حدث خطأ أثناء إجراء العملية');
        }
    });
}

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(catForm)
{
    /* 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('لقد حدث خطأ أثناء إجراء العملية');
//		}
//	});
}


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)
{
    //alert(name);
    ////alert(itr);
    //check if there is a product with the same name in this category or not.
    var catid = $("#productCatId").val();
    //alert('checkRedundantNames.php?name='+name+'&tablename=product&catid='+catid);
    $.ajax({
        url: 'checkRedundantNames.php?name=' + name + '&tablename=product&catid=' + catid,
        success: function (data) {
            //  alert("data: "+data);
            if (data == '0')
            {
            }
            else if (data == '1')
            {
                $('#productName' + itr).val("");
                $('#productName' + itr).focus();
                alert("هذا الإسم موجود من قبل");
            }
        }
    });
}


function checkProductNameForEdit(name, id)
{
    $.ajax({
        async: false,
        url: 'checkRedundantNames.php?do=checkNameWithId&name=' + name + '&id=' + id + '&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());
}

//add product units
function addUnits(itr)
{

    //var productItr = $("#productItr").val();
    var unitsItr = $("#unitsItr" + itr).val();
    unitsItr++;
//$('.select2_custom1').select2();
    $("#unitsTable" + itr).append(
            '<tr>'
            + '      <td><div class="form-group">'
            + '              <label class="col-lg-4 control-label">اسم وحدة القياس</label>'
            + '              <div class="col-lg-8">'
            + '           <select name="productunit' + itr + unitsItr + '" id="productunit' + itr + unitsItr + '" class="select2_custom1 wdt100 chosenproduct"  >'
            + $("#productUnitsDiv").html()
            + '           </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 + unitsItr + '" id="productnumber' + itr + unitsItr + '" class="form-control" type="text" />'
            + '              </div>'
            + '            </div>'
            + '</td>'
            + '       <td>'
            + '       <a id="remove' + itr + unitsItr + '" onclick="removeUnits(' + itr + ',' + unitsItr + ');"  class="removeUnits">X</a>'
            + '		  </td>'
            + '</tr>'
            );
    $('select.select2_custom1').select2();
    $("#unitsItr" + itr).val(unitsItr); //assign new iteration value
}

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

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

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="catname' + itr + '"  id="catname' + itr + '" type="text">'
            + ' </div>'
            + '</td>'
            + '<td><input name="productbarcode' + itr + '" id="productbarcode' + itr + '" type="text">'
            + '<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><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=getProducts2",
            dataType: 'json',
            data: function (term, page) {
                return {
                    term: term, //search term
                    page_limit: 10 // page size
                };
            },
            results: function (data) {
                return {results: data};
            }
        },
        formatResult: formatResult,
        initSelection: function (element, callback) {
            var item = element.val().split(':');
            var data = {id: item[0], text: item[1]};
            callback(data);
        }
    });






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



    var formatResult;


    formatResult = function (data) {
        //alert(data);
        return  data.text;
    }

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


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

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




}






function getbarcode(productid, itr)
{

    // alert("productControllerAjax.php?do=getproductbarcode&id="+productid);

    $.ajax({
        url: "productControllerAjax.php?do=getproductbarcode&id=" + productid,
        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('')
            }
        }
    });

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



    $.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('')
            }
        }
    });

}


