//here all method and function that control bill

var calcuproduct;
var totalprice;
var thegeneraldiscount;
var checkthepayed;
var thegeneralpayed;
var therestofdebt;
var addrow;
var getUnits;
var totalquantity;
var return_calcuproduct;
var return_totalprice;

var return_thegeneralpayed;
var return_therestofdebt;
var return_addrow;
var return_totalquantity;
var hideBillPrices = 1;
if ($('#hideBillPrices').length > 0)
    hideBillPrices = document.getElementById("hideBillPrices").value;

var proNumType = $('#proNumType').val();
var numClass = 'positivefloat';
if (proNumType == 1) {
    numClass = 'positiveNo';
}

shortcut.add("f3", function () {
    $("#saveBill").click();
    return false;
});
shortcut.add("f4", function () {
    if ($("#saveAndNew").length > 0) {
        $("#saveAndNew").click();
    } else {
        $("#saveBill").click();
    }
    return false;
});


function newOptionAtInputTooShort() {
    var suppdata = $('#supplier').select2('data');
    $('#supplier').select2('data', {id: -2, text: 'اضافة عميل جديد'}).change();
    $('#supplieridBeforeChange').val(suppdata.id);
    $('#suppliernameBeforeChange').val(suppdata.text);
}
jQuery(document).ready(function () {

    $(".positiveNo").forcepositiveNum();
    $("#parcode1").focus();

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

        var code = (e.keyCode);
        //to stop the submit of the form
        /*alert("onkeypress handler: \n"
         + "keyCode property: " + e.keyCode + "\n"
         + "which property: " + e.which + "\n"
         + "charCode property: " + e.charCode + "\n"
         + "Character Key Pressed: "
         + String.fromCharCode(e.charCode) + "\n"
         );*/
        if (code == 114)//f3 //114 = r not f3 stop this code//fatma
        {
            //            $("#gendis").val("0");
            //            $("#saveAndNew").click();
            //            return false;
        }
        if (code == 113)//f2
        {
            //            $("#gendis").val("0");
            //            $("#supplier").change();
            //            $("#billform").submit();
            //            return false;
        }
    });


    //here the varables in supplier method
    var supplierpagename = 'buyBillControllerAjax.php';
    var supplierid = 1;
    var productpricepagename = 'buyBillControllerAjax.php';

    var parcodeSetting = $("#parcodeSetting").val();
    var newProductSetting = $("#newProductSetting").val();
    var noteSetting = $("#noteSetting").val();
    var productDiscountSetting = $("#productDiscountSetting").val();
    var quantityOrParcodeSetting = $("#quantityOrParcodeSetting").val();
    var unitSetting = $("#unitSetting").val();

    var round_numbers = $("#round_numbers").val();
    $noOfDecimalPlaces = $("#noOfDecimalPlaces").val();
    var scunitname = $('#scunitnamevalue').val();
    var supplierWithAddOption = (Number($('#supplierWithAddOption').val()) == 1) ? 0 : 1;
    var withNakdi = (Number($('#withNakdi').val()) == 1) ? 0 : 1;


    //type determine if the bill is buy or return
    // 0 for buy , 1 for return
    var billtype = 0;

    $('select2').select2();

    $(".select2Supp").select2({
        placeholder: "المورد",
        minimumInputLength: document.getElementById("clientsearchvalue").value,
        //inimumInputLength: 0,
        multiple: false,
        quietMillis: 100,
        formatInputTooShort: function (input, min) {
            var n = min - input.length;


            $lenMsg = '<ul class="select2-results">';
            if (supplierWithAddOption == 1)
                $lenMsg += '<li class="select2-results-dept-0 select2-result select2-result-selectable" onclick="newOptionAtInputTooShort();"><div class="select2-result-label newoption"><span class="newoption">اضافة مورد جديد</span></div></li>';
            $lenMsg += '</ul><div class="select2-result-label"><span>من فضلك أدخل ' + n + ' حروف أكثر</span></div>';

            // Append it to the select
            return $lenMsg;
        },
        ajax: {
            url: "supplierAjaxController.php?do=select2supplier",
            dataType: 'json',
            data: function (term, page) {
                return {
                    term: term, //search term
                    page_limit: 7, // page size
                    withAddOption: supplierWithAddOption,
                    withNakdi: withNakdi,
                    //jsonRowRet: 1,
                };
            },
            results: function (data) {
                return {results: data};
            }
        },
        formatResult: function (data) {
            if (Number(data.id) == -2) {
                return '<span class="newoption">' + data.text + '</span >';
            } else {
                return '<span>' + data.text + '</span >';
            }
        },
        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], productquantity: item[2], price: item[3]};
            callback(data);
        },
        //dropdownCssClass: "bigdrop", // apply css that makes the dropdown taller
    }).on('select2-loaded', function (e) {// not "select2-open" nor "select2-opening" //http://mkurz.github.io/select2/index.html
        $('.newoption').parent().addClass('newoption');
    }).on('change', function (e) {
        if ($('#supplier').select2('data').sullpierCurrencyid > 0 || $('#supplier').val() == '-2') {//it is natural change event from choosing or removing option
            var sullpierCurrencyid = $('#supplier').select2('data').sullpierCurrencyid;
            supplierDebt($(this).val());
            $('#currencyId').val(sullpierCurrencyid).change();
        } else {//this is triggerd change "here it is from submit"
            var sullpierCurrencyid = e.params.data.sullpierCurrencyid;
            $('#supplier').select2('data', {id: e.params.data.id, text: e.params.data.text, sullpierCurrencyid: sullpierCurrencyid});
            supplierDebt($(this).val());
            $("#currencyId").trigger('change', ['submit']);//to use existing cfactor @submit
        }

    })
    //this is needed for ajax =>to obtain id from it  and use in ajax
    $('#supplier').select2('data', {id: $('#oldsupplierid').val(), text: $('#oldsuppliername').val(), sullpierCurrencyid: $('#suppCurr').val()});
    setTimeout(function () {
        //this is needed as we need html to end drawing then put value => without it text will be undefined
        $('#supplier').select2('data', {id: $('#oldsupplierid').val(), text: $('#oldsuppliername').val(), sullpierCurrencyid: $('#suppCurr').val()});
        $("#tempclientName").val($('#supplier').select2('data').text);
    }, 0);

    $(".select2client").select2({
        placeholder: "العميل",
        minimumInputLength: document.getElementById("searchvalue").value,
        inimumInputLength: 0,
        multiple: false,
        quietMillis: 100,
        formatInputTooShort: function (input, min) {
            var n = min - input.length;
            $lenMsg = '<ul class="select2-results">';
            $lenMsg += '</ul><div class="select2-result-label"><span>من فضلك أدخل ' + n + ' حروف أكثر</span></div>';
            // Append it to the select
            return $lenMsg;
        },
        ajax: {
            url: "clientControllerAjax.php?do=select2ClientsAjax",
            dataType: 'json',
            data: function (term, page) {
                return {
                    term: term, //search term
                    page_limit: 7, // page size
                    withAddOption: 0, //supplierWithAddOption,
                    withNakdi: 0, //withNakdi,
                    //jsonRowRet: 1,
                };
            },
            results: function (data) {
                return {results: data};
            }
        },
        formatResult: function (data) {
            if (Number(data.id) == -2) {
                return '<span class="newoption">' + data.text + '</span >';
            } else {
                return '<span>' + data.text + '</span >';
            }
        },
        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], productquantity: item[2], price: item[3]};
            callback(data);
        },
        //dropdownCssClass: "bigdrop", // apply css that makes the dropdown taller
    });
    if ($('#oldclientid').val() > 0) {
        $('#client').select2('data', {id: $('#oldclientid').val(), text: $('#oldclientname').val(), sullpierCurrencyid: $('#suppCurr').val()});
    }

    //to start the itration with default value // 1
    //document.getElementById("hidden_itr").value = 1;

    //the common itration and the start // 2
    // $aw_i = 2;
    $aw_i = document.getElementById("hidden_itr").value;
    $aw_i++;
    //the tabindex to increment in dynmaic load
    $tabindexnum = 8;

    //add new row in bill
    //on click the add button
    /************************/
    $("#addpro").click(function () {
        // $aw_i = document.getElementById("hidden_itr").value;
        // $aw_i++;
        addrow($aw_i, $tabindexnum);
        // fill the iltration filed with common iltration
        document.getElementById("hidden_itr").value = $aw_i;

        // incrementaion of row number and tab index
        $aw_i++
        $tabindexnum++;

        //reload the dropdownlist and jquery files
        //$('select2').select2();
        return false;
    });


    $("#addpro2").click(function () {

        $aw_i = Number(document.getElementById("hidden_itr").value) + 1;

        addrow($aw_i, $tabindexnum);
        // fill the iltration filed with common iltration
        document.getElementById("hidden_itr").value = $aw_i;

        // incrementaion of row number and tab index
        $aw_i++
        $tabindexnum++;

        //reload the dropdownlist and jquery files
        //$('select2').select2();
        return false;
    });
    /************************/


    //add new row in bill
    /**************************/
    addrow = function ($aw_i, $tabindexnum, enterationId = '') {

        var productAndQuantityOnly = $('#productAndQuantityOnly').val();
        var shownumber = document.getElementById("shownumber").value;
        var discountrowtype = document.getElementById("discountrowtype").value;
        var canEditAddDiscountPercentage = document.getElementById("canEditAddDiscountPercentage").value;
        var morestore = document.getElementById("morestore").value;
        var userstoreid = document.getElementById("userstoreid").value;
        var hideBillPricesClass = '';
        if (hideBillPrices == 1) {
            hideBillPricesClass = 'hidden';
        }

        $storeClass = '';
        if (morestore == 0) {
            $storeClass = '';
        } else {
            $storeClass = 'hidden';
        }

        $addedRow = '<tr id="newProduct' + $aw_i + '">';

        if (newProductSetting == 0) {
            $addedRow += '<td><a onclick="javascript:showModalBox(this.name);" class="newLink btn btn-primary btn-xs conformdel"  id="new' + $aw_i + '"  name="' + $aw_i + '">جديد</a></td>';
        }

        if (shownumber == 0) {
            $addedRow += '<td>';
        } else {
            $addedRow += '<td  style="display:none !important">';
        }
        $addedRow += $aw_i + '</td>';

        //# check to hide
        var hidden_parcode = '';
        $('.check_tr_parcode:first').each(function (e) {
            var ths = $(this);
            if (ths.hasClass('hidden')) {
                hidden_parcode = 'hidden';
                return false;
            }
        });

        if (parcodeSetting == 0) {
            $addedRow += '<td class="' + hidden_parcode + '">';
        } else {
            $addedRow += '<td  class="' + hidden_parcode + '">';
        }

        $addedRow += '<input name="parcode' + $aw_i + '" type="text" id="parcode' + $aw_i + '" class="form-control txt-nonraduis"  onkeypress="getproductbyParcode(event,this.value, ' + $aw_i + ');"   autocomplete="off" placeholder="الباركود" tabindex="' + $tabindexnum + '"/></td>'

        if (userstoreid == 0) {
            $addedRow += '<td class="' + $storeClass + '"> <div id="prstoridsiv' + $aw_i + '">' +
                    '<select class="select2 clientstore wdt100" name="prstorid' + $aw_i + '" id="prstorid' + $aw_i + '">' +
                    $("#addstore").html() +
                    '</select></div>' +
                    '</td>';
        } else if (userstoreid != 0) {
            $addedRow += '<td class="' + $storeClass + '"> <div id="prstoridsiv' + $aw_i + '">'
                    + ' <input name="prstorid' + $aw_i + '" id="prstorid' + $aw_i + '" class="selectstore clientstore" type="hidden" value="' + $('#userstoreidForClient').val() + '" />'
                    + $("#addstore2").html()

                    + '  </div></td>';
        }


        if ($('#billtype2').length > 0 && $('#billtype2').val() == "1") {
            $addedRow += '<td>'
                    + '<div style="display: inline">'
                    + '<select class="select2 productCat productCat' + $aw_i + '" style="width:30%;display: inline" data-level="0" data-itr ="' + $aw_i + '" name="productCatId0_' + $aw_i + '" id="productCatId0_' + $aw_i + '" >'
                    + $('#cats').html()
                    + '</select>'
                    + ' </div>'
                    + '<input type="hidden" id="level_' + $aw_i + '" data-itr ="' + $aw_i + '" name="level_' + $aw_i + '" value="0">'
                    + '<div id="manyParents_' + $aw_i + '"  data-itr ="' + $aw_i + '" style="display: inline">'

                    + '</div>'
                    + '</td>';
        } else {
            $addedRow += '<td>'
                    + '<div id="productdiv' + $aw_i + '" >'
                    + '<input type="hidden" id="product' + $aw_i + '" name="product' + $aw_i + '" data-placeholder="اختر" class="select2product' + $aw_i + ' wdt100"  tabindex="' + $tabindexnum + '"/></div></td>';
        }
        if (noteSetting == 0) {
            $addedRow += ' <td>'
                    + '    <input name="note' + $aw_i + '" id="note' + $aw_i + '" size="3"  type="text" class="form-control  txt-nonraduis" tabindex="' + $tabindexnum + '"/>'
                    + '    </td>';
        }





        //# check to hide
        var hidden_unit = '';
        $('.check_tr_unit').each(function (e) {
            var ths = $(this);
            if (ths.hasClass('hidden')) {
                hidden_unit = 'hidden';
                return false;
            }
        });

        var hidden_quantity = '';
        $('.check_tr_quantity').each(function (e) {
            var ths = $(this);
            if (ths.hasClass('hidden')) {
                hidden_quantity = 'hidden';
                return false;
            }
        });
        if (unitSetting == 0) {
            $addedRow += '<td class="' + hidden_unit + '">';
        } else {
            $addedRow += '<td  class="' + hidden_unit + '">';
        }

        //# check to hide
        var hidden_discount = '';
        $('.check_tr_discount:first').each(function (e) {
            var ths = $(this);
            if (ths.hasClass('hidden')) {
                hidden_discount = 'hidden';
                return false;
            }
        });

        $addedRow += '<div id="unitDiv' + $aw_i + '">'
                + '    <select name="unitId' + $aw_i + '" id="unitId' + $aw_i + '"  size="3"  onchange="getUnitPrice(' + $aw_i + ');"  data-placeholder="اختر" class="select2_custom aw_m1 "  tabindex="' + $tabindexnum + '">'
                + '    </select>'
                + '    </div>'
                + '    </td>'


                + '<td class="' + hidden_quantity + '"><input name="pronum' + $aw_i + '" id="pronum' + $aw_i + '" value="1"  placeholder="العدد" class="form-control getprototal  txt-nonraduis numberclic enteraction numberinput ' + numClass + '" type="text" tabindex="' + $tabindexnum + '" /></td>';



        if (Number(scunitname) == 0) {
            $addedRow += '<td style="display:none !important;"><input name="scunitname' + $aw_i + '" id="scunitname' + $aw_i + '" value="0" class="form-control  txt-nonraduis  numberclic   positiveNo" type="text" tabindex="' + $tabindexnum + '"  /></td>';

        } else {
            $addedRow += '<td ><input name="scunitname' + $aw_i + '" id="scunitname' + $aw_i + '" value="0" class="form-control  txt-nonraduis  numberclic   positiveNo" type="text" tabindex="' + $tabindexnum + '"  /></td>';

        }




        //        if (productAndQuantityOnly != 1)
        //        {
        //            $addedRow += '<td style="display:none !important;"><div id="propricechange' + $aw_i + '"><input name="proprice' + $aw_i + '" id="proprice' + $aw_i + '" value="0" class="form-control getprototal txt-nonraduis  numberclic enteraction numberinput positiveNo" type="text" tabindex="' + $tabindexnum + '"  placeholder="السعر"/></div></td>';
        //        } else
        //        {
        $addedRow += '<td class="' + hideBillPricesClass + '"><div id="propricechange' + $aw_i + '"><input name="proprice' + $aw_i + '" id="proprice' + $aw_i + '" value="0" class="form-control getprototal txt-nonraduis  numberclic enteraction numberinput positiveNo" type="text" tabindex="' + $tabindexnum + '"  placeholder="السعر"/></div></td>';
        //}

        //        if (productAndQuantityOnly != 1)
        //        {
        //            $addedRow += '<td style="display:none !important;"><input name="prodis' + $aw_i + '" id="prodis' + $aw_i + '" value="0"  size="3" class="form-control getprototal  txt-nonraduis numberonly enteraction numberinput positiveNo" type="text" tabindex="' + $tabindexnum + '"  placeholder="الخصم"/></td>';
        //        } else
        //        {

        $addedRow += '<td class="' + hidden_discount + ' ' + hideBillPricesClass + '">';
        $addedRow += '      <input name="prodis' + $aw_i + '" id="prodis' + $aw_i + '" value="0"  size="3" class="form-control getprototal  txt-nonraduis numberonly enteraction numberinput positiveNo" tabindex="' + $tabindexnum + '"  placeholder="الخصم" ';
        if (discountrowtype == 0) {
            $addedRow += ' type="text" ';
        } else {
            $addedRow += ' type="hidden" ';
        }
        $addedRow += '/> <input name="discounttype' + $aw_i + '" id="discounttype' + $aw_i + '"  value="0" size="3" class="form-control getprototal numberonly enteraction numberinput txt-nonraduis positivefloat" tabindex="' + $tabindexnum + '" ';
        if (discountrowtype == 1) {
            $addedRow += ' type="text" ';
        } else {
            $addedRow += ' type="hidden" ';
        }
        $addedRow += ' />';
        $addedRow += '      <input type="hidden" name="realprice_precentage' + $aw_i + '" value="0" id="realprice_precentage' + $aw_i + '" /></td>';

        //}

        //# check to hide
        var hidden_tax = '';
        $('.check_tr_tax:first').each(function (e) {
            var ths = $(this);
            if (ths.hasClass('hidden')) {
                hidden_tax = 'hidden';
                return false;
            }
        });

        $addedRow += '<td class=" ' + hidden_tax + ' ' + hideBillPricesClass + '">'
                + '           <input name="rowtaxval' + $aw_i + '" id="rowtaxval' + $aw_i + '" value="0" class="form-control getprototal numberonly enteraction numberinput txt-nonraduis positiveNo" placeholder="ضريبة" type="hidden"/>'
                + '           <input name="rowtaxper' + $aw_i + '" id="rowtaxper' + $aw_i + '"  value="0" class="form-control getprototal numberonly enteraction numberinput txt-nonraduis positiveNo" tabindex="' + $tabindexnum + '"  type="text" />'
                + '   </td>';

        //        if (productAndQuantityOnly != 1)
        //        {
        //            $addedRow += '<td class="aw_totalprice" style="display:none !important;">'
        //                    + '<input  name="hidden_prototal' + $aw_i + '" id="hidden_prototal' + $aw_i + '" class="editTotal form-control txt-nonraduis enteraction numberinput positiveNo" value="0" type="text"/>'
        //                    + '</td>';
        //        } else
        //        {

        //# check to hide
        var hidden_buydiscount = '';
        $('.buydiscountClass:first').each(function (e) {
            var ths = $(this);
            if (ths.hasClass('hidden')) {
                hidden_buydiscount = 'hidden';
                return false;
            }
        });
        var typeis = (canEditAddDiscountPercentage == 1) ? "text" : "hidden";
        $addedRow += '<td ' + hidden_buydiscount + '>';
        if (canEditAddDiscountPercentage != 1)
            $addedRow += '<span id="probuyDiscountPer_span' + $aw_i + '">0</span>';
        $addedRow += ' <input name="probuyDiscountPer' + $aw_i + '" id="probuyDiscountPer' + $aw_i + '" value="0" class="form-control txt-nonraduis positiveNo probuyDiscountPerClass getprototal" tabindex="7" type="' + typeis + '"/></td>';
        $addedRow += '<td class="aw_totalprice">'
                + '<input  name="hidden_prototal' + $aw_i + '" id="hidden_prototal' + $aw_i + '" class="editTotal form-control txt-nonraduis enteraction numberinput positiveNo" value="0" type="text"/>'
                + '</td>';
        //}



        $addedRow += '<td>	<button type="button" id="remove' + $aw_i + '" class="removeproduct close flt-none" aria-hidden="true"   onclick="removeproduct(' + $aw_i + ');" >&times;</button>'
                + '</td>'
                + '</tr>';

        //add the new row with itration and with all propperties
        $("#containerpros").append($addedRow);

        $(".positiveNo").forcepositiveNum();
        $(".positivefloat").forcepositivefloat();
        $('select').select2();

        //assign select2 properties
        if (morestore == 0) {
            $(".select2product" + $aw_i).select2({
                placeholder: "إسم المنتج",
                //minimumInputLength: 3,
                minimumInputLength: document.getElementById("searchvalue").value,
                //	  maximumSelectionSize:3,
                multiple: false,
                quietMillis: 100,
                ajax: {
                    url: "buyBillControllerAjax.php?do=getProductsnotcollective",
                    dataType: 'json',
                    data: function (term, page) {
                        return {
                            term: term, //search term
                            page_limit: 10, // page size
                            storeid: document.getElementById("prstorid" + $aw_i).value,
                            stopStoreSearch: document.getElementById("stopStoreSearch").value,
                            searchWithCatAndProductNameOnly: document.getElementById("searchWithCatAndProductNameOnly").value,
                        };
                    },
                    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);
                },
                formatSelection: function (data) {
                    $choice = data.text;
                    if (data.productquantity)
                        $choice += '<span  style="text-align: left;float: left;  font-weight: bold;color: blue;">ك:' + Number(data.productquantity) + '</span>';
                    return $choice;
                },
            }).on('change', function (e) {
                var thisitr = $(this).attr('id').substr(7);
                $('#pronum' + thisitr).focus();
            });
        } else {
            $(".select2product" + $aw_i).select2({
                placeholder: "إسم المنتج",
                //minimumInputLength: 3,
                minimumInputLength: document.getElementById("searchvalue").value,
                //	  maximumSelectionSize:3,
                multiple: false,
                quietMillis: 100,
                ajax: {
                    url: "buyBillControllerAjax.php?do=getProductsnotcollective",
                    dataType: 'json',
                    data: function (term, page) {
                        return {
                            term: term, //search term
                            page_limit: 10, // page size
                            storeid: document.getElementById("storeId").value,
                            stopStoreSearch: document.getElementById("stopStoreSearch").value,
                            searchWithCatAndProductNameOnly: document.getElementById("searchWithCatAndProductNameOnly").value,
                        };
                    },
                    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);
                },
                formatSelection: function (data) {
                    $choice = data.text;
                    if (data.productquantity)
                        $choice += '<span  style="text-align: left;float: left;  font-weight: bold;color: blue;">ك:' + Number(data.productquantity) + '</span>';
                    return $choice;
                },
            }).on('select2:select', function (e) {
                var thisitr = $(this).attr('id').substr(7);
                $('#pronum' + thisitr).focus();
            });
        }
        //choose main store for the row
        if (morestore == 0) {
            var lastValue = $('select[id^="prstorid"]').filter(function () {
                var itr = $(this).attr('id').substr(8);
                return ($(this).val() !== null && itr != $aw_i && (Number($(this).val()) > 0 || $(this).val().indexOf("hasSizeColor") == 0));
            }).last().val();
            $("#prstorid" + $aw_i).val(lastValue).trigger('change.select2');
        } else {
            if (Number($("#storeId").val()) > 0) {//$("#storeid").is(":visible") &&
                //            var storeidData = $("#storeid").select2('data')
                //            $("#prstorid" + $aw_if).select2('data', {id: storeidData.id, text: storeidData.text});
                $("#prstorid" + $aw_i).val($("#storeId").val()).trigger('change.select2');
            }
        }



        $(".numberinput").forceNumeric();

        // varaible to contains the common itration
        var n = $aw_i;
        var tbindexn = $tabindexnum;

        //action in change of created dropdown list  to load the price
        $("#product" + n).on("change", function (e) {
            var fromProSizeColor = $(this).select2('data').fromProSizeColor;
            var priceFromProSizeColor = $(this).select2('data').price;

            checkForRepeatedProducts(n, 0);
            //here  will get the price for every product
            //the selected value in drop down list
            var theselectedvalue = e.target.value;

            var returnBillFlag = 0;
            var supplier = $('#supplier').val();
            var comingproserial = 0;//$(this).select2('data').comingproserial;
            var parcode = $('#parcode_re' + n).val();

            //using the load method to load the price
            // $("#propricechange"+n).html('<img src="../views/default/images/loader/6.gif" alt="">');
            //////////////////////////////////////////////////
            $.ajax({
                url: 'buyBillControllerAjax.php?do=units&&return=' + returnBillFlag + '&itrs=' + n + '&tabindex=' + tbindexn + '&productid=' + theselectedvalue + '&supplier=' + supplier + '&billnameid=' + $('#billnameid').val() + '&comingproserial=' + comingproserial + '&parcode=' + parcode,
                type: "get",
                success: function (data) {
                    // alert(data);
                    var response = $.parseJSON(data);
                    //populate unit
                    $('#unitDiv' + n).html(response.unitString);
                    $('#parcode' + n).val(response.parcodeString);

                    $("#productUnitsDiv").empty();
                    $("#unitDiv" + n + " option").clone().appendTo("#productUnitsDiv");
                    $('.select2_unit' + n).select2();

                    //populate buy price
                    $('#propricechange' + n).html(response.priceString);
                    $(".positiveNo").forcepositiveNum();
                    //change price of product from main curr to slected curr val
                    $('#proprice' + n).val(getValueInTermsOfSelectedCurrency($('#proprice' + n).val()));


                    var productpricetype = document.getElementById("productpricetype" + n).value;
                    if (productpricetype == 1) {
                        $('#proprice' + n).css("background-color", "#B7DFA4");
                        $('#propricechange' + n).css("background-color", "#B7DFA4");
                    } else {
                        $('#proprice' + n).css("background-color", "#FFF");
                        $('#propricechange' + n).css("background-color", "#FFF");
                    }


                    var productData = $("#product" + n).select2('data');
                    if (productData.isProUnitParcode == 1) {
                        $('#unitId' + n).val(productData.productunitid).change();
                        $('#proprice' + n).val(productData.proUnitBuyPrice);
                    }
                    $('#probuyDiscountPer' + n).val(productData.buydiscountpercent);
                    $('#probuyDiscountPer_span' + n).html(productData.buydiscountpercent);

                    if (fromProSizeColor == 1)
                        $('#proprice' + n).val(priceFromProSizeColor);
                    //here all code that will happend with loading contants
                    //the number of rows of products
                    var noitr = document.getElementById("hidden_itr").value

                    //to calculate the price and amount with discount
                    calcuproduct(n);

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

                    totalquantity(n);

                    //get the general discount
                    thegeneraldiscount();

                    checkthepayed();

                    // this function used for changing discount value based on bill setting تطبيق نسب الخصم فى فاتورة الشراء
                    change_discount_val(n, response.buypricereal_precentage);
                    $('#realprice_precentage' + n + '').val(response.buypricereal_precentage);

                    //get the general payed
                    thegeneralpayed();

                    // calculate the rest of debt
                    therestofdebt();

                    var quantityOrParcodeSetting = $("#quantityOrParcodeSetting").val();
                    if ((Number($aw_i) - Number(n)) == 1) {

                        if (quantityOrParcodeSetting == 0) {
                            $("#pronum" + n).focus();
                            $("#pronum" + n).select();
                        } else {
                            $("#parcode" + $aw_i).focus();
                            $("#parcode" + $aw_i).select();
                        }

                        // fill the iltration filed with common iltration

                    } else {
                        if (quantityOrParcodeSetting == 0) {
                            $("#pronum" + n).focus();
                            $("#pronum" + n).select();
                        } else {
                            $("#parcode" + $aw_i).focus();
                            $("#parcode" + $aw_i).select();
                        }
                    }

                    //add another row if there is no new rows
                    $proId = document.getElementById("product" + noitr).value;
                    if ($proId != null && $proId != '-1' && $proId != '') {
                        $("#addpro").trigger('click');
                    }
                },
                error: function () {
                    alert("لقد حدث خطأ أثناء إجراء العملية");
                }
            });
            //////////////////////////////////////////////////
        });


        //
        if (enterationId.startsWith('pronum')) {//pronum1//pronum_re1
            //means i press enter while being in pronum field
            if ($("#parcode" + n).is(":visible")) {
                //so focus parcode
                $("#parcode" + n).focus();
            } else {
                $("#product" + n).select2('focus');
                //$("#product" + n).select2('open');
            }
        } else {
            if (quantityOrParcodeSetting == 0) {
                var nold = Number(n) - 1;
                $("#pronum" + nold).focus();
            } else {
                $("#parcode" + n).focus();
            }
    }
    }

    /********************************************************************************/


    var formatResult = function (data) {
        //var cfactor = $('#currencyId').select2("data").element[0].attributes['data-cfactor'].value;
        var cfactor = $('#cFactor').val();
        data.price = Number((data.price * cfactor).toFixed(4));

        $choice = data.text;
        if (hideBillPrices != 1)
            $choice += '<span  style="text-align: left;  float: left;  width: 30%;">' + data.price + '</span >';

        $choice += '<span  style="float: left;  margin-left: 5px;"  > ' + data.productquantity + '';
        return $choice;
    }


    var morestore = document.getElementById("morestore").value;
    if (morestore == 0) {
        $('.select2product').select2({
            placeholder: "إسم المنتج",
            //minimumInputLength: 3,
            minimumInputLength: document.getElementById("searchvalue").value,
            multiple: false,
            quietMillis: 100,
            ajax: {
                url: "buyBillControllerAjax.php?do=getProductsnotcollective",
                dataType: 'json',
                data: function (term, page) {
                    return {
                        term: term, //search term
                        page_limit: 10, // page size
                        storeid: document.getElementById("prstorid1").value,
                        stopStoreSearch: document.getElementById("stopStoreSearch").value,
                        searchWithCatAndProductNameOnly: document.getElementById("searchWithCatAndProductNameOnly").value,
                    };
                },
                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);
            },
            formatSelection: function (data) {
                $choice = data.text;
                if (data.productquantity)
                    $choice += '<span  style="text-align: left;float: left;  font-weight: bold;color: blue;">ك:' + Number(data.productquantity) + '</span>';
                return $choice;
            },
        }).on('change', function (e) {
            var thisitr = $(this).attr('id').substr(7);
            $('#pronum' + thisitr).focus();
        });
    } else {
        $('.select2product').select2({
            placeholder: "إسم المنتج",
            //minimumInputLength: 3,
            minimumInputLength: document.getElementById("searchvalue").value,
            multiple: false,
            quietMillis: 100,
            ajax: {
                url: "buyBillControllerAjax.php?do=getProductsnotcollective",
                dataType: 'json',
                data: function (term, page) {
                    return {
                        term: term, //search term
                        page_limit: 10, // page size
                        storeid: document.getElementById("storeId").value,
                        stopStoreSearch: document.getElementById("stopStoreSearch").value,
                        searchWithCatAndProductNameOnly: document.getElementById("searchWithCatAndProductNameOnly").value,
                    };
                },
                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);
            },
            formatSelection: function (data) {
                $choice = data.text;
                if (data.productquantity)
                    $choice += '<span  style="text-align: left;float: left;  font-weight: bold;color: blue;">ك:' + Number(data.productquantity) + '</span>';
                return $choice;
            },
        }).on('change', function (e) {
            var thisitr = $(this).attr('id').substr(7);
            $('#pronum' + thisitr).focus();
        });
    }


    $('.select2productSC').select2({
        placeholder: "إسم المنتج",
        //minimumInputLength: 3,
        minimumInputLength: document.getElementById("searchvalue").value,
        multiple: false,
        quietMillis: 100,
        ajax: {
            url: "buyBillControllerAjax.php?do=getProductsHasSizeAndColor",
            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) {
            $choice = data.text;
            return $choice;
        },
        initSelection: function (element, callback) {
            var item = element.val().split(':');
            var data = {id: item[0], text: item[1]};
            callback(data);
        },
        formatSelection: function (data) {
            $choice = data.text;
            return $choice;
        },
    }).on('change', function () {
        var productId = $(this).val();
        var storeId = $('#storeId').val();
        $.post("productControllerAjax.php?do=getProductsSizesAndColors", {productId: productId, storeId: storeId}, function (res) {
            $('#SizeColorTB_eman').html(res);
        });
    });
    $('#doAddProWithSC').on('click', function (e) {
        var sizeColorItr = $('#sizeColorItr_eman').val();
        var proid = $('#productSC').val();
        for (var i = 1; i <= sizeColorItr; i++) {
            var lastRow = $('#containerpros tr:last').attr('id');
            var lastitr = lastRow.substr(10);
            if ($('#size_detail' + i).length > 0) {
                var barcode = $('#parcode_detail' + i).val();
                var sizeid = $('#size_detail' + i).val();
                var colorid = $('#color_detail' + i).val();
                var quantity = $('#quantity' + i).val();
                var price = $('#price' + i).val();
                var productidComplex = "hasSizeColor" + proid + "-" + sizeid + "-" + colorid;
                var productNameComplex = $('#productSC').select2('data').text + "/" + $('#sizeName' + i).val() + "/" + $('#colorName' + i).val();
                if ($('#product' + lastitr).val() != '') {
                    $("#addpro").trigger('click');
                }
                var lastRow = $('#containerpros tr:last').attr('id');
                var newitr = lastRow.substr(10);
                $('#proprice' + newitr).val(getValueInTermsOfSelectedCurrency(price));
                $('#pronum' + newitr).val(quantity);
                $('#pronum' + newitr).keyup();
                // alert(newitr);
                $('#product' + newitr).select2('data', {
                    id: productidComplex, text: productNameComplex
                    , proUnitBuyPrice: price
                    , price: price
                    , userEnteredParcode: barcode
                    , productquantity: quantity,
                    fromProSizeColor: 1
                }, true);

            }
        }
        $('#SizeColorTB_eman').html('');
        $('#productSC').val('');
        $('.select2productSC').select2('data', {text: ''});
        $('#proSizeColorModal').modal('hide');
    })
    /************************/
    // get product units
    /************************/
    getUnits = function ($itrr) {
        $productid = document.getElementById("product" + $itrr).value;
        var supplier = $('#supplier').val();
        $('#unitDiv' + $itrr).load('buyBillControllerAjax.php?do=units&&itrs=' + $itrr + '&productid=' + $productid + '&supplier=' + supplier + '&billnameid=' + $('#billnameid').val(), function () {
            //reload the dropdownlist and jquery files
            $('.select2_unit' + $itrr).select2();

            $('select').select2();

            //populate unit price
            $("#unitId" + $itrr).trigger("change");
        });
    }


    /**************************/
    // the delete action that delete row of products
    /************************/
    $(document).on('click', '.removeproduct', function () {//
        //
        //		// delete by partents
        //		$(this).parent().parent().remove();
        //
        //		// get the itration from itration colum
        //		$remitr = document.getElementById("hidden_itr").value

        //		// get the total price of product
        //		totalprice($remitr);
        //
        //		//get the general discount
        //		thegeneraldiscount();
        //		checkthepayed();
        //		//get the general payed
        //		thegeneralpayed();
        //
        //		// calculate the rest of debt
        //		therestofdebt();
        //
        //		document.getElementById("hidden_itr").value = Number($remitr) - 1;
        //
        //		//reduce number of products //عدد القطع
        //		$("#totalQty").html( Number($remitr) - 1);
        //		//$aw_i--;
        //		//$tabindex--;

        //		return false;
    });

    /************************/
    // calculating the product price
    // on keyup action
    /************************/
    $(document).on('keyup', ".getprototal", function (e) {

        //the id of selected row
        var currentId = $(this).attr('id');

        //get the num from this method
        var newword = currentId.slice(0, 4);

        //the number of ilteration
        var thecolnmu = 0;
        //see what chase
        switch (newword) {
            case "prop":
                thecolnmu = currentId.substr(8);
                break;
            case "pron":
                // if ($('#enablequantityfractions').val() != 1) {
                //     if ($(this).val() % 1 > 0)
                //         $(this).val(Math.round($(this).val())).keyup();
                // }
                thecolnmu = currentId.substr(6);
                var buypricereal_precentage = 0;
                if ($('#realprice_precentage' + thecolnmu + '').length > 0) {
                    buypricereal_precentage = $('#realprice_precentage' + thecolnmu + '').val()
                }

                // this function used for changing discount value based on bill setting تطبيق نسب الخصم فى فاتورة الشراء
                change_discount_val(thecolnmu, buypricereal_precentage);
                break;
            case "prod":
                thecolnmu = currentId.substr(6);
                break;
            case "disc":
                thecolnmu = currentId.substr(12);
                break;
            case "rowt":
                thecolnmu = currentId.substr(9);
                break;
            case "prob":
                thecolnmu = currentId.substr(17);
                break;
            default:
                thecolnmu = 0;
        }



        // get the total of product
        calcuproduct(thecolnmu);

        var noitr = document.getElementById("hidden_itr").value

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

        //calculate total quantity
        totalquantity(noitr);

        //get the general discount
        thegeneraldiscount();
        checkthepayed();
        //get the general payed
        thegeneralpayed();

        // calculate the rest of debt
        therestofdebt();

        if (e.keyCode == 65)//If CTRL+A has been pressed (SELECT ALL)
        {
            $('#pronum' + thecolnmu).select();
        }

    });
    //if buy product change inform user if he want to change other prices
    $("input[id^='proprice']").live('blur', function () {
        var showProPriceUpdateModalIfBuyPriceChange = Number($('#showProPriceUpdateModalIfBuyPriceChange').val());
        if (showProPriceUpdateModalIfBuyPriceChange == 0) {
            var itr = $(this).attr('id').slice(8);
            var productId = $('#product' + itr).val();
            var newBuyPrice = Number($(this).val());
            var oldProPrice = Number($('#product' + itr).select2('data').price);
            if (productId != "" && newBuyPrice != 0 && newBuyPrice != oldProPrice) {
                $('#proPriceInfo').html('');
                $('#saveProPricesBtn').data('rowItr', itr);
                $.ajax({
                    type: 'POST',
                    url: 'buyBillControllerAjax.php?do=getProPriceUpdateModalData&id=' + productId + '&newBuyPrice=' + newBuyPrice,
                    success: function (data) {
                        $('#proPriceInfo').html(data);
                        $('#proPriceUpdateModal').modal('show');
                        setTimeout(function () {
                            $('#productBuyPrice1').first().focus();
                        }, 300)

                    }
                });

            }
        }
    });
    function saveProPrices() {
        if (!$('#saveProPricesBtn').hasClass('processing...')) {
            $('#saveProPricesBtn').addClass('processing...');
            $.ajax({
                type: 'POST',
                url: 'buyBillControllerAjax.php?do=updateProPriceOnlyFromModal',
                data: $('#proPriceInfo').serialize(),
                success: function (data) {
                    $('#proPriceUpdateModal').modal('hide');
                    setTimeout(function () {
                        $('#saveProPricesBtn').removeClass('processing...');
                        var nextItr = Number($('#saveProPricesBtn').data('rowItr')) + 1;
                        $('#product' + nextItr).select2('focus');
                    }, 300)

                }
            });
        }
    }
    $(document).on('click', "#saveProPricesBtn", function (e) {
        saveProPrices();
    });
    $(document).on('keypress', "#proPriceUpdateModal input[type='text']", function (e) {
        if (e.which == 13 && $('#proPriceUpdateModal').is(':visible')) {
            saveProPrices();
        }
    });
    /************************/
    $(document).on('change', ".editTotal", function () {

        //the id of selected row
        var currentId = $(this).attr('id');

        //get the num from this method
        var thecolnmu = currentId.substr(15);
        var totalVal = $(this).val();
        var pronum = $("#pronum" + thecolnmu).val();

        var prodis = $("#prodis" + thecolnmu).val();
        if (prodis == 0) {
            $("#proprice" + thecolnmu).val(totalVal / pronum);
        } else {
            $("#proprice" + thecolnmu).val((+totalVal + +prodis) / pronum);
        }
        //get the total price of sell
        var noitr = document.getElementById("hidden_itr").value
        totalprice(noitr);
        //get the general discount
        thegeneraldiscount();
    });


    // here the frist action on frist dropdownlist
    /************************/
    $("#product1").on("change", function (e) {
        checkForRepeatedProducts(1, 0);

        var d = $("#product1").select2("data");

        //alert('xxxxxxxxxxx');
        //here get the price of product from ajax
        //the selected value of drop downlsit
        var theselectedvalue = e.target.value;

        var comingproserial = 0;//$(this).select2('data').comingproserial;
        var parcode = $('#parcode1').val();

        var returnBillFlag = 0; //indicates that this is not return buy bill
        var supplier = $('#supplier').val();
        //using the load method to load the price
        // $("#propricechange1").html('<img src="../views/default/images/loader/6.gif" alt="">');
        //////////////////////////////////////////////////
        $.ajax({
            url: 'buyBillControllerAjax.php?do=units&&return=' + returnBillFlag + '&itrs=1&tabindex=7&productid=' + theselectedvalue + '&supplier=' + supplier + '&billnameid=' + $('#billnameid').val() + '&comingproserial=' + comingproserial + '&parcode=' + parcode,
            type: "get",
            success: function (data) {
                var response = $.parseJSON(data);
                //populate unit
                $('#unitDiv1').html(response.unitString);
                $('#parcode1').val(response.parcodeString);
                $("#productUnitsDiv").empty();
                $("#unitDiv1 option").clone().appendTo("#productUnitsDiv");
                $('.select2_unit1').select2();
                //$('#prodis1').val('55');
                //populate buy price
                $('#propricechange1').html(response.priceString);
                //change price of product from main curr to slected curr val
                $('#proprice1').val(getValueInTermsOfSelectedCurrency($('#proprice1').val()));
                $(".positiveNo").forcepositiveNum();

                var productpricetype = document.getElementById("productpricetype1").value;
                if (productpricetype == 1) {
                    $('#proprice1').css("background-color", "#B7DFA4");
                    $('#propricechange1').css("background-color", "#B7DFA4");
                } else {
                    $('#proprice1').css("background-color", "#FFF");
                    $('#propricechange1').css("background-color", "#FFF");
                }



                var productData = $("#product1").select2('data');
                if (productData.isProUnitParcode == 1) {
                    $('#unitId1').val(productData.productunitid).change();
                    $('#proprice1').val(productData.proUnitBuyPrice);
                }
                $('#probuyDiscountPer1').val(productData.buydiscountpercent);
                $('#probuyDiscountPer_span1').html(productData.buydiscountpercent);

                if (d.fromProSizeColor == 1)
                    $('#proprice1').val(d.price);

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

                // get the total of product
                calcuproduct(1);

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

                totalquantity($aw_i);

                // this function used for changing discount value based on bill setting تطبيق نسب الخصم فى فاتورة الشراء
                change_discount_val(1, response.buypricereal_precentage);
                $('#realprice_precentage1').val(response.buypricereal_precentage);
                //get the general discount
                thegeneraldiscount();

                checkthepayed();

                //get the general payed
                thegeneralpayed();

                // calculate the rest of debt
                therestofdebt();
                var quantityOrParcodeSetting = $("#quantityOrParcodeSetting").val();


                if (quantityOrParcodeSetting == 0) {
                    $("#pronum1").focus();
                    $("#pronum1").select();
                } else {
                    $("#parcode1").focus();
                    $("#parcode1").select();
                }




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


    });


    change_discount_val = function (n, buypricereal_precentage) {

        var hide_discount = $('#hide_discount').val();

        if (hide_discount == '0' && buypricereal_precentage != '') {
            buypricereal_precentage = Number(buypricereal_precentage);
            var pronum = Number($('#pronum' + n + '').val());
            var proprice = Number($('#proprice' + n + '').val());
            var prodis_real = (buypricereal_precentage * pronum * proprice) / 100;
            document.getElementById('prodis' + n + '').value = prodis_real;

            var probuyDiscountPer = $("#probuyDiscountPer" + n).val();
            var buyDiscountVal = 0;
            if (probuyDiscountPer > 0) {
                buyDiscountVal = (proprice * pronum) * probuyDiscountPer / 100;
            }

            var hidden_prototal = (proprice * pronum) - prodis_real - buyDiscountVal;
            $('#hidden_prototal' + n + '').val(hidden_prototal);
        }
    }

    change_discount_val_re = function (n, buypricereal_precentage) {

        // alert(1011);
        var hide_discount = $('#hide_discount').val();
        if (hide_discount == '0' && buypricereal_precentage != '') {
            var pronum = $('#pronum_re' + n + '').val();

            //##get price
            var proprice = $('#proprice_re' + n + '').val();
            var productData = $("#product_re" + n).select2('data');
            if (productData.isProUnitParcode == 1) {
                proprice = productData.proUnitBuyPrice;
            }

            console.log('buypricereal_precentage = ' + buypricereal_precentage + ' proprice = ' + proprice + ' pronum = ' + pronum);
            var prodis_real = (buypricereal_precentage * pronum * proprice) / 100;


            $('#prodis_re' + n + '').val(prodis_real);



            document.getElementById('hidden_prototal_re' + n + '').value = prodis_real;

            var hidden_prototal = (pronum * proprice) - prodis_real;
            // alert(hidden_prototal);
            $('#hidden_prototal_re' + n + '').val(hidden_prototal);
        }
    }

    /************************/
    // get the total price
    /************************/
    totalprice = function ($ix) {
        // variable that will carry total price
        var thealltotal = 0;
        var buyed_thealltotal = "";
        var returned_thealltotal = "";

        $round_numbers = $("#round_numbers").val();
        $noOfDecimalPlaces = $("#noOfDecimalPlaces").val();
        //$ix= document.getElementById("hidden_itr").value;
        //alert($ix);

        var $ix = document.getElementById("hidden_itr").value
        //loop to sum the all prices
        for ($x = 1; $x <= $ix; $x++) {
            var numco = $x;
            var inputname = "#hidden_prototal" + numco;

            //alert("hidden_prototal"+numco+$("#hidden_prototal"+numco).length);
            //to make sure that all input is created
            if ($("#hidden_prototal" + numco).length == 0) {
                var trrownor = $("#containerpros>tbody>tr").length;

                if (trrownor == 0) {

                    $("#buyBillTotal").html(0);
                    $('#totalBuyBill').val(0);
                    if ($("#norbuyBillTotal").length > 0) {
                        $("#norbuyBillTotal").val(0);
                    }
                }
                continue;
            } else {
                //Calculate it again to make sure that there are no errors in calculations
                calcuproduct(numco);

                if ($('#product' + numco).val() != "" && Number($('#product' + numco).val()) != -1) {
                    // sum method
                    buyed_thealltotal = Number(buyed_thealltotal) + Number(document.getElementById("hidden_prototal" + numco).value);
                    //check round number property
                    if ($round_numbers == 0) //التقريب لأقرب عدد صحيح
                    {
                        //alert(222);

                        buyed_thealltotal = Math.round(buyed_thealltotal);
                    } else //التقريب لأقرب رقم
                    {

                        //alert(1);
                        //alert(buyed_thealltotal);

                        //buyed_thealltotal = Math.round(buyed_thealltotal*10)/10;
                        buyed_thealltotal = (buyed_thealltotal).toFixed($noOfDecimalPlaces);
                        //alert(2);
                        //alert(buyed_thealltotal);

                    }

                    $("#buyBillTotal").html(buyed_thealltotal);
                    $('#totalBuyBill').val(buyed_thealltotal);

                    if ($("#norbuyBillTotal").length > 0) {
                        $("#norbuyBillTotal").val(buyed_thealltotal);
                    }
                }
            }
        }

        $return_itr = document.getElementById("hidden_itr_re").value;

        //loop to sum the all prices
        for ($x = 1; $x <= $return_itr; $x++) {
            var numco = $x;
            var inputname = "#hidden_prototal_re" + numco;


            //to make sure that all input is created
            if ($("#hidden_prototal_re" + numco).length == 0) {

                var trrownor_re = $("#containerpros_re>tbody>tr").length;

                if (trrownor_re == 0) {

                    $("#buyBillTotal_re").html(0);
                    $("#returnBuyBillTotal").val('0');
                    if ($("#norbuyBillTotal_re").length > 0) {
                        $("#norbuyBillTotal_re").val(0);
                    }

                }
                continue;
            } else {
                //Calculate it again to make sure that there are no errors in calculations
                return_calcuproduct(numco);

                if ($('#product_re' + numco).val() != "" && Number($('#product' + numco).val()) != -1) {
                    // sum method
                    returned_thealltotal = Number(returned_thealltotal) + Number(document.getElementById("hidden_prototal_re" + numco).value);
                    //check round number property
                    if ($round_numbers == 0) //التقريب لأقرب عدد صحيح
                    {
                        returned_thealltotal = Math.round(returned_thealltotal);
                    } else //التقريب لأقرب رقم
                    {
                        //returned_thealltotal = Math.round(returned_thealltotal*10)/10;
                        //	alert(3);
                        returned_thealltotal = returned_thealltotal.toFixed($noOfDecimalPlaces);
                        //alert(4);
                    }
                    $("#buyBillTotal_re").html(returned_thealltotal);
                    $("#returnBuyBillTotal").val(returned_thealltotal);
                    if ($("#norbuyBillTotal_re").length > 0) {
                        $("#norbuyBillTotal_re").val(returned_thealltotal);
                    }
                }
            }
        }

        //total price
        thealltotal = buyed_thealltotal - returned_thealltotal;
        //## check for value added buy of prog setting // valueaddedbuy = 1 means product price has tax included ,so remove that tax from total price as it is calculated below
        var valueadded = Number($('#valueaddedbuy').val());
        var taxPer = Number($('#payedtax').val()) / 100;
        if (valueadded == 1 && taxPer > 0) {
            var taxPerPlusOne = (taxPer + 1).toFixed(2);
            var taxVal = (thealltotal * taxPer) / taxPerPlusOne;
            thealltotal = thealltotal - taxVal;
        }
        //######################################################################

        //check round number property
        if ($round_numbers == 0) //التقريب لأقرب عدد صحيح
        {
            thealltotal = Math.round(thealltotal);
        } else //التقريب لأقرب رقم
        {
            //thealltotal = Math.round(thealltotal*10)/10;
            //alert(5);
            thealltotal = thealltotal.toFixed($noOfDecimalPlaces);
            //	alert(6);

        }

        //### probuyDiscountPer
        var totalBuyDiscountVal = 0;
        $('.probuyDiscountPerClass').each(function () {
            var itr = $(this).attr('id').slice(17);
            var pronum = $('#pronum' + itr).val();
            var proprice = $('#proprice' + itr).val();
            var prodis = $('#prodis' + itr).val();
            var rowTot = pronum * proprice - prodis;
            var buyDiscountPer = Number($(this).val()) / 100;
            totalBuyDiscountVal += rowTot * buyDiscountPer;
        });
        if ($round_numbers == 0) //التقريب لأقرب عدد صحيح
            totalBuyDiscountVal = Math.round(totalBuyDiscountVal);
        else //التقريب لأقرب رقم
            totalBuyDiscountVal = totalBuyDiscountVal.toFixed($noOfDecimalPlaces);

        // thealltotal = thealltotal - totalBuyDiscountVal;
        $('#totalBuyDiscountVal').html(totalBuyDiscountVal);
        $('#totalBuyDiscountVal_hidden').val(totalBuyDiscountVal);
        //####################



        //insert the value in div
        $("#gentotal").html(thealltotal);
        document.getElementById("totalbeforediscount").value = thealltotal;

        if ($("#supplier").val() != '-1' && $("#supplier").val() != '-2' && $("#supplier").val() != '1')//if there is supplier rather than مباشر
        {
            if ($('#genpay').val() == "") {
                document.getElementById("genpay").value = 0;
            }

        } else {
            //alert('thealltotal'+thealltotal);
            if (thealltotal > 0) {
                //alert(555);
                // document.getElementById("genpay").value = thealltotal;
            } else {
                //alert(444);
                //document.getElementById("genpay").value = (thealltotal*-1);
            }
        }
    }


    /************************/
    // get the total quantity
    /************************/
    totalquantity = function ($ixx) {
        // variable that will carry total quantity
        var totalQty = "";

        //loop to sum the all prices
        for ($x = 1; $x <= $ixx; $x++) {
            var numco = $x;
            var inputname = "pronum" + numco;

            //to make sure that all inputs are created
            if ($("#" + inputname).length == 0) {
                continue;
            } else {
                if ($("#product" + $x).val() != '-1' && $("#product" + $x).val() != null && $("#product" + $x).val() != '') {//to not calculate the last row's quantity if its empty
                    // sum method
                    totalQty = Number(totalQty) + Number($("#" + inputname).val());
                }
            }
        }

        //			//insert the value in div
        $("#totalQty").html(totalQty);
    }


    /************************/
    // method that calculate discount
    /************************/
    thegeneraldiscount = function (useOld = 0) {
        //calculate the dicount
        var generalprice = Number($("#gentotal").html());
        var generaldiscount = Number(document.getElementById("gendis").value);

        if (useOld == 1) {
            generaldiscount = $('#oldGendis').val();
            $('#gendis').val(generaldiscount);
        }


        $round_numbers = $("#round_numbers").val();
        $noOfDecimalPlaces = $("#noOfDecimalPlaces").val();

        var valueaddeddiscount = $("#valueaddeddiscount").val();

        //check discount type
        var discountType = $("#discount_type").val();
        if ($("#discount_type").length < 1) {
            discountType = 0;
        }
        if (discountType == "0") //خصم مباشر
        {


            if (generaldiscount >= 0)//لا تسمح بالسالب في الخصم
            {

                if (Number($("#gen2total").html()) > 0) {
                    if (generaldiscount > generalprice) {//if قيمه الخصم > إجمالى الفاتوره

                        document.getElementById("gendis").value = generalprice;// قيمة الخصم = //إجمالى الفاتوره
                        var generaldiscount = document.getElementById("gendis").value;
                        var netprice = 0; // المبلغ بعد الخصم = 0
                    } else {//حساب الخصم
                        var netprice = Number(generalprice) - Number(generaldiscount);
                    }


                    //alert('netprice'+netprice);
                } else {
                    var netprice = Number(generalprice) - (-Number(generaldiscount));
                }
            } else { //حساب الخصم
                document.getElementById("gendis").value = 0;
                var netprice = Number(generalprice);
            }
        } else if (discountType == "1") // خصم بنسبة مئوية
        {
            if (generaldiscount > 100) {//حتى لا يتعدي 100% من إجمالي الفاتورة
                document.getElementById("gendis").value = 100;
                var generaldiscount = document.getElementById("gendis").value;
            }

            var resultdiscountbefore = generaldiscount / 100;
            var resultdiscount = resultdiscountbefore * generalprice;
            var netprice = generalprice - resultdiscount;

        }


        /***** calc discount ended *****/
        /***** calc addition start *****/
        var genaddition = Number(document.getElementById("genaddition").value);

        if (useOld == 1) {
            genaddition = $('#oldgenaddition').val();
            $('#genaddition').val(genaddition);
        }

        //check addition type
        var addition_type = $("#addition_type").val();
        if ($("#addition_type").length < 1) {
            addition_type = 0;
        }
        if (addition_type == "0") // مباشر
        {


            if (genaddition >= 0)//لا تسمح بالسالب في الاضافة
            {
                if (Number($("#gen2total").html()) > 0) {
                    if (genaddition > generalprice) {//if قيمه الاضافة > إجمالى الفاتوره

                        document.getElementById("genaddition").value = generalprice;// قيمة الاضافة = //إجمالى الفاتوره
                        var genaddition = document.getElementById("genaddition").value;
                        var netprice = 0; // المبلغ بعد الاضافة = 0
                    } else {//حساب الخصم
                        var netprice = Number(netprice) + Number(genaddition);
                    }


                    //alert('netprice'+netprice);
                } else {
                    var netprice = Number(netprice) - (-Number(generaldiscount));
                }
            } else { //حساب الخصم
                document.getElementById("genaddition").value = 0;
                var netprice = Number(generalprice);
            }
        } else if (addition_type == "1") // اضافة بنسبة مئوية
        {
            if (genaddition > 100) {//حتى لا يتعدي 100% من إجمالي الفاتورة
                document.getElementById("genaddition").value = 100;
                var genaddition = document.getElementById("genaddition").value;
            }

            var resultadditionbefore = genaddition / 100;
            var resultaddition = resultadditionbefore * generalprice;
            netprice = netprice + resultaddition;

        }

        /***** calc addition ended *****/

        if ($round_numbers == 0) //التقريب لأقرب عدد صحيح
        {
            netprice = Math.round(netprice);
        } else //التقريب لأقرب رقم
        {
            //netprice = Math.round(netprice*10)/10;
            //alert(7);
            netprice = netprice.toFixed($noOfDecimalPlaces);

            //alert(8);
        }


        var taxOfDiscountPercentage = Number($('#taxOfDiscountPercentage').val()) / 100;
        var taxOfDiscountVal = taxOfDiscountPercentage * netprice;
        $('#taxOfDiscountVal').val(taxOfDiscountVal.toFixed($noOfDecimalPlaces));
        $('#taxOfDiscountVal_h').val(taxOfDiscountVal.toFixed($noOfDecimalPlaces));


        if (Number($("#payedtax").val()) <= 100) {


            if (valueaddeddiscount == 1) {
                var payedtax = Number(((document.getElementById("payedtax").value) / 100) * generalprice);
            } else {
                var payedtax = Number(((document.getElementById("payedtax").value) / 100) * netprice);
            }

            $('#taxVal').val(payedtax.toFixed($noOfDecimalPlaces));
            var aftertax = Number(netprice) - taxOfDiscountVal + payedtax;//Number((payedtax * netprice));
            aftertax = aftertax.toFixed($noOfDecimalPlaces);
            $("#gen2total").html(aftertax); // المبلغ بعد الخصم
            document.getElementById("totalafterdiscount").value = aftertax;

            if ($("#supplier").val() == '-1' || ($("#supplier").val() == '1'))//if there is supplier rather than مباشر
            {

                //alert('in if')
                //alert('thealltotal'+thealltotal);
                if (netprice > 0) {
                    //document.getElementById("genpay").value = aftertax;
                } else {
                    //document.getElementById("genpay").value = (aftertax*-1);
                }
            }

        } else {

            document.getElementById("payedtax").value = 0;
            $("#gen2total").html(netprice - taxOfDiscountVal); // المبلغ بعد الخصم
            document.getElementById("totalafterdiscount").value = netprice - taxOfDiscountVal;

    }



    /***************************************************************************************************************/


    /***************************************************************************************************************/

    }



    /************************/
    // method that calculate discount if user changed discount type after entering discount value
    /************************/
    $("#discount_type ,#addition_type").on("change", function () {

        $("#gendis").trigger('keyup'); //trigger event
    });
    /***************************/






    /************************/
    // general pay , calaclution in key up
    /************************/
    $(document).on('keyup', "#genpay", function () {
        checkPayed();
        //get the general payed
        thegeneralpayed();
        checkthepayed();



        // calculate the rest of debt
        therestofdebt();
    });
    /************************/

    /************************/
    // general pay2 , calaclution in key up
    /************************/
    $(document).on('keyup', "#genpay2", function () {
        checkPayed();

        var value = $("#genpay").val();

        if (value != 0) {

            var result = $("#genpay2").val() - $("#genpay").val();

            $("#gen3total2").html(result);
        } else {
            $("#genpay2").val(0);
            $("#gen3total2").html(0);
        }
    });
    /************************/

    /**********************/
    // calculate the general payed
    /************************/
    thegeneralpayed = function () {
        var netprice = Number($("#gen2total").html());
        var generalpayed = Number(document.getElementById("genpay").value);
        //var discountValue = Number(document.getElementById("gen2total").html);
        if (netprice < 0) {
            var resultpayed = netprice + generalpayed;//netprice is a negative number
        } else {
            var resultpayed = netprice - generalpayed;
        }

        $round_numbers = $("#round_numbers").val();
        $noOfDecimalPlaces = $("#noOfDecimalPlaces").val();
        if ($round_numbers == 0) //التقريب لأقرب عدد صحيح
        {
            //alert('in if');
            resultpayed = Math.round(resultpayed);
        } else //التقريب لأقرب رقم
        {
            //alert('in else');
            resultpayed = Math.round(resultpayed * 100) / 100;
            /*	alert(9);
             resultpayed = resultpaye.toFixed($noOfDecimalPlaces)
             alert(10);*/

        }

        //alert(resultpayed);
        $("#gen3total").html(resultpayed);
    }

    /*$(document).on("keyup","#genpay",function(){
     checkthepayed();
     thegeneralpayed();
     therestofdebt();
     });*/
    /**********************/


    /************************/
    //calculate the rest of debt
    /************************/
    therestofdebt = function () {
        //var generalpayed = document.getElementById("genpay").value;
        var debt = document.getElementById("hidden_debt").value;
        var resultpayed = $("#gen3total").html();
        var therestdebt = Number(debt) + Number(resultpayed);

        $round_numbers = $("#round_numbers").val();
        $noOfDecimalPlaces = $("#noOfDecimalPlaces").val();
        if ($round_numbers == 0) //التقريب لأقرب عدد صحيح
        {
            therestdebt = Math.round(therestdebt);
        } else //التقريب لأقرب رقم
        {
            //therestdebt = Math.round(therestdebt*10)/10;
            //alert(11);
            therestdebt = therestdebt.toFixed($noOfDecimalPlaces)
            //alert(12);
        }

        $("#gen4total").html(therestdebt);

        document.getElementById("supplierdebtafter").value = therestdebt;
    }
    /************************/


    /************************/
    // calculate general discount
    /***********************/
    $(document).on('keyup', "#gendis ,#genaddition", function () {

        // get the itration from itration colum
        $remitr = document.getElementById("hidden_itr").value

        // get the total price of product
        totalprice($remitr);

        //get the general discount
        thegeneraldiscount();

        checkthepayed();
        //get the general payed
        thegeneralpayed();

        // calculate the rest of debt
        therestofdebt();

        checkthepayed();
    });
    /**********************/


    /**********************/
    // action of edit debt
    /************************/
    $("#editdebt").click(function () {
        //here the code
        var theselectedvalue = document.getElementById("proprice1").value;
        $("#debt").html('<img src="../views/default/images/loader/6.gif" alt="">');
        $('#debt').load('test.php?itrs=1&id=' + theselectedvalue + '', function () {

            $("#editdebt").css("display", "none");
        });
    });
    /************************/


    /**********************/
    // the main method to calucalte products price
    /***************************/
    calcuproduct = function (thecolnmux) {
        var discountrowtype = $("#discountrowtype").val();
        var showdiscountrow = $("#productDiscountSetting").val();
        var price = Number(document.getElementById("proprice" + thecolnmux).value);
        var amount = Number(document.getElementById("pronum" + thecolnmux).value);
        var productTotal = Number(document.getElementById("hidden_prototal" + thecolnmux).value);//إجمالي سعر المنتج

        var pricebefore = price * amount;

        //********if discount input is not shown
        /* if (productDiscountSetting == 1)
         {
         var discountbefore = 0;
         }
         // else
         {*/
        //القيمه المباشره
        var discountbefore = $("#prodis" + thecolnmux).val();
        var probuyDiscountPer = $("#probuyDiscountPer" + thecolnmux).val();
        var buyDiscountVal = 0;
        if (probuyDiscountPer > 0) {
            buyDiscountVal = (pricebefore - discountbefore) * probuyDiscountPer / 100;
        }
        //القيمه النسبيه
        var discounttype = $("#discounttype" + thecolnmux).val();
        $noOfDecimalPlaces = $("#noOfDecimalPlaces").val();
        //  }
        //****************

        //alert(555);
        //خصم مباشر
        if (discountrowtype == 0) {

            if (discountbefore > pricebefore) {
                $("#prodis" + thecolnmux).val(pricebefore);
                var discountbefore = Number($("#prodis" + thecolnmux).val());
            }

            var totalpricex = pricebefore - discountbefore - buyDiscountVal;
            //();
            $("#discounttype" + thecolnmux).val(((discountbefore / pricebefore) * 100).toFixed($noOfDecimalPlaces));
            // alert($("#discounttype" + thecolnmux).val());
        }
        //خصم نسبه
        else if (discountrowtype == 1 && showdiscountrow == 0) {
            if (discounttype > 100) {
                $("#discounttype" + thecolnmux).val(100);
                var discounttype = Number($("#discounttype" + thecolnmux).val());
            }
            //alert(((pricebefore/100)* discounttype));

            $("#prodis" + thecolnmux).val(((pricebefore / 100) * discounttype).toFixed($noOfDecimalPlaces));
            /*alert($("#prodis"+thecolnmux).val());
             alert($("#discounttype"+thecolnmux).val());*/
            var totalpricex = pricebefore - ((pricebefore / 100) * discounttype) - buyDiscountVal;
        } else {

            var totalpricex = pricebefore - buyDiscountVal;
        }


        //####################################
        //row tax "user input it as percentage" add its value to   totalpricex
        var rowtaxper = Number($("#rowtaxper" + thecolnmux).val());
        if (rowtaxper > 100) {
            rowtaxper = 100;
            $("#rowtaxper" + thecolnmux).val(rowtaxper);
        }
        $("#rowtaxval" + thecolnmux).val(((totalpricex / 100) * rowtaxper).toFixed($noOfDecimalPlaces));
        var totalpricex = totalpricex + ((totalpricex / 100) * rowtaxper);
        //####################################

        $round_numbers = $("#round_numbers").val();
        $noOfDecimalPlaces = $("#noOfDecimalPlaces").val();
        if ($round_numbers == 0) //التقريب لأقرب عدد صحيح
        {
            totalpricex = (totalpricex.toFixed($noOfDecimalPlaces));
            $("#hidden_prototal" + thecolnmux).val(totalpricex);
        } else //التقريب لأقرب رقم
        {

            /*  document.getElementById("hidden_prototal" + thecolnmux).value = Math.round(totalpricex * 100) / 100;
             totalpricex = Math.round(totalpricex * 10) / 10;*/

            $("#hidden_prototal" + thecolnmux).val(totalpricex);
            totalpricex = (totalpricex.toFixed($noOfDecimalPlaces));
        }
        //alert(totalpricex)

        $("#prototal" + thecolnmux).html(totalpricex);
        $("#hidden_prototal" + thecolnmux).val(totalpricex);


    }
    /***************************/


    /**********************/
    //use enter action do new row
    /*****************************/
    $(document).on('keypress', ".enteraction", function (e) {
        if (e.which == 13) {
            var id = $(this).attr('id');
            //add the new row with itration and with all propperties
            addrow($aw_i, $tabindexnum, id);

            //here to make focus in dropdown list
            // $('.chzn-single').focus(function (e) {
            //     e.preventDefault();
            // });
            // $('#product' + $aw_i + '_chzn a.chzn-single').focus();

            var settingQuantitiyFocus = document.getElementById("settingQuantitiyFocus").value;
            if (settingQuantitiyFocus == 0) {
                var currentId = $(this).attr('id');
                //get the num from this method
                var newword = currentId.slice(0, 4);
                if (newword == "pron") {
                    $inputItr = currentId.substr(6);
                    $inputItr++;
                    $("#product" + $inputItr).focus();
                    $("#product" + $inputItr).select2('open');
                }
                else {
                    $("#pronum" + $aw_i).focus();
                    $("#pronum" + $aw_i).select();
                }
            } else {
                if ($("#parcode" + $aw_i).is(":visible") === true) {
                    $("#parcode" + $aw_i).focus();
                    $("#parcode" + $aw_i).select();
                } else {
                    $("#product" + $aw_i).select2('focus');//.select2('open');
                }
            }
            // fill the iltration filed with common iltration
            document.getElementById("hidden_itr").value = $aw_i;

            // incrementaion of row number and tab index
            $aw_i++
            $tabindexnum++;

            //reload the dropdownlist and jquery files
            //	//$('select').chosen();
            //$.getScript('../views/default/js/head_scripts.js');

            //here to make focus in dropdown list
            //$('.chzn-drop .chzn-search input[type="text"]').focus();
            //$('.chzn-container').addClass('chzn-container-active');

            return false;
        }
    });
    /*****************************/


    /**********************/
    //to use enter and click to submit the form
    /*******************************/
    //    $("#billsure").keypress(function (e) {
    //        if (e.which == 13) {
    //            $("#supplier").change();
    //            $('#billform').submit();
    //        }
    //    });
    /******************************/


    /**********************/
    // using esc to delete row
    /*****************************/
    $(document).keypress(function (e) {

        var code = (e.keyCode ? e.keyCode : e.which);
        //to stop the submit of the form
        if (e.which == 13) {

            e.preventDefault();
        }
        if (code == 114) {
            //			print_Custom('mycustomheader');
            //			this.print(false);
            //			return false;
        }
        if (code == 27) {

            $trno = $("#containerpros tr").length - 1;
            if ($trno != 1) {
                // delete by partents
                $('#containerpros tr:last').remove();

                // get the itration from itration colum
                $remitr = document.getElementById("hidden_itr").value

                // get the total price of product
                totalprice($remitr);

                //get the general discount
                thegeneraldiscount();
                checkthepayed();
                //get the general payed
                thegeneralpayed();

                // calculate the rest of debt
                therestofdebt();

            }
            return false;
        }
    });
    /*******************************/

    /**********************/
    //
    /**********************/
    checkthepayed = function () {



        var netpriceto = Math.abs($("#gen2total").html()); //المبلغ بعد الخصم


        var generalpayedto = Math.abs(document.getElementById("genpay").value); //المدفوع
        var generaldiscountto = Math.abs(document.getElementById("gendis").value); // قيمة الخصم
        var genetalpriceto = Math.abs($("#gentotal").html()); //إجمالي الفاتورة


        if (generaldiscountto > 0) {
            //alert( 'in if ');
            if (Number(generalpayedto) > Number(netpriceto)) {
                document.getElementById("genpay").value = netpriceto;
            }
        } else {
            if (Number(generalpayedto) > Number(genetalpriceto) && generaldiscountto != 0) {
                document.getElementById("genpay").value = genetalpriceto;
            }

        }

        //        if (netpriceto == 0) {
        //            document.getElementById("genpay").value = 0;
        //            $("#genpay").attr("readonly", true);
        //            $("#gen3total").html(0);
        //
        //            //calculate total debt
        //            therestofdebt();
        //
        //        } else {
        //            if ($('#supplier').val() == 1) {
        //                $("#genpay").attr("readonly", true);
        //                $("#genpay").val(netpriceto);
        //            } else {
        //                $("#genpay").attr("readonly", false);
        //            }
        //
        //        }



    }
    /*******************************/


    /**********************/
    //action of store dropdownlist
    /**********************/
    /*	$("#storeId").chosen().change( function() {

     var theselectedvalue = $(this).val();
     $("#productdiv1").html('<img src="../views/default/images/loader/6.gif" alt="">');
     $('#productdiv1').load(''+storepagename+'?storeid='+theselectedvalue+'',function() {
     $("#addrowcreated").empty();
     $("#productdiv1 option").clone().appendTo("#addrowcreated");
     //$('select').chosen();
     });
     });
     */


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

    //to start the itration with default value // 1
    //document.getElementById("hidden_itr_re").value = 1;

    //the common itration and the start // 2

    $aw_i_re = Number($("#hidden_itr_re").val());// + 1;// 2;
    $aw_i_re++;

    //the tabindex to increment in dynmaic load
    $tabindexnum_re = 302;


    //add new row in bill
    //on click the add button
    /************************/
    $("#addpro_re").click(function () {

        // $aw_i_re = Number(document.getElementById("hidden_itr_re").value) + 1;
        return_addrow($aw_i_re, $tabindexnum_re);

        // fill the iltration filed with common iltration
        document.getElementById("hidden_itr_re").value = $aw_i_re;

        // incrementaion of row number and tab index
        $aw_i_re++
        $tabindexnum_re++;

        //reload the dropdownlist and jquery files
        ////$('select').chosen();
        return false;
    });
    /************************/


    //add new row in bill
    /**************************/
    return_addrow = function ($aw_i_re, $tabindexnum_re) {
        var productAndQuantityOnly = $('#productAndQuantityOnly').val();
        // var scunitname = $('#scunitname').val();
        var morestore = document.getElementById("morestore").value;
        var userstoreid = document.getElementById("userstoreid").value;
        var shownumber = document.getElementById("shownumber").value;
        var discountrowtype = document.getElementById("discountrowtype").value;
        var hideBillPricesClass = '';
        if (hideBillPrices == 1) {
            hideBillPricesClass = 'hidden';
        }

        $storeClass = '';
        if (morestore == 0) {
            $storeClass = '';
        } else {
            $storeClass = 'hidden';
        }

        $addedRow = '<tr>';

        //alert('aw_if'+$aw_if);
        if (shownumber == 0) {
            $addedRow += '<td>';
        } else {
            $addedRow += '<td  style="display:none !important">';
        }
        $addedRow += $aw_i_re + '</td>';

        //# check to hide
        var hidden_parcode = '';
        $('.check_tr_parcode').each(function (e) {
            var ths = $(this);
            if (ths.hasClass('hidden')) {
                hidden_parcode = 'hidden';
                return false;
            }
        });
        if (parcodeSetting == 0) {
            $addedRow += ' <td class="' + hidden_parcode + '">';
        } else {
            $addedRow += ' <td class="' + hidden_parcode + '">';
        }

        $addedRow += '<input name="parcode_re' + $aw_i_re + '" type="text" id="parcode_re' + $aw_i_re + '" class="form-control  txt-nonraduis" onkeypress="getreturnproductbyParcode(event,this.value, ' + $aw_i_re + ');" autocomplete="off" placeholder="الباركود" tabindex="' + $tabindexnum_re + '"/></td>';
        if (userstoreid == 0) {
            $addedRow += '<td class="' + $storeClass + '"> <div id="prstoridsiv' + $aw_i + '">' +
                    '<select class="clientstore wdt100" name="reprstorid' + $aw_i + '" id="reprstorid' + $aw_i + '">' +
                    $("#addstore").html() +
                    '</select></div>' +
                    '</td>';
        } else if (userstoreid != 0) {
            $addedRow += '<td class="' + $storeClass + '"> <div id="prstoridsiv' + $aw_i_re + '">'
                    + ' <input name="reprstorid' + $aw_i_re + '" id="reprstorid' + $aw_i_re + '" class="selectstore clientstore" type="hidden" value="' + $('#userstoreidForClient').val() + '" />'
                    + $("#addstore2").html()

                    + '  </div></td>';
        }
        if ($('#billtype2').length > 0 && $('#billtype2').val() == "1") {
            $addedRow += '<td>'
                    + '<div style="display: inline">'
                    + '<select class="select2 productCat_re productCat_re' + $aw_i_re + '" style="width:30%;display: inline" data-level="0" data-itr ="' + $aw_i_re + '" name="productCatId_re0_' + $aw_i_re + '" id="productCatId_re0_' + $aw_i_re + '" >'
                    + $('#cats').html()
                    + '</select>'
                    + ' </div>'
                    + '<input type="hidden" id="level_re_' + $aw_i_re + '" data-itr ="' + $aw_i_re + '" name="level_re_' + $aw_i_re + '" value="0">'
                    + '<div id="manyParents_re_' + $aw_i_re + '"  data-itr ="' + $aw_i_re + '" style="display: inline">'

                    + '</div>'
                    + '</td>';
        } else {
            $addedRow += '<td>'
                    + '<div id="productdiv_re' + $aw_i_re + '" class="aw_width aw_mt5">'
                    + '<input type="hidden" id="product_re' + $aw_i_re + '" name="product_re' + $aw_i_re + '" data-placeholder="اختر" class="select2product_re' + $aw_i_re + ' wdt100" tabindex="' + $tabindexnum_re + '"/>'
                    + '</div></td>';
        }


        if (noteSetting == 0) {
            $addedRow += ' <td>'
                    + '    <input name="note_re' + $aw_i_re + '" id="note_re' + $aw_i_re + '"   type="text"  class="form-control  txt-nonraduis" tabindex="' + $tabindexnum_re + '"/>'
                    + '    </td>';
        }

        //# check to hide
        var hidden_unit = '';
        $('.check_tr_unit').each(function (e) {
            var ths = $(this);
            if (ths.hasClass('hidden')) {
                hidden_unit = 'hidden';
                return false;
            }
        });

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

        if (unitSetting == 0) {
            $addedRow += '<td class="' + hidden_unit + '">';
        } else {
            $addedRow += '<td  class="hidden">';
        }

        //alert('1111aw_i_re'+$aw_i_re)
        $addedRow += '<div id="unitDiv_re' + $aw_i_re + '">'
                + '    <select name="unitId_re' + $aw_i_re + '" id="unitId_re' + $aw_i_re + '" onchange="return_getUnitPrice(' + $aw_i_re + ');"  data-placeholder="اختر" class="select2_customx  aw_m1 "  tabindex="' + $tabindexnum_re + '">'
                + '    </select>'
                + '    </div>'
                + '    </td>'
                + '<td class="' + hidden_quantity + '"><input name="pronum_re' + $aw_i_re + '" id="pronum_re' + $aw_i_re + '" value="1"   class="form-control return_getprototal  txt-nonraduis numberclic enteraction numberinput ' + numClass + '" type="text" tabindex="' + $tabindexnum_re + '" /></td>'
                ;



        if (scunitname == '0') {
            $addedRow += '<td style="display:none !important;"><input name="scunitname_re' + $aw_i_re + '" id="scunitname_re' + $aw_i_re + '" value="0" class="form-control  txt-nonraduis  numberclic   positiveNo" type="text" tabindex="' + $aw_i_re + '"  /></td>';

        } else {
            $addedRow += '<td ><input name="scunitname_re' + $aw_i_re + '" id="scunitname_re' + $aw_i_re + '" value="0" class="form-control  txt-nonraduis  numberclic   positiveNo" type="text" tabindex="' + $aw_i_re + '"  /></td>';

        }

        if (productAndQuantityOnly == 1) {
            $addedRow += '<td class="' + hideBillPricesClass + '" style="display:none !important;"><div id="propricechange_re' + $aw_i_re + '"><input name="proprice_re' + $aw_i_re + '" id="proprice_re' + $aw_i_re + '"  value="0" class="form-control txt-nonraduis return_getprototal numberclic enteraction numberinput positiveNo" type="text" tabindex="' + $tabindexnum_re + '" /></div></td>';
        } else {
            $addedRow += '<td class="' + hideBillPricesClass + '"><div id="propricechange_re' + $aw_i_re + '"><input name="proprice_re' + $aw_i_re + '" id="proprice_re' + $aw_i_re + '"  value="0" class="form-control txt-nonraduis return_getprototal numberclic enteraction numberinput positiveNo" type="text" tabindex="' + $tabindexnum_re + '" /></div></td>';
        }

        //# check to hide
        var hidden_discount = '';
        $('.check_tr_discount').each(function (e) {
            var ths = $(this);
            if (ths.hasClass('hidden')) {
                hidden_discount = 'hidden';
                return false;
            }
        });
        //        if (productAndQuantityOnly == 1)
        //        {
        //            $addedRow += '<td style="display:none !important;"><input name="prodis_re' + $aw_i_re + '" id="prodis_re' + $aw_i_re + '" value="0" class="form-control return_getprototal txt-nonraduis numberonly enteraction numberinput positiveNo" type="text" tabindex="' + $tabindexnum_re + '" /></td>';
        //        } else
        //        {
        //            if (productDiscountSetting == 0 && productAndQuantityOnly == 0)
        //            {
        //                $addedRow += '<td class="' + hidden_discount + '"> <input type="hidden" name="realprice_precentage_re' + $aw_i_re + '" value="0" id="realprice_precentage_re' + $aw_i_re + '" /><input name="prodis_re' + $aw_i_re + '" id="prodis_re' + $aw_i_re + '" value="0" class="form-control return_getprototal txt-nonraduis numberonly enteraction numberinput positiveNo" type="text" tabindex="' + $tabindexnum_re + '" /></td>';
        //            } else {//if (productDiscountSetting == 1)
        //                $addedRow += '<td style="display:none !important;"><input name="prodis_re' + $aw_i_re + '" id="prodis_re' + $aw_i_re + '" value="0" class="form-control return_getprototal txt-nonraduis numberonly enteraction numberinput positiveNo" type="text" tabindex="' + $tabindexnum_re + '" /></td>';
        //            }
        //        }
        $addedRow += '<td class="' + hidden_discount + ' ' + hideBillPricesClass + '"> <input name="prodis_re' + $aw_i_re + '" id="prodis_re' + $aw_i_re + '" value="0" class="form-control return_getprototal txt-nonraduis numberonly enteraction numberinput positiveNo"  tabindex="' + $tabindexnum_re + '" ';
        if (discountrowtype == 0) {
            $addedRow += ' type="text" ';
        } else {
            $addedRow += ' type="hidden" ';
        }
        $addedRow += '/> <input name="discounttype_re' + $aw_i_re + '" id="discounttype_re' + $aw_i_re + '"  value="0" class="form-control return_getprototal numberonly enteraction numberinput txt-nonraduis positivefloat" tabindex="' + $tabindexnum_re + '" ';
        if (discountrowtype == 1) {
            $addedRow += ' type="text" ';
        } else {
            $addedRow += ' type="hidden" ';
        }
        $addedRow += ' />';
        $addedRow += '     <input type="hidden" name="realprice_precentage_re' + $aw_i_re + '" value="0" id="realprice_precentage_re' + $aw_i_re + '" />' + //<input name="prodis_re' + $aw_i_re + '" id="prodis_re' + $aw_i_re + '" value="0" class="form-control return_getprototal txt-nonraduis numberonly enteraction numberinput positiveNo" type="text" tabindex="' + $tabindexnum_re + '" />\n\
                '</td>';

        //# check to hide
        var hidden_tax = '';
        $('.check_tr_tax:first').each(function (e) {
            var ths = $(this);
            if (ths.hasClass('hidden')) {
                hidden_tax = 'hidden';
                return false;
            }
        });

        $addedRow += '<td class=" ' + hidden_tax + ' ' + hideBillPricesClass + '">'
                + '           <input name="rowtaxval_re' + $aw_i_re + '" id="rowtaxval_re' + $aw_i_re + '" value="0" class="form-control return_getprototal numberonly enteraction numberinput txt-nonraduis positiveNo" placeholder="ضريبة" type="hidden"/>'
                + '           <input name="rowtaxper_re' + $aw_i_re + '" id="rowtaxper_re' + $aw_i_re + '"  value="0" class="form-control return_getprototal numberonly enteraction numberinput txt-nonraduis positiveNo" tabindex="' + $tabindexnum_re + '"  type="text" />'
                + '   </td>';

        if (productAndQuantityOnly == 1) {
            $addedRow += '<td class="aw_totalprice ' + hideBillPricesClass + '" style="display:none !important;">'
                    + '<input  name="hidden_prototal_re' + $aw_i_re + '" id="hidden_prototal_re' + $aw_i_re + '" class="returnEditTotal form-control txt-nonraduis enteraction numberinput positiveNo" value="0" type="text"/>'
                    + '</td>'
        } else {
            $addedRow += '<td class="aw_totalprice ' + hideBillPricesClass + '">'
                    + '<input  name="hidden_prototal_re' + $aw_i_re + '" id="hidden_prototal_re' + $aw_i_re + '" class="returnEditTotal form-control txt-nonraduis enteraction numberinput positiveNo" value="0" type="text"/>'
                    + '</td>'
        }

        $addedRow += '<td><button type="button" id="remove_re' + $aw_i_re + '" class="removeproduct_re close flt-none" aria-hidden="true" onclick="removeproduct_re(' + $aw_i_re + ');">&times;</button></td>'
                + '</tr>';


        //add the new row with itration and with all propperties
        $("#containerpros_re").append($addedRow);
        $('select').select2();

        $(".positiveNo").forcepositiveNum();
        $(".positivefloat").forcepositivefloat();

        // varaible to contains the common itration
        var n = $aw_i_re;
        var tbindexn_re = $tabindexnum_re;

        if (morestore == 0) {
            var lastValue = $('select[id^="reprstorid"]').filter(function () {
                var itr = $(this).attr('id').substr(10);
                return ($(this).val() !== null && itr != $aw_i_re && (Number($(this).val()) > 0 || $(this).val().indexOf("hasSizeColor") == 0));
            }).last().val();
            $("#reprstorid" + $aw_i_re).val(lastValue).trigger('change.select2');
        } else {
            if (Number($("#storeId").val()) > 0) {
                $("#reprstorid" + $aw_i_re).val($("#storeId").val()).trigger('change.select2');
            }
        }

        //assign select2 properties
        if ($('#billtype2').length > 0 && $('#billtype2').val() == "1") {
            $("#productCatId_re0_" + $aw_i_re).select2();
        } else {
            var morestore = document.getElementById("morestore").value;
            var restoreid = document.getElementById("storeId").value;
            if (morestore == 0) {
                restoreid = document.getElementById("reprstorid" + $aw_i_re).value;
            }

            $(".select2product_re" + $aw_i_re).select2({
                placeholder: "إسم المنتج",
                // minimumInputLength: 3,
                minimumInputLength: document.getElementById("searchvalue").value,
                multiple: false,
                quietMillis: 100,
                ajax: {
                    url: "buyBillControllerAjax.php?do=getProductsnotcollective",
                    dataType: 'json',
                    data: function (term, page) {
                        return {
                            term: term, //search term
                            page_limit: 10, // page size
                            storeid: restoreid, //document.getElementById("storeId").value,
                            searchWithCatAndProductNameOnly: document.getElementById("searchWithCatAndProductNameOnly").value,
                        };
                    },
                    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);
                },
                formatSelection: function (data) {
                    $choice = data.text;
                    if (data.productquantity)
                        $choice += '<span  style="text-align: left;float: left;  font-weight: bold;color: blue;">ك:' + Number(data.productquantity) + '</span>';
                    return $choice;
                },
            });

            $(".numberinput").forceNumeric();

            //action in change of created dropdown list  to load the price
            $("#product_re" + n).on("change", function (e) {
                checkForRepeatedProducts(n, 1);

                //here  will get the price for every product
                //the selected value in drop down list
                var theselectedvalue = e.val;
                var supplier = $('#supplier').val();

                var comingproserial = $(this).select2('data').comingproserial;
                var parcode = $('#parcode_re' + n).val();
                //using the load method to load the price
                // $("#propricechange_re"+n).html('<img src="../views/default/images/loader/6.gif" alt="">');
                //////////////////////////////////////////////////
                $.ajax({
                    url: 'buyBillControllerAjax.php?do=units&&return=1&itrs=' + n + '&tabindex=' + tbindexn_re + '&productid=' + theselectedvalue + '&supplier=' + supplier + '&billnameid=' + $('#billnameid').val() + '&comingproserial=' + comingproserial + '&parcode=' + parcode,
                    type: "get",
                    success: function (data) {
                        //    alert(data);
                        var response = $.parseJSON(data);
                        //populate unit
                        // alert(response.parcodeString);
                        $('#unitDiv_re' + n).html(response.unitString);
                        $('#parcode_re' + n).val(response.parcodeString);



                        $("#productUnitsDiv").empty();
                        $("#unitDiv_re" + n + " option").clone().appendTo("#productUnitsDiv");
                        $('.select2_unit_re' + n).select2();

                        //populate buy price
                        $('#propricechange_re' + n).html(response.priceString);
                        //change price of product from main curr to slected curr val
                        $('#proprice_re' + n).val(getValueInTermsOfSelectedCurrency($('#proprice_re' + n).val()));
                        $(".positiveNo").forcepositiveNum();

                        var productData = $("#product_re" + n).select2('data');
                        if (productData.isProUnitParcode == 1) {
                            $('#unitId_re' + n).val(productData.productunitid).change();
                            $('#proprice_re' + n).val(productData.proUnitBuyPrice);
                        }

                        //here all code that will happend with loading contants
                        //the number of rows of products
                        var return_itr = document.getElementById("hidden_itr_re").value

                        // get the total of product
                        return_calcuproduct(n);

                        $itr = document.getElementById("hidden_itr").value

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

                        return_totalquantity(n);

                        //get the general discount
                        thegeneraldiscount();

                        checkthepayed();

                        thegeneralpayed();

                        // calculate the rest of debt
                        return_therestofdebt();


                        // this function used for changing discount value based on bill setting تطبيق نسب الخصم فى فاتورة الشراء
                        change_discount_val_re(n, response.buypricereal_precentage);
                        $('#realprice_precentage_re' + n + '').val(response.buypricereal_precentage);

                        var quantityOrParcodeSetting = $("#quantityOrParcodeSetting").val();
                        if ((Number($aw_i) - Number(n)) == 1) {

                            if (quantityOrParcodeSetting == 0) {
                                $("#pronum_re" + n).focus();
                                $("#pronum_re" + n).select();
                            } else {
                                $("#parcode_re" + $aw_i).focus();
                                $("#parcode_re" + $aw_i).select();
                            }

                            // fill the iltration filed with common iltration

                        } else {
                            if (quantityOrParcodeSetting == 0) {
                                $("#pronum_re" + n).focus();
                                $("#pronum_re" + n).select();
                            } else {
                                $("#parcode_re" + $aw_i).focus();
                                $("#parcode_re" + $aw_i).select();
                            }
                        }

                        //alert(return_itr)
                        //add another row if there is no any new rows
                        $proId = document.getElementById("product_re" + return_itr).value;
                        //alert($proId)
                        if ($proId != null && $proId != '-1' && $proId != '') {
                            $("#addpro_re").trigger('click');
                        }

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




        if (quantityOrParcodeSetting == 0) {
            var nold = Number(n) - 1;
            $("#pronum_re" + nold).focus();
        } else {
            $("#parcode_re" + n).focus();
        }
    }

    var morestore = document.getElementById("morestore").value;
     if(morestore == 0 ){
        $('.select2product_re').select2({
            placeholder: "إسم المنتج",
            minimumInputLength: document.getElementById("searchvalue").value,
            // minimumInputLength: 3,
            multiple: false,
            quietMillis: 100,
            ajax: {
                url: "buyBillControllerAjax.php?do=getProductsnotcollective",
                dataType: 'json',
                data: function (term, page) {
                    return {
                        term: term, //search term
                        page_limit: 10, // page size
                        storeid: document.getElementById("reprstorid1").value, //document.getElementById("reprstorid1" /*+ $aw_i_re*/).value, //document.getElementById("storeId").value,
                        searchWithCatAndProductNameOnly: document.getElementById("searchWithCatAndProductNameOnly").value,
                    };
                },
                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);
            },
            formatSelection: function (data) {
                $choice = data.text;
                if (data.productquantity)
                    $choice += '<span  style="text-align: left;float: left;  font-weight: bold;color: blue;">ك:' + Number(data.productquantity) + '</span>';
                return $choice;
            },
    
        });
    }
    else{
        $('.select2product_re').select2({
            placeholder: "إسم المنتج",
            minimumInputLength: document.getElementById("searchvalue").value,
            // minimumInputLength: 3,
            multiple: false,
            quietMillis: 100,
            ajax: {
                url: "buyBillControllerAjax.php?do=getProductsnotcollective",
                dataType: 'json',
                data: function (term, page) {
                    return {
                        term: term, //search term
                        page_limit: 10, // page size
                        storeid: document.getElementById("storeId").value, //document.getElementById("reprstorid1" /*+ $aw_i_re*/).value, //document.getElementById("storeId").value,
                        searchWithCatAndProductNameOnly: document.getElementById("searchWithCatAndProductNameOnly").value,
                    };
                },
                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);
            },
            formatSelection: function (data) {
                $choice = data.text;
                if (data.productquantity)
                    $choice += '<span  style="text-align: left;float: left;  font-weight: bold;color: blue;">ك:' + Number(data.productquantity) + '</span>';
                return $choice;
            },
    
        });
    }


    /************************/
    // get product units
    /************************/
    var getUnits_re = function ($itrr) {

        $productid = $("#product_re" + $itrr).val();
        var supplier = $('#supplier').val();
        $('#unitDiv_re' + $itrr).load('buyBillControllerAjax.php?do=units&return=1&itrs=' + $itrr + '&productid=' + $productid + '&supplier=' + supplier + '&billnameid=' + $('#billnameid').val(), function () {
            //reload the dropdownlist and jquery files
            $('.select2_unit_re' + $itrr).select2();
        });
    }


    /************************/
    // calculating the product price
    // on keyup action
    /************************/
    $(document).on('keyup', ".return_getprototal", function (e) {

        //the id of selected row
        var currentId_re = $(this).attr('id');

        //get the num from this method
        var newword = currentId_re.slice(0, 4);

        //the number of ilteration
        var thecolnmu_re = 0;

        //see what chase
        switch (newword) {
            case "prop":
                thecolnmu_re = currentId_re.substr(12);
                break;
            case "pron":
                // if ($('#enablequantityfractions').val() != 1) {
                //     if ($(this).val() % 1 > 0)
                //         $(this).val(Math.round($(this).val())).keyup();
                // }
                thecolnmu_re = currentId_re.substr(9);
                var buypricereal_precentage = $('#realprice_precentage_re' + thecolnmu_re + '').val();
                // this function used for changing discount value based on bill setting تطبيق نسب الخصم فى فاتورة الشراء
                change_discount_val_re(thecolnmu_re, buypricereal_precentage);
                break;
            case "prod":
                thecolnmu_re = currentId_re.substr(9);
                break;
            case "disc":
                thecolnmu_re = currentId_re.substr(15);
                break;
            case "rowt":
                thecolnmu_re = currentId_re.substr(12);
                break;
            default:
                thecolnmu_re = 0;
        }

        // get the total of product
        return_calcuproduct(thecolnmu_re);

        //get buyed products iteration
        $itr = document.getElementById("hidden_itr").value

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

        //calculate total quantity
        return_totalquantity($aw_i_re);

        //get the general discount
        thegeneraldiscount();

        checkthepayed();

        //get the general payed
        thegeneralpayed();

        // calculate the rest of debt
        return_therestofdebt();

        if (e.keyCode == 65)//If CTRL+A has been pressed (SELECT ALL)
        {
            $('#pronum_re' + thecolnmu_re).select();
        }
    });


    /************************/
    $(document).on('change', ".returnEditTotal", function () {
        //the id of selected row
        var currentId = $(this).attr('id');

        //get the num from this method
        var thecolnmu = currentId.substr(18);
        var totalVal = $(this).val();
        var pronum = $("#pronum_re" + thecolnmu).val();

        var prodis = $("#prodis_re" + thecolnmu).val();
        if (prodis == 0) {
            $("#proprice_re" + thecolnmu).val(totalVal / pronum);
        } else {
            $("#proprice_re" + thecolnmu).val((+totalVal + +prodis) / pronum);
        }
        //get buyed products iteration
        $itr = document.getElementById("hidden_itr").value

        // get the total price of product
        totalprice($itr);
        //get the general discount
        thegeneraldiscount();
    });
    // here the frist action on frist dropdownlist
    /************************/
    $("#product_re1").on("change", function (e) {
        checkForRepeatedProducts(1, 1);

        //here get the price of product from ajax
        //the selected value of drop downlsit
        var theselectedvalue = e.val;
        var supplier = $('#supplier').val();

        var comingproserial = $(this).select2('data').comingproserial;
        var parcode = $('#parcode_re1').val();
        //using the load method to load the price
        //$("#propricechange_re1").html('<img src="../views/default/images/loader/6.gif" alt="">');
        //////////////////////////////////////////////////
        $.ajax({
            url: 'buyBillControllerAjax.php?do=units&&return=1&itrs=1&tabindex=301&productid=' + theselectedvalue + '&supplier=' + supplier + '&billnameid=' + $('#billnameid').val() + '&comingproserial=' + comingproserial + '&parcode=' + parcode,
            type: "get",
            success: function (data) {
                var response = $.parseJSON(data);
                //populate unit
                $('#unitDiv_re1').html(response.unitString);
                $("#productUnitsDiv").empty();
                $('#parcode_re1').val(response.parcodeString);
                $("#unitDiv_re1 option").clone().appendTo("#productUnitsDiv");
                $('.select2_unit_re1').select2();

                //populate buy price
                $('#propricechange_re1').html(response.priceString);
                //change price of product from main curr to slected curr val
                $('#proprice_re1').val(getValueInTermsOfSelectedCurrency($('#proprice_re1').val()));
                $(".positiveNo").forcepositiveNum();

                var productData = $("#product_re1").select2('data');
                if (productData.isProUnitParcode == 1) {
                    $('#unitId_re1').val(productData.productunitid).change();
                    $('#proprice_re1').val(productData.proUnitBuyPrice);
                }
                //here all code that will happend with loading contants
                //the number of rows of products
                var return_itr = document.getElementById("hidden_itr_re").value

                // get the total of product
                return_calcuproduct(1);

                $itr = document.getElementById("hidden_itr").value
                // get the total price of product

                totalprice($itr);

                return_totalquantity($aw_i_re);

                //get the general discount
                thegeneraldiscount();

                //get the general payed
                // return_thegeneralpayed();
                checkthepayed();
                thegeneralpayed();
                // calculate the rest of debt
                return_therestofdebt();


                var quantityOrParcodeSetting = $("#quantityOrParcodeSetting").val();

                if (quantityOrParcodeSetting == 0) {
                    $("#pronum_re1").focus();
                    $("#pronum_re1").select();
                } else {
                    $("#parcode_re1").focus();
                    $("#parcode_re1").select();
                }
                // this function used for changing discount value based on bill setting تطبيق نسب الخصم فى فاتورة الشراء

                change_discount_val_re(1, response.buypricereal_precentage);
                $('#realprice_precentage_re1').val(response.buypricereal_precentage);
                console.log('response.buypricereal_precentage = ' + response.buypricereal_precentage);
                //populate units
                //return_getUnitPrice(1);

                //add another row if there is no any new rows
                if ($("#product_re" + $return_itr).val() != null && $("#product_re" + $return_itr).val() != '-1' && $("#product_re" + $return_itr).val() != '') {
                    $("#addpro_re").trigger('click');
                    //return_addrow($aw_i_re, $tabindexnum_re);

                }

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

    });


    /**************************/
    // the delete action that delete row of products
    /************************/
    $(document).on('click', '.removeproduct_re', function () {
        //
        //
        //		// delete by partents
        //		$(this).parent().parent().remove();
        //
        //		// get the itration from itration colum
        //		$remitr = document.getElementById("hidden_itr_re").value
        //		$itr = document.getElementById("hidden_itr").value
        //		// get the total price of product
        //		totalprice($itr);
        //		//return_totalprice($remitr);
        //		//get the general discount
        //		thegeneraldiscount();
        //	checkthepayed();
        //		//get the general payed
        //		return_thegeneralpayed();
        //
        //		// calculate the rest of debt
        //		return_therestofdebt();
        //
        //		document.getElementById("hidden_itr_re").value = Number($remitr) - 1;
        //		//reduce number of products //عدد القطع
        //		$("#returnTotalQty").html( Number($remitr) - 1);
        //		return false;
    });


    /************************/
    //calculate the rest of debt
    /************************/
    return_therestofdebt = function () {
        var generalpayed = document.getElementById("genpay").value;//المدفوع
        var debt = document.getElementById("hidden_debt").value;//دين المورد
        //Number($("#debt").html()); //
        var resultpayed = $("#gen3total").html();//المتبقي

        var therestdebt = Number(debt) + Number(resultpayed);//إجمالي المديونية
        $round_numbers = $("#round_numbers").val();
        $noOfDecimalPlaces = $("#noOfDecimalPlaces").val();
        if ($round_numbers == 0) //التقريب لأقرب عدد صحيح
        {
            therestdebt = Math.round(therestdebt);
        } else //التقريب لأقرب رقم
        {
            //therestdebt = Math.round(therestdebt*10)/10;
            //alert(15);
            therestdebt = therestdebt.toFixed($noOfDecimalPlaces);
            //alert(16);
        }
        //alert("المدفوع: "+generalpayed+"   دين: "+debt +"  المتبقي: "+resultpayed);
        //alert("إجمالي المديونية: "+therestdebt);
        $("#gen4total").html(therestdebt);

        document.getElementById("supplierdebtafter").value = therestdebt;
    }
    /************************/


    /************************/
    // get the total quantity
    /************************/
    return_totalquantity = function ($ixx) {
        // variable that will carry total quantity
        var totalQty = "";

        //loop to sum the all prices
        for ($x = 1; $x <= $ixx; $x++) {
            var numco = $x;
            var inputname = "pronum_re" + numco;
            //to make sure that all inputs are created
            if ($("#" + inputname).length == 0) {
                continue;
            } else {
                if ($("#product_re" + $x).val() != '-1' && $("#product_re" + $x).val() != null && $("#product_re" + $x).val() != '') {//to not calculate the last row's quantity if its empty
                    // sum method
                    totalQty = Number(totalQty) + Number($("#" + inputname).val());
                }
            }
        }

        //		//insert the value in div
        $("#returnTotalQty").html(totalQty);
    }


    /**********************/
    // the main method to calucalte products price
    /***************************/
    return_calcuproduct = function (thecolnmux) {

        // alert(thecolnmux);
        var discountrowtype = $("#discountrowtype").val();
        var showdiscountrow = $("#productDiscountSetting").val();
        var return_itr = document.getElementById("hidden_itr_re").value;

        for ($i = 1; $i <= return_itr; $i++) {
            //alert();

            var inputname = "pronum_re" + $i;
            //to make sure that all inputs are created

            if ($("#proprice_re" + $i).length > 0) {
                var price = Number(document.getElementById("proprice_re" + $i).value);
                var amount = Number(document.getElementById("pronum_re" + $i).value);
                var productTotal = Number(document.getElementById("hidden_prototal_re" + $i).value);//إجمالي سعر المنتج

                var pricebefore = price * amount;

                //********if discount input is not shown
                /* if (productDiscountSetting == 1)
                 {
                 var discountbefore = 0;
                 }
                 else
                 {*/
                //القيمه المباشره
                var discountbefore = $("#prodis_re" + $i).val();
                //القيمه النسبيه
                var discounttype = $("#discounttype_re" + $i).val();
                // }
                //****************

                //alert("price: "+price+"  amount: "+amount+"  productTotal: "+productTotal+"   pricebefore: "+pricebefore);
                //خصم مباشر
                if (discountrowtype == 0) {
                    if (discountbefore > pricebefore) {
                        $("#prodis_re" + $i).val(pricebefore);
                        var discountbefore = Number($("#returnprodis" + $i).val());


                    }
                    var totalpricex = pricebefore - discountbefore;

                    //var xx=Math.round((discountbefore/pricebefore)*100)*100)/)100;
                    $("#discounttype_re" + $i).val(Math.round((((discountbefore / pricebefore) * 100)) * 100) / 100);

                    //alert('totalpricex'+totalpricex);
                }
                //خصم نسبة
                else if (Number(discountrowtype) == 1 && Number(showdiscountrow) == 0) {


                    if (discounttype > 100) {


                        $("#discounttype_re" + $i).val(100);
                        var discountbefore = Number($("#discounttype_re" + $i).val());
                    }
                    $("#prodis_re" + $i).val(Math.round((pricebefore / 100) * discounttype));
                    var totalpricex = pricebefore - ((pricebefore / 100) * discounttype);
                    //alert('totalpricex'+totalpricex);

                } else {
                    var totalpricex = pricebefore;
                }

                //####################################
                //row tax "user input it as percentage" add its value to   totalpricex
                var rowtaxper = Number($("#rowtaxper_re" + $i).val());
                if (rowtaxper > 100) {
                    rowtaxper = 100;
                    $("#rowtaxper_re" + $i).val(rowtaxper);
                }
                $("#rowtaxval_re" + $i).val(((totalpricex / 100) * rowtaxper).toFixed(3));
                var totalpricex = totalpricex + ((totalpricex / 100) * rowtaxper);
                //####################################


                $round_numbers = $("#round_numbers").val();
                if ($round_numbers == 0) //التقريب لأقرب عدد صحيح
                {
                    $("#hidden_prototal_re" + $i).val(Math.round(totalpricex * 100) / 100);
                    totalpricex = (Math.round(totalpricex * 100) / 100);
                } else //التقريب لأقرب رقم
                {
                    /*.getElementById("hidden_prototal_re"+$i).value = Math.round(totalpricex*10)/10;
                     totalpricex = Math.round(totalpricex*10)/10;
                     */
                    //alert(111111111111111111)
                    $("#hidden_prototal_re" + $i).val(Math.round(totalpricex * 100) / 100);
                    //alert(Math.round(totalpricex*10)/10);
                    //alert(totalpricex.toFixed(2));
                    totalpricex = (Math.round(totalpricex * 100) / 100);
                    //alert('cccccccccccccccccccccccccccccc')
                }

                $("#prototal_re" + $i).html(totalpricex);
            }
        }
    }
    /***************************/

    /**********************/
    //
    /**********************/
    return_thegeneralpayed = function () {

        var netpriceto = $("#gen2total").html();
        var generalpayedto = document.getElementById("genpay").value;
        var generaldiscountto = document.getElementById("gendis").value;
        var genetalpriceto = $("#gentotal").html();

        if (generaldiscountto > 0) {
            if (Number(generalpayedto) > Number(netpriceto)) {
                document.getElementById("genpay").value = netpriceto;
            }
        } else {
            if (Number(generalpayedto) > Number(genetalpriceto)) {
                //document.getElementById("genpay").value = genetalpriceto;
                document.getElementById("genpay").value = 0;
            }
        }
    }
    /*******************************/

    /*$("#supplier").select2().change(function () {
     //            var filedvalue = document.getElementById("supplier").value;
     //
     //			if(filedvalue == "-2")
     //			{
     //				$('#supplierModal').modal('show');
     //				//$("#modalLink").click(); //invoke click event of the link
     ////				$("#modalLink").cs
     //			}
     ////
     //			return false;

     });*/
    $("#currencyId").trigger('change', ['atPageLoading']);

    $('input[id^="pronum"]').keypress(function (e) {
        if (e.which === 13) {
            // Enter key was pressed
            var thisitr = $(this).attr('id').substr(6);
            if ($('#parcode' + thisitr).is(':visible')) {
                $('#parcode' + thisitr).focus();
            } else if ($('#product' + thisitr).is(':visible')) {
                $('#product' + thisitr).focus();
            }
        }
    });
    /////////////////////End////////////////
    if ($('#billidnor').length > 0 && $('#billidnor').val() > 0) {//edit
        setTimeout(function () {
            $('#pronum1').keyup();
        });

    }

});

//## currency main part ########################################################
var oldCFactor = Number($('#oldCFactor').val());//0 for add to stop changing prices at first //1 for edit to affect with bill cfactor only "like in buybillcurr"
var oldOtherCFactor = oldCFactor;//0 for add to stop changing prices at first //1 for edit to affect with bill cfactor only "like in buybillcurr"
$(function () {
    oldCFactor = Number($('#currencyId').select2("data").element[0].attributes['data-cfactor'].value);
    oldOtherCFactor = Number($('#currencyId').select2("data").element[0].attributes['data-othercfactor'].value);

    $('#saveid').on('change', function () {
        var curr = $('#saveid option:selected').data('curr');
        $('#currencyId').val(curr).change();
    })
});

//changing cFactor affect otherCFactor,otherCFactor changing affect cFactor
$('.calcOther').live('keyup', function () {
    var val = Number($(this).val());
    if (val == 0) {
        var otherVal = 0;
    } else {
        var otherVal = Number((1 / val).toFixed(6));
    }
    if ($(this).attr('id') == 'cFactor') {
        $('#otherCFactor').val(otherVal);
    } else {
        $('#cFactor').val(otherVal);
    }

});
//$('#currencyId, #cFactor, #otherCFactor').live('change', function (e, callingAtWhichEvent) {
$('#currencyId').live('change', function (e, callingAtWhichEvent) {
    $('#currencyText').text($('#currencyId').select2('data').text);
    if ($(this).attr('id') != "cFactor" && $(this).attr('id') != "otherCFactor" && ((callingAtWhichEvent != 'atPageLoading' && callingAtWhichEvent != 'submit') || $('#cFactor').val() == "" || $('#otherCFactor').val() == "")) {
        if (callingAtWhichEvent == 'atPageLoading' && $('#oldCFactorVal').length > 0) {//loading edit page
            cfactor = Number($('#oldCFactorVal').val());
            oldOtherCFactor = Number(1 / cfactor);
        } else {
            var cfactor = $('#currencyId').select2("data").element[0].attributes['data-cfactor'].value;
            var oldOtherCFactor = $('#currencyId').select2("data").element[0].attributes['data-othercfactor'].value;
        }
        $('#cFactor').val(cfactor);
        $('#otherCFactor').val(oldOtherCFactor);
    } else {
        var cfactor = $('#cFactor').val();
        var oldOtherCFactor = $('#otherCFactor').val();
    }


    //affect existing prices of products
    if (oldCFactor != 0 && callingAtWhichEvent != 'submit') {
        // dont recalc prices @submit to allow change in cfactor with value not default of currency to stay
        // it allow to have price in "bill currency like dollar" to remain unchanged , while price in "main currency like egyptian pound" change
        //this will affect 5 buy prices , supplierdebt in main currency
        $("input[id^='proprice']").each(function () {
            var itr = Number($(this).attr('id').slice(8));
            var BuyPrice = Number($(this).val());
            var buyPriceInNewCurr = (BuyPrice * cfactor) / oldCFactor;
            buyPriceInNewCurr = Number(buyPriceInNewCurr.toFixed(4));
            $(this).val(buyPriceInNewCurr).keyup();
        });
    }

    //finally
    oldCFactor = cfactor;
    //populateDebtAfter();
});
//##############################################################################
//change price of product from main curr to slected curr val
function getValueInTermsOfSelectedCurrency(val) {
    //    var cfactor = $('#currencyId').select2("data").element[0].attributes['data-cfactor'].value;
    var cfactor = $('#cFactor').val();
    val = Number((val * cfactor).toFixed(4));
    return val;
}


/**********************/

function submitSupplier() {
    /*	var sup_textDetails = document.getElementById("sup_textDetails").value;
     var sup_txtAddress = document.getElementById("sup_txtAddress").value;
     var sup_txtDebt = document.getElementById("sup_txtDebt").value;
     var sup_txtName = document.getElementById("sup_txtName").value;
     var sup_txtPhone = document.getElementById("sup_txtPhone").value;

     $("#preloader").html('<img src="{$path}/assets/pre-loader/Fading squares.gif">');
     $.post("cardAjaxController.php?do=add",{sup_txtAddress:sup_txtAddress, sup_textDetails:sup_textDetails, sup_txtDebt:sup_txtDebt, sup_txtName:sup_txtName,  sup_txtPhone:sup_txtPhone},function(result){
     $("#supplier").html(result);
     });
     */}


function return_getUnitPrice(n) {
    //here  will get the price for every product
    //the selected value in drop down list
    var productunitid = $("#unitId_re" + n).val();

    var productId = $("#product_re" + n).val();
    var tbindexn_re = document.getElementById("unitId_re" + n).getAttribute("tabindex");

    if (productunitid != '-1') {
        var supplier = $('#supplier').val();
        //using the load method to load the price
        $("#propricechange_re" + n).html('<img src="../views/default/images/loader/6.gif" alt="">');
        $('#propricechange_re' + n).load('buyBillControllerAjax.php?do=unitPrice&return=1&itrs=' + n + '&tabindex=' + tbindexn_re + '&productunitid=' + productunitid + '&productid=' + productId + '&supplier=' + supplier, function () {

            //here all code that will happend with loading contants
            //the number of rows of products
            var noitr = document.getElementById("hidden_itr_re").value;

            //to calculate the price and amount with discount
            return_calcuproduct(n);

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

            //get the general discount
            thegeneraldiscount();

            checkthepayed();

            thegeneralpayed();

            // calculate the rest of debt
            return_therestofdebt();
        });
    }
}


function supplierDebt(value) {
    var theselectedvalue = value;
    if (theselectedvalue != '-1' && theselectedvalue != '-2')//دين المورد
    {
        $("#debt").html('<img src="../views/default/images/loader/6.gif" alt="">');
        $('#debt').load('buyBillControllerAjax.php?supplierid=' + theselectedvalue + '', function () {

            document.getElementById("hidden_debt").value = $('#debt').html();
            $itrxxxx = $('#hidden_itr').val();
            totalprice($itrxxxx);

            //get the general discount
            thegeneraldiscount();
            checkthepayed();
            thegeneralpayed();
            therestofdebt();

        });
    } else if (theselectedvalue == '-2')//إضافة مورد جديد
    {
        showSupplierModalBox();
    }
    $('select').select2();
}

/**********************/

function getUnitPrice(n) {
    //here  will get the price for every product
    //the selected value in drop down list
    var productunitid = document.getElementById("unitId" + n).value;

    if (productunitid != '-1' && productunitid != null) {
        var productId = $("#product" + n).select2('val');
        var tbindexn = document.getElementById("unitId" + n).getAttribute("tabindex");

        //using the load method to load the price
        $("#propricechange" + n).html('<img src="../views/default/images/loader/6.gif" alt="">');
        var supplier = $('#supplier').val();
        $('#propricechange' + n).load('buyBillControllerAjax.php?do=unitPrice&itrs=' + n + '&tabindex=' + tbindexn + '&productunitid=' + productunitid + '&productid=' + productId + '&supplier=' + supplier, function () {

            var productpricetype = document.getElementById("productpricetype" + n).value;
            if (productpricetype == 1) {
                $('#proprice' + n).css("background-color", "#B7DFA4");
                $('#propricechange' + n).css("background-color", "#B7DFA4");
            } else {
                $('#proprice' + n).css("background-color", "#FFF");
                $('#propricechange' + n).css("background-color", "#FFF");
            }

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

            //to calculate the price and amount with discount
            calcuproduct(n);

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

            //get the general discount
            thegeneraldiscount();

            checkthepayed();

            //get the general payed
            thegeneralpayed();

            // calculate the rest of debt
            therestofdebt();
        });
    }
}


//// load product by parcode ///////
function getproductbyParcode(e, value, n) {
    var code = (e.keyCode ? e.keyCode : e.which);
    //to stop the submit of the form
    if (e.which == 13 && value != "") {
        //here get the price of product from ajax
        //the selected value of drop downlsit
        var usedParcode = Number($('#usedParcode').val());
        if (usedParcode == 1) {
            var theselectedvalue = value.replace("ه", "i");//this replacement is for parcode reader
            theselectedvalue = theselectedvalue.replace("÷", "i");//this replacement is for parcode reader
            theselectedvalue = theselectedvalue.replace("/", "i");//this replacement is for parcode reader
            theselectedvalue = theselectedvalue.replace("I", "i");//this replacement is for parcode reader
        } else {
            theselectedvalue = value;
        }

        var store = Number($('#storeId').val());
        //alert(theselectedvalue.charAt(0));
        $.ajax({
            url: 'buyBillControllerAjax.php?do=parcode&parcode=' + theselectedvalue + '&store=' + store,
            type: "get",
            success: function (data) {

                if (data != null && data != "") {
                    var response = $.parseJSON(data);
                    if (response.id != 0 && response.text != 0) {
                        //send value as a string of id and name to the initSelection function
                        //$("#product" + n).select2('val', ['' + response.id + ':' + response.text + ''], true);// true is a flag to allow triggering the change event which is false by default
                        $("#product" + n).select2('data', {
                            id: response.id, text: response.text
                            , isProUnitParcode: response.isProUnitParcode
                            , productunitid: response.productunitid
                            , unitid: response.unitid
                            , proUnitBuyPrice: response.proUnitBuyPrice
                            , userEnteredParcode: theselectedvalue
                            , comingproserial: 1
                            , productquantity: response.quantity
                        }, true);
                        //checkForRepeatedProducts(n, 0);
                    } else {
                        var parcodeValue = $("#parcode" + n).val();
                        $("#parcode" + n).val("");//empty parcode input
                        alert("رقم الباركود: " + parcodeValue + " غير موجود، تأكد من إدخال رقم صحيح");
                    }
                }
            },
            error: function () {
                alert("لقد حدث خطأ أثناء إجراء العملية");
            }
        });
    }
}


//// load return product by parcode ///////
function getreturnproductbyParcode(e, value, n) {
    var code = (e.keyCode ? e.keyCode : e.which);
    //to stop the submit of the form
    if (e.which == 13 && value != "") {
        //here get the price of product from ajax
        //the selected value of drop downlsit
        var usedParcode = Number($('#usedParcode').val());
        if (usedParcode == 1) {
            var theselectedvalue = value.replace("ه", "i");//this replacement is for parcode reader
            theselectedvalue = theselectedvalue.replace("÷", "i");//this replacement is for parcode reader
            theselectedvalue = theselectedvalue.replace("/", "i");//this replacement is for parcode reader
            theselectedvalue = theselectedvalue.replace("I", "i");//this replacement is for parcode reader
        } else {
            theselectedvalue = value;
        }

        var store = Number($('#storeId').val());
        //alert(theselectedvalue.charAt(0));
        $.ajax({
            url: 'buyBillControllerAjax.php?do=parcode&parcode=' + theselectedvalue + '&store=' + store,
            type: "get",
            success: function (data) {

                if (data != null && data != "") {
                    var response = $.parseJSON(data);
                    if (response.id != 0 && response.text != 0) {
                        //send value as a string of id and name to the initSelection function
                        //$("#product_re" + n).select2('val', ['' + response.id + ':' + response.text + ''], true);// true is a flag to allow triggering the change event which is false by default
                        $("#product_re" + n).select2('data', {
                            id: response.id, text: response.text
                            , isProUnitParcode: response.isProUnitParcode
                            , productunitid: response.productunitid
                            , unitid: response.unitid
                            , proUnitBuyPrice: response.proUnitBuyPrice
                            , userEnteredParcode: theselectedvalue
                            , comingproserial: 1
                            , productquantity: response.quantity
                        }, true);
                    } else {
                        var parcodeValue = $("#parcode_re" + n).val();
                        $("#parcode_re" + n).val("");//empty parcode input
                        alert("رقم الباركود: " + parcodeValue + " غير موجود، تأكد من إدخال رقم صحيح");
                    }
                }
            },
            error: function () {
                alert("لقد حدث خطأ أثناء إجراء العملية");
            }
        });
    }
}


//زر حفظ وجديد
function changeFormAction(billnameid) {
    $("#billform").attr("action", "buyBillController.php?do=add&return_url=1&billnameid=" + billnameid);
    return true;
}


function removeproduct($i) {
    $productValue = $("#product" + $i).val();

    //if($productValue != null && $productValue != '-1' && $productValue != '')
    {
        // delete by parents
        $("#remove" + $i).parent().parent().remove();
        // get the itration from itration colum
        $remitr = document.getElementById("hidden_itr").value

        // get the total price of product
        totalprice($remitr);

        //get the general discount
        thegeneraldiscount();

        checkthepayed();

        //get the general payed
        thegeneralpayed();

        //calculate the rest of debt
        therestofdebt();

        //document.getElementById("hidden_itr").value = Number($remitr) - 1;
        totalquantity(Number($remitr) - 1);
        //totalquantity(document.getElementById("hidden_itr").value);
    }
    //	else
    {
        //if the row is empty
        //		$aw_i--;
        //		$tabindexnum-- ;
    }
    return false;
}

function checkdisValue() {
    // get the itration from itration colum
    $remitr = document.getElementById("hidden_itr").value

    // get the total price of product
    totalprice($remitr);

    //get the general discount
    thegeneraldiscount();
    checkthepayed();


    thegeneralpayed();
    checkthepayed();



    // calculate the rest of debt
    therestofdebt();



}
function removeproduct_re($i) {
    $productValue = $("#product_re" + $i).val();

    //if($productValue != null && $productValue != '-1' && $productValue != '')
    {
        // delete by parents
        $("#remove_re" + $i).parent().parent().remove();
        // get the itration from itration colum
        $remitr = document.getElementById("hidden_itr_re").value
        $itr = document.getElementById("hidden_itr").value
        // get the total price of product

        totalprice($itr);

        //get the general discount
        thegeneraldiscount();

        checkthepayed();

        //get the general payed
        return_thegeneralpayed();

        // calculate the rest of debt
        return_therestofdebt();

        document.getElementById("hidden_itr_re").value = Number($remitr);// - 1;

        return_totalquantity(document.getElementById("hidden_itr_re").value);
    }
    //else
    {
        //if the row is empty
        //		$aw_i_re--;
        //		$tabindexnum_re-- ;
    }
    return false;
}

$("#saveBill, #saveAndNew").on('click', function (e) {
    if (!$('#billform').hasClass('processing')) {//to stop multi submitting
        $('#billform').addClass('processing');

        e.preventDefault();
        checkPayed();
        if (Number($("#supplier").val()) > 0) {
        } else {
            alert('عفوا اختر مورد');
            $('#billform').removeClass('processing');
            return false;
        }
        if (Number($("#storeId").val()) > 0) {
        } else {
            alert('عفوا اختر مخزن');
            $('#billform').removeClass('processing');
            return false;
        }

        var productBuy = 0;
        var productRet = 0;
        var productNeedCheckFlag = 0;
        if ($('#containerpros').is(":visible")) {
            var itr = $('#hidden_itr').val();
            for (i = 1; i <= itr; i++) {
                if ($('#product' + i).val()) {
                    if ($('#product' + i).val() != "") {
                        productBuy = 1;
                        //break;
                    }
                }
                if (($('#product' + i).val() == "" || $('#product' + i).val() == "-1" || !$('#unitId' + i).val()) && Number($('#proprice' + i).val()) > 0) {
                    productNeedCheckFlag = 1;
                    $('#product' + i).parents('tr').addClass('unsufficient');
                } else {
                    $('#product' + i).parents('tr').removeClass('unsufficient');
                }
            }
        }
        if ($('#containerpros_re').is(":visible")) {
            var itr = $('#hidden_itr_re').val();
            for (i = 1; i <= itr; i++) {
                if ($('#product_re' + i)) {
                    if ($('#product_re' + i).val() != "") {
                        productRet = 1;
                        //break;
                    }
                }
                if (($('#product_re' + i).val() == "" || $('#product_re' + i).val() == "-1" || !$('#unitId_re' + i).val()) && Number($('#proprice_re' + i).val()) > 0) {
                    productNeedCheckFlag = 1;
                    $('#product_re' + i).parents('tr').addClass('unsufficient');
                } else {
                    $('#product_re' + i).parents('tr').removeClass('unsufficient');
                }
            }

        }
        if ((productBuy == 1 || productRet == 1) && productNeedCheckFlag == 0) {
            $('#bn').removeAttr('disabled');
            if (check_negative_store_value() == 1) {
                //https://github.com/select2/docs/blob/master/pages/12.programmatic-control/04.events/docs.md
                //send data to trigger change of select2 to use it there
                $("#supplier").removeAttr('disabled');
                $("#supplier").trigger({
                    //type: 'select2:select',
                    type: 'change',
                    params: {
                        data: {
                            id: $('#supplier').select2('data').id,
                            text: $('#supplier').select2('data').text,
                            sullpierCurrencyid: $('#supplier').select2('data').sullpierCurrencyid
                        }
                    }
                });
                var billnameid = $('#billnameid').val();
                //it is save btn,but i need after save open new bill so use action of save and new
                if ($('#saveBtnGoesTo').val() == 1) {
                    //save and go to new bill after print
                    $("#billform").attr("action", "buyBillController.php?do=add&return_url=1&billnameid=" + billnameid);
                }
                $('#billform').submit();
            }
        } else {
            alert('عفوا لم تختر منتجات');
            $('#billform').removeClass('processing');
            return false;
        }
    }

});

/*--fatma--*/
$('.productCat').live('change', function () {
    var id = $(this).val();
    var level = Number($(this).attr('data-level'));
    level = level + 1;
    var itr = $(this).attr('data-itr');
    $('#level_' + itr).val(level);
    // alert('id = '+id);

    //--reset-----------------------------------------------------------------//
    //populate unit
    $("#unitDiv option").remove();

    //populate buy price
    $('#proprice' + itr).val(0);

    var noitr = document.getElementById("hidden_itr").value
    //to calculate the price and amount with discount
    calcuproduct(itr);

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

    totalquantity(itr);

    //get the general discount
    thegeneraldiscount();

    checkthepayed();

    //get the general payed
    thegeneralpayed();

    // calculate the rest of debt
    therestofdebt();

    //------------------------------------------------------------------------//
    $.post('salesreportajax.php?do=getsubcatbills', {id: id, level: level, itr: itr}, function (data) {
        $('.productCat' + itr).each(function () {
            var thisLevel = Number($(this).attr('data-level'));
            if (thisLevel >= level) {
                $(this).parent('div').remove();
            }
        });
        $('#productIdDiv_' + itr).remove();
        if (data != "-1") {
            $('#manyParents_' + itr).append(data);
        } else {
            var x = $aw_i;
            $aw_i++;
            var y = $tabindexnum;
            $tabindexnum++;
            $.post('salesreportajax.php?do=getproductsbills', {id: id, itr: itr, aw_i: x, tabindexnum: y}, function (data) {
                $('#manyParents_' + itr).append(data);

            });
        }
    });

});

if ($('#billtype2').length > 0 && $('#billtype2').val() == "1") {
    $(".productchange").live("change", function (e) {
        var rowitr = $(this).attr('data-itr');
        var aw_i_f = $('#aw_i_f_' + rowitr).val();
        var tabindexnum_f = $('#tabindexnum_f_' + rowitr).val();
        //here  will get the price for every product
        //the selected value in drop down list
        var theselectedvalue = e.val;
        //alert('222222222222222222222');
        var returnBillFlag = 0;

        var isoptic = $('#product' + rowitr + ' option:selected').attr('data-optic');
        var isColorSize = $(this).hasClass('colorsize');

        if (isoptic == 2) {
            if (isColorSize == false) {
                //$('#product' + rowitr).removeClass('productchange');
                $('#product' + rowitr).attr('name', 'preproduct' + rowitr);
                $('#product' + rowitr).attr('id', 'preproduct' + rowitr);
                //$('#s2id_product' + rowitr).removeClass('productchange');
                $('#s2id_product' + rowitr).attr('name', 's2id_preproduct' + rowitr);
                $('#s2id_product' + rowitr).attr('id', 's2id_preproduct' + rowitr);

                $('#sizeColorDiv_' + rowitr).remove();
                $.post('salesreportajax.php?do=getsizecolor', {id: theselectedvalue, itr: rowitr}, function (data) {
                    $('#productIdDiv_' + rowitr).append(data);
                });
            }
        } else {
            if ($('#preproduct' + rowitr).length > 0) {
                $('#sizeColorDiv_' + rowitr).remove();

                $('#preproduct' + rowitr).attr('name', 'product' + rowitr);
                $('#preproduct' + rowitr).attr('id', 'product' + rowitr);
                $('#s2id_preproduct' + rowitr).attr('name', 'product' + rowitr);
                $('#s2id_preproduct' + rowitr).attr('id', 'product' + rowitr);
                //$('#s2id_product' + rowitr).addClass('productchange');
                //$('#s2id_product' + rowitr).removeClass('productchange');
            }
        }


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



        if (isoptic == 2 && isColorSize == false) {
            //--reset-----------------------------------------------------------------//
            //populate unit
            $("#unitDiv option").remove();

            //populate buy price
            $('#proprice' + rowitr).val(0);

            var noitr = document.getElementById("hidden_itr").value
            //to calculate the price and amount with discount
            calcuproduct(rowitr);

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

            totalquantity(rowitr);

            //get the general discount
            thegeneraldiscount();

            checkthepayed();

            //get the general payed
            thegeneralpayed();

            // calculate the rest of debt
            therestofdebt();

            //------------------------------------------------------------------------//
        }

        if (theid == "product" + rowitr) {
            var supplier = $('#supplier').val();
            var comingproserial = 0;//$("#product" + rowitr).select2('data').comingproserial;
            var parcode = $('#parcode' + rowitr).val();
            //using the load method to load the price
            // $("#propricechange"+n).html('<img src="../views/default/images/loader/6.gif" alt="">');
            //////////////////////////////////////////////////
            $.ajax({
                url: 'buyBillControllerAjax.php?do=units&&return=' + returnBillFlag + '&itrs=' + rowitr + '&tabindex=' + tabindexnum_f + '&productid=' + theselectedvalue + '&supplier=' + supplier + '&billnameid=' + $('#billnameid').val() + '&comingproserial=' + comingproserial + '&parcode=' + parcode,
                type: "get",
                success: function (data) {
                    var response = $.parseJSON(data);
                    //populate unit
                    $('#unitDiv' + rowitr).html(response.unitString);
                    $("#productUnitsDiv").empty();
                    $("#unitDiv" + rowitr + " option").clone().appendTo("#productUnitsDiv");
                    $('.select2_unit' + rowitr).select2();

                    //populate buy price
                    $('#propricechange' + rowitr).html(response.priceString);
                    //change price of product from main curr to slected curr val
                    $('#proprice' + rowitr).val(getValueInTermsOfSelectedCurrency($('#proprice' + rowitr).val()));
                    $(".positiveNo").forcepositiveNum();

                    var productData = $("#product" + rowitr).select2('data');
                    if (productData.isProUnitParcode == 1) {
                        $('#unitId' + rowitr).val(productData.productunitid).change();
                        $('#proprice' + rowitr).val(productData.proUnitBuyPrice);
                    }
                    $('#probuyDiscountPer' + rowitr).val(productData.buydiscountpercent);
                    $('#probuyDiscountPer_span' + rowitr).html(productData.buydiscountpercent);

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

                    //to calculate the price and amount with discount
                    calcuproduct(rowitr);

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

                    totalquantity(rowitr);

                    //get the general discount
                    thegeneraldiscount();

                    checkthepayed();

                    //get the general payed
                    thegeneralpayed();

                    // calculate the rest of debt
                    therestofdebt();

                    var quantityOrParcodeSetting = $("#quantityOrParcodeSetting").val();
                    if ((Number(aw_i_f) - Number(rowitr)) == 1) {

                        if (quantityOrParcodeSetting == 0) {
                            $("#pronum" + rowitr).focus();
                            $("#pronum" + rowitr).select();
                        } else {
                            $("#parcode" + aw_i_f).focus();
                            $("#parcode" + aw_i_f).select();
                        }

                        // fill the iltration filed with common iltration

                    } else {
                        if (quantityOrParcodeSetting == 0) {
                            $("#pronum" + rowitr).focus();
                            $("#pronum" + rowitr).select();
                        } else {
                            $("#parcode" + aw_i_f).focus();
                            $("#parcode" + aw_i_f).select();
                        }
                    }

                    //add another row if there is no new rows
                    $proId = document.getElementById("product" + noitr).value;
                    if ($proId != null && $proId != '-1' && $proId != '') {
                        $("#addpro").trigger('click');
                    }
                },
                error: function () {
                    alert("لقد حدث خطأ أثناء إجراء العملية");
                }
            });
            //////////////////////////////////////////////////
        }
    });
    $(".productchange_re").live("change", function (e) {
        var rowitr = $(this).attr('data-itr');
        var aw_i_f = $('#aw_i_f_re_' + rowitr).val();
        var tabindexnum_f = $('#tabindexnum_f_re_' + rowitr).val();
        //here  will get the price for every product
        //the selected value in drop down list
        var theselectedvalue = e.val;
        //alert('333333333333333333333');
        var returnBillFlag = 1;

        var isoptic = $('#product_re' + rowitr + ' option:selected').attr('data-optic');
        var isColorSize = $(this).hasClass('colorsize');

        if (isoptic == 2) {
            if (isColorSize == false) {
                //$('#product' + rowitr).removeClass('productchange');
                $('#product_re' + rowitr).attr('name', 'preproduct_re' + rowitr);
                $('#product_re' + rowitr).attr('id', 'preproduct_re' + rowitr);
                //$('#s2id_product_re' + rowitr).removeClass('productchange_re');
                $('#s2id_product_re' + rowitr).attr('name', 's2id_preproduct_re' + rowitr);
                $('#s2id_product_re' + rowitr).attr('id', 's2id_preproduct_re' + rowitr);
                // ################
                $('#sizeColorDiv_re_' + rowitr).remove();
                $.post('salesreportajax.php?do=getsizecolor', {id: theselectedvalue, itr: rowitr, ret: 1}, function (data) {
                    $('#productIdDiv_re_' + rowitr).append(data);
                });
            }
        } else {
            if ($('#preproduct_re' + rowitr).length > 0) {
                $('#sizeColorDiv_re_' + rowitr).remove();

                $('#preproduct_re' + rowitr).attr('name', 'product_re' + rowitr);
                $('#preproduct_re' + rowitr).attr('id', 'product_re' + rowitr);
                $('#s2id_preproduct_re' + rowitr).attr('name', 'product_re' + rowitr);
                $('#s2id_preproduct_re' + rowitr).attr('id', 'product_re' + rowitr);
                //$('#s2id_product_re' + rowitr).addClass('productchange_re');
                //$('#s2id_product_re' + rowitr).removeClass('productchange_re');
            }
        }


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



        if (isoptic == 2 && isColorSize == false) {
            //--reset-----------------------------------------------------------------//
            //populate unit
            $("#unitDiv_re option").remove();

            //populate buy price
            $('#proprice_re' + rowitr).val(0);

            //the number of rows of products
            var return_itr = document.getElementById("hidden_itr_re").value

            // get the total of product
            return_calcuproduct(rowitr);

            $itr_up = document.getElementById("hidden_itr").value
            // get the total price of product
            totalprice($itr_up);

            return_totalquantity($aw_i_re);

            //get the general discount
            thegeneraldiscount();

            //get the general payed
            // return_thegeneralpayed();
            checkthepayed();
            thegeneralpayed();
            // calculate the rest of debt
            return_therestofdebt();

            //------------------------------------------------------------------------//
        }

        if (theid == "product_re" + rowitr) {
            var supplier = $('#supplier').val();
            var comingproserial = $("#product_re" + rowitr).select2('data').comingproserial;
            var parcode = $('#parcode_re' + rowitr).val();
            //using the load method to load the price
            // $("#propricechange"+n).html('<img src="../views/default/images/loader/6.gif" alt="">');
            //////////////////////////////////////////////////
            $.ajax({
                url: 'buyBillControllerAjax.php?do=units&&return=' + returnBillFlag + '&itrs=' + rowitr + '&tabindex=' + tabindexnum_f + '&productid=' + theselectedvalue + '&supplier=' + supplier + '&billnameid=' + $('#billnameid').val() + '&comingproserial=' + comingproserial + '&parcode=' + parcode,
                type: "get",
                success: function (data) {
                    var response = $.parseJSON(data);
                    //populate unit
                    $('#unitDiv_re' + rowitr).html(response.unitString);
                    $("#productUnitsDiv").empty();
                    $("#unitDiv_re" + rowitr + " option").clone().appendTo("#productUnitsDiv");
                    $('.select2_unit_re' + rowitr).select2();

                    //populate buy price
                    $('#propricechange_re' + rowitr).html(response.priceString);
                    //change price of product from main curr to slected curr val
                    $('#proprice_re' + rowitr).val(getValueInTermsOfSelectedCurrency($('#proprice_re' + rowitr).val()));
                    $(".positiveNo").forcepositiveNum();

                    var productData = $("#product_re" + rowitr).select2('data');
                    if (productData.isProUnitParcode == 1) {
                        $('#unitId_re' + rowitr).val(productData.productunitid).change();
                        $('#proprice_re' + rowitr).val(productData.proUnitBuyPrice);
                    }

                    //here all code that will happend with loading contants
                    //the number of rows of products
                    var return_itr = document.getElementById("hidden_itr_re").value

                    // get the total of product
                    return_calcuproduct(rowitr);

                    $itr_up = document.getElementById("hidden_itr").value
                    // get the total price of product
                    totalprice($itr_up);

                    return_totalquantity($aw_i_re);

                    //get the general discount
                    thegeneraldiscount();

                    //get the general payed
                    // return_thegeneralpayed();
                    checkthepayed();
                    thegeneralpayed();
                    // calculate the rest of debt
                    return_therestofdebt();


                    var quantityOrParcodeSetting = $("#quantityOrParcodeSetting").val();

                    if (quantityOrParcodeSetting == 0) {
                        $("#pronum_re" + rowitr).focus();
                        $("#pronum_re1" + rowitr).select();
                    } else {
                        $("#parcode_re" + rowitr).focus();
                        $("#parcode_re" + rowitr).select();
                    }



                    //populate units
                    //return_getUnitPrice(1);

                    //add another row if there is no any new rows
                    if ($("#product_re" + $return_itr).val() != null && $("#product_re" + $return_itr).val() != '-1' && $("#product_re" + $return_itr).val() != '') {
                        $("#addpro_re").trigger('click');
                    }

                },
                error: function () {
                    alert("لقد حدث خطأ أثناء إجراء العملية");
                }
            });
            //////////////////////////////////////////////////
        }
    });
}
//-- return part --//
$('.productCat_re').live('change', function () {
    var id = $(this).val();
    var level = Number($(this).attr('data-level'));
    level = level + 1;
    var itr = $(this).attr('data-itr');
    $('#level_' + itr).val(level);
    ///alert('44444444444444444444');

    //--reset-----------------------------------------------------------------//
    //populate unit
    $("#unitDiv_re option").remove();

    //populate buy price
    $('#proprice_re' + itr).val(0);

    //the number of rows of products
    var return_itr = document.getElementById("hidden_itr_re").value

    // get the total of product
    return_calcuproduct(itr);

    $itr_up = document.getElementById("hidden_itr").value
    // get the total price of product
    totalprice($itr_up);

    return_totalquantity($aw_i_re);

    //get the general discount
    thegeneraldiscount();

    //get the general payed
    // return_thegeneralpayed();
    checkthepayed();
    thegeneralpayed();
    // calculate the rest of debt
    return_therestofdebt();
    //------------------------------------------------------------------------//

    $.post('salesreportajax.php?do=getsubcatbills', {id: id, level: level, itr: itr, ret: 1}, function (data) {
        $('.productCat' + itr).each(function () {
            var thisLevel = Number($(this).attr('data-level'));
            if (thisLevel >= level) {
                $(this).parent('div').remove();
            }
        });
        $('#productIdDiv_re_' + itr).remove();
        if (data != "-1") {
            $('#manyParents_re_' + itr).append(data);
        } else {
            var x = $aw_i_re;
            var y = $tabindexnum_re;
            $tabindexnum_re++;
            $.post('salesreportajax.php?do=getproductsbills', {id: id, itr: itr, aw_i: x, tabindexnum: y, ret: 1}, function (data) {
                $('#manyParents_re_' + itr).append(data);

            });
        }
    });

});

$("#storeId").on('change',function () {
    var current_store = Number($(this).val()); //Number($('#storeid option:selected').val());
        // ## if ther is store selected choose it or choose first choice
    if (current_store > 0) {
        $(".clientstore").val(current_store).trigger('change.select2');
    } 
});
////////////////////////////////////
function check_negative_store_value() {


    //when preventing -ve store values
    //the buy product in retuurn buy bill with quantity make store quantity -ve is not allowed
    if ($('#storenegative').val() == 0) {
        var flag = 0;

        //1-prepare return products group by productid,storeid
        $('#check_store_msg').html("جارى التحقق من المخازن.");
        $('#check_store_div').show();
        var product_store_arr = {};//object not array
        //return itrations
        var itr = $('#hidden_itr_re').val();
        for (var i = 0; i <= itr; i++) {
            if ($('#product_re' + i).length > 0 && Number($('#product_re' + i).val()) > 0
                    && $('#storeId').length > 0 && Number($('#storeId').val()) > 0) {
                var product_id = Number($('#product_re' + i).val());
                var store_id = Number($('#storeId').val());
                var unit_id = Number($('#unitId_re' + i).val());
                var quantity = Number($('#pronum_re' + i).val());
                if (!product_store_arr[store_id + "_" + product_id]) {
                    var units_quantity_arr = {};
                    //product_store_arr[product_id + "_" + store_id] is equivalent to product_store_arr.product_id + "_" + store_id as we are dealing with object
                    product_store_arr[store_id + "_" + product_id] = units_quantity_arr;
                }
                var units_quantity_arr = product_store_arr[store_id + "_" + product_id];
                if (!units_quantity_arr[unit_id]) {
                    units_quantity_arr[unit_id] = 0;
                }
                units_quantity_arr[unit_id] += quantity;
            }
        }
        var product_store_arr = JSON.stringify(product_store_arr);
        //$('#product_store_arr').val(product_store_arr);
        $.ajax({
            type: "POST",
            url: 'sellbillAjaxController.php?do=checkNegative',
            data: {product_store_arr: product_store_arr},
            async: false,
            success: function (data) {
                if (data == 1) {
                    //all quantities required from store already exists
                    $('#check_store_div').hide();
                    flag = 1;
                } else {
                    var itr = $('#hidden_itr_re').val();
                    for (var i = 1; i <= itr; i++) {
                        if ($('#product_re' + i).length > 0) {
                            $('#product_re' + i).parents('tr').removeClass('unsufficient');
                        }
                    }

                    $('#check_store_msg').html("بعض الكميات المطلوبة غير موجودة بالمخازن.");
                    $('#check_store_div').show();
                    alert("بعض الكميات المطلوبة غير موجودة بالمخازن.");
                    data = JSON.parse(data);
                    console.log(data);
                    data.forEach(function (element) {
                        element = element.split(",");
                        var store_id = element[0];
                        var product_id = element[1];
                        //loop to mark un sufficient quantities
                        for (var i = 1; i <= itr; i++) {
                            if ($('#product_re' + i).length > 0) {
                                var product_id_row = $('#product_re' + i).val();
                                var store_id_row = Number($('#storeId').val());
                                if (product_id_row == product_id && store_id_row == store_id) {
                                    $('#product_re' + i).parents('tr').addClass('unsufficient');
                                }
                            }
                        }
                    });
                }

            }

        });
    } else {
        var flag = 1;
    }



    return flag;
}

function checkPayed() {
    //
    var genpay = Number($('#genpay').val());
    var payedSetting = Number($('#payedSetting').val());
    var totalafterdiscount = Math.abs(Number($('#totalafterdiscount').val()));
    if (payedSetting == 0) {
        //payed shouldnot be greater than total
        if (genpay > totalafterdiscount) {
            $('#genpay').val(totalafterdiscount);
        }
    }
}
//-- product with size 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});
                }
            });
        }
    }
}
$('#SizeColorQuantity').live('click', function () {
    getSizeColorArrays();
    //make sure ther are  sizes and colors selected
    if (sizes.length > 0 && colors.length > 0) {
        drawSizeColor();
        $('#quantity_div').show();
    } else {
        alert('عفوا تاكد من اختيار لون و مقاس على الاقل');
    }

});

$('.hasSizeAndColor').live('change', function () {
    var val = Number($(this).val());
    if (val == 0) {
        $('#sizeColorDiv').hide();
    } else {
        $('#sizeColorDiv').show();
    }
});
$('.removethis').live('click', function () {
    $(this).parent().parent().remove();
});


$(document).on('change keyup', '#vatIncludedTotalIfRow', function () {
    var vatIncludedTotalIfRow = $(this).val();
    var vatPerBill = $('#payedtax').val();
    if (vatIncludedTotalIfRow != "" && vatPerBill != "") {
        //get total
        var realVatPer = (vatPerBill / 100) + 1;
        var onePerVal = vatIncludedTotalIfRow / realVatPer;
        var vatVal = (vatPerBill * .01) * onePerVal;
        var total = vatIncludedTotalIfRow - vatVal;
        total = Number(total.toFixed(2));
        //get row number
        $n = getLastUsedRow();
        var quantity = 1;
        if ($n) {
            quantity = Number($('#pronum' + $n).val());
            var rowTotal = total / quantity;
            $('#proprice' + $n).val(rowTotal);
            $('#pronum' + $n).keyup();
        } else {
            $n = getLastUsedRetRow();
            quantity = Number($('#pronum_re' + $n).val());
            var rowTotal = total / quantity;
            $('#proprice_re' + $n).val(rowTotal);
            $('#pronum_re' + $n).keyup();
        }
    }
});
function getLastUsedRow() {
    var itr = $('#hidden_itr').val();
    var lastItr = 0;
    for (i = itr; i >= 1; i--) {
        if ($('#product' + i).val()) {
            //if ($('#product' + i).val() != "") {
            if (Number($('#product' + i).val()) > 0 || $('#product' + i).val().indexOf("hasSizeColor") == 0) {
                lastItr = i;
                return lastItr;
            }
        }
    }
}
function getLastUsedRetRow() {
    var itr = $('#hidden_itr_re').val();
    var lastItr = 0;
    for (i = itr; i >= 1; i--) {
        if ($('#product_re' + i).val()) {
            //if ($('#product' + i).val() != "") {
            if (Number($('#product_re' + i).val()) > 0 || $('#product_re' + i).val().indexOf("hasSizeColor") == 0) {
                lastItr = i;
                return lastItr;
            }
        }
    }
}

function checkForRepeatedProducts(rowitr, type) {
    //here use condition in bill setting
    var checkRedundantProducts = $('#checkRedundantProducts').val();
    if (checkRedundantProducts == 0) {
        if (type == 0) {//sell part
            if ($('#product' + rowitr).val()) {
                if (Number($('#product' + rowitr).val()) > 0 || $('#product' + rowitr).val().indexOf("hasSizeColor") == 0) {
                    //##
                    var itr = $('#hidden_itr').val();
                    for (i = 1; i <= itr; i++) {
                        if ($('#product' + i).length > 0 && i != rowitr && $('#product' + i).val() === $('#product' + rowitr).val()) {
                            $('#product' + i).parents('tr').addClass('unsufficient');
                            $('#product' + rowitr).parents('tr').addClass('unsufficient');
                            alert('هذا المنتج مكرر');
                            setTimeout(function () {
                                $('#product' + i).parents('tr').removeClass('unsufficient');
                                $('#product' + rowitr).parents('tr').removeClass('unsufficient');
                            }, 2000);
                            break;
                        }
                    }
                }
            }
        } else {//ret part
            if ($('#product_re' + rowitr).val()) {
                if (Number($('#product_re' + rowitr).val()) > 0 || $('#product_re' + rowitr).val().indexOf("hasSizeColor") == 0) {
                    //##
                    var itr = $('#hidden_itr_re').val();
                    for (i = 1; i <= itr; i++) {
                        if ($('#product_re' + i).length > 0 && i != rowitr && $('#product_re' + i).val() === $('#product_re' + rowitr).val()) {
                            $('#product_re' + i).parents('tr').addClass('unsufficient');
                            $('#product_re' + rowitr).parents('tr').addClass('unsufficient');
                            alert('هذا المنتج مكرر');
                            setTimeout(function () {
                                $('#product_re' + i).parents('tr').removeClass('unsufficient');
                                $('#product_re' + rowitr).parents('tr').removeClass('unsufficient');
                            }, 2000);
                            break;
                        }
                    }
                }
            }
        }
    }

}

$(document).on('click', ".addProSizeColor", function () {
    $('#proSizeColorModal').modal('show');
});