
function updateProduct()
{
    //alert('updateProduct');
    var newLinkCurrentId = $("#newLinkCurrentId").val();
    var itr = newLinkCurrentId
    var totalQuantity = $("#totalQty").html();
    var billnameid = $("#billnameid").val();

    $tabIndex = $("#product" + itr).attr("tabindex");

    //alert("itr:"+itr);
    $.ajax({
        type: 'POST',
        url: 'buyBillControllerAjax.php?do=updateProduct&itr=' + itr + '&tabIndex=' + $tabIndex + '&billnameid=' + billnameid,
        data: $("#productInfo").serialize(),
        success: function (data) {

            if (data != "1") //not error
            {
                //alert("not error");
                $("#newProduct" + itr).html(data);
                $('#productModal').modal('hide');

                $('select.select2_unit' + itr).select2();

                // here the frist action on frist dropdownlist
                /************************/
                $("#product" + itr).on("change", function () {
                    //alert("change product");
                    //here get the price of product from ajax
                    //the selected value of drop downlsit
                    var theselectedvalue = $(this).val();
                    var returnBillFlag = 0;

                    //using the load method to load the price
                    //$("#propricechange"+itr).html('<img src="../views/default/images/loader/6.gif" alt="">');

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

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

                    //////////////////////////////////////////////////
                    var supplier = $('#supplier').val();
                    $.ajax({
                        url: 'buyBillControllerAjax.php?do=units&return=' + returnBillFlag + '&itrs=' + itr + '&tabindex=13&productid=' + theselectedvalue + '&supplier=' + supplier + '&billnameid=' + $('#billnameid').val(),
                        type: "get",
                        success: function (data) {
                            // alert(data);
                            var response = $.parseJSON(data);

                            //populate unit
                            $('#unitDiv' + itr).html(response.unitString);
                            $("#productUnitsDiv").empty();
                            $("#unitDiv" + itr + " option").clone().appendTo("#productUnitsDiv");
                            $('.select2_unit' + itr).select2();
                            $('#parcode' + itr).val(response.parcodeString);


                            //populate buy price
                            $('#propricechange' + itr).html(response.priceString);

                            //here all code that will happend with loaded content
                            //the number of rows of products
                            var noitr = document.getElementById("hidden_itr").value

                            // get the total of product
                            calcuproduct(itr);
                            // get the total price of product
                            totalprice(noitr);

                            totalquantity(noitr);

                            //get the general discount
                            thegeneraldiscount();

                            //get the general payed
                            thegeneralpayed();


                            // calculate the rest of debt
                            therestofdebt();

                            //add another row if there is no any new rows
                            $proId = document.getElementById("product" + noitr).value;
                            if ($proId != null && $proId != '-1' && $proId != '')
                            {
                                $("#addpro").trigger('click');
                            }
                            //load the jquery checker for number only
                            //  $.getScript('../views/default/js/head_scripts.js');

                            $('.select2_unit' + itr).select2();

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

                    //	  $('#propricechange'+itr).load('buyBillControllerAjax.php?return='+returnBillFlag+'&itrs='+itr+'&tabindex=13&productid='+theselectedvalue+'',function() {//
//
//						  //here all code that will happend with loaded content
//						  //the number of rows of products
//						  var noitr = document.getElementById("hidden_itr").value
//
//						  // get the total of product
//						  calcuproduct(itr);
//					 	  // get the total price of product
//						  totalprice(noitr);
//
//						  totalquantity(noitr);
//
//						  //get the general discount
//						  thegeneraldiscount();
//
//						  //get the general payed
//						  thegeneralpayed();
//
//						  // calculate the rest of debt
//						  therestofdebt();
//
//						  //populate units
//						  getUnits(itr);
//
//						  //add another row if there is no any new rows
//						  $proId = document.getElementById("product"+noitr).value;
//						  if($proId != null && $proId != '-1' && $proId != '')
//						  {
//							 $("#addpro").trigger('click');
//						  }
//						  //load the jquery checker for number only
//						  $.getScript('../views/default/js/head_scripts.js');
//
//						$('.select2_unit'+itr).select2();
//
//					  });

                    $('.select2_unit' + itr).select2();
                });





                /**********************************/
                //populate product select with value and label
                var productId = $("#productid_hidden" + itr).val();
                //alert(" productId : "+productId);
                if (productId != null && productId != '' && productId != '-1')
                {
                    //alert("draw select2");
                    $.ajax({
                        url: 'buyBillControllerAjax.php?do=productData&id=' + productId + '',
                        type: "get",
                        success: function (data) {
                            //alert(data);
                            if (data != null && data != "")
                            {
                                var response = $.parseJSON(data);
                                //send value as a string of id and name to the initSelection function
                                $("#product" + itr).select2('val', ['' + response.id + ':' + response.text + ''], true);// true is a flag to allow triggering the change event which is false by default
                            }
                        },
                        error: function () {
                            alert("لقد حدث خطأ أثناء إجراء العملية");
                        }
                    });

                    //populate units
                    //getUnits(itr);
                }
                /***********************************/

                emptyModalForm();
            } else
            {
                alert("يرجى إدخال البيانات بشكل صحيح");
            }

        }
    });

}


function closeProductForm2()
{
    //empty modal box's inputs' values
    $('#productInfo').reset();
    $("#new_cat_id").val('');
    //$("#new_cat_id").trigger('liszt:updated');
    $("#new_cat_id").select2();

    $("#productId").val('');
    $("#new_productName").val('');

    //reset units
    $unitsItr = $("#unitsItr").val();

    for ($i = 1; $i <= $unitsItr; $i++)
    {
        //removeUnits($i);
        $("#productunit" + $i).val('-1');
        //$("#productunit"+$i).trigger('liszt:updated');
        $("#productunit" + $i).select2();
        //$("#unitsTable").html($("#unitsTableHidden").html());
        $('.select2').select2();
        $('.select2_custom').select2();
        $('select').select2();
    }
}

