// // JavaScript Document
//here all method and function that control bill
var supplierpagename = 'sellbillAjaxController.php';
var storepagename = 'sellbillAjaxController.php';
var productpricepagename = 'sellbillAjaxController.php';
var billtype = 0;
var calcuproduct;
var totalprice;
var selltotalprice;
var thegeneraldiscount;
var checkthepayed;
var thegeneralpayed;
var therestofdebt;
var addrow;
var formatResult;
var sprydate;
var spryclient;
var sprytempname;
var userstoreidForUser;
var scunitname = $('#scunitnamevalue').val();

//#for siam make sure that rows have 2 decimals while applying round setting on gentotal of bill
var noOfDecimalPlacesForRows = 2;
var round_numbersForRows = 1;

//the common itration and the start // 2
$aw_i = document.getElementById("hidden_itr").value;
$aw_i++;
//the tabindex to increment in dynmaic load
$tabindexnum = 15;
var allDiscounts = JSON.parse($('#allDiscounts').val());
var stopDiscountOfTotalControl = Number($('#stopDiscountOfTotalControl').val());
var discountOfTotalControlEditable = Number($('#discountOfTotalControlEditable').val());
var discountOfTotalControlMTGDA = Number($('#discountOfTotalControlMTGDA').val()); //MTGDA is MTGDA more than group discount Allowed
var supplierWithAddOption = (Number($('#supplierWithAddOption').val()) == 1) ? 0 : 1;
var withNakdi = (Number($('#withNakdi').val()) == 1) ? 0 : 1;
var manyParcodesFlag = Number($('#manyParcodesFlag').val());
var addServiceToBill = Number($('#addServiceToBill').val());
var defaultUnitPriceAtBill = Number($('#defaultUnitPriceAtBill').val());
$noOfDecimalPlacesBillTotal = ($("#noOfDecimalPlacesBillTotal").val() > 0) ? $("#noOfDecimalPlacesBillTotal").val() : $("#noOfDecimalPlaces").val();
var clientType = Number($('#clientType').val());
if ($("[name='oldid']").length > 0) {//if in edit
    clientType = 0;// @ edit stop this setting , request by eng.sherif
}
var firstLoadingForClientChange = 1;
var autoDelBillRowFunc;
var autoDelBillRowRetFunc;
var activateAutoSave = Number($('#activateAutoSave').val());
var allowSupplierChange = 1; //1 do supplier changes, 0 dont do change events
var noORowsToUpdate, itr_finished, itr_ret_finished;
var pageLoadFlagForStore = 1;
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;
});
shortcut.add("f1", function () {
    var itr = $('#hidden_itr').val();
    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) {
                $('#pronum' + i).focus();
                break;
            }
        }
    }
    return false;
});
function newOptionAtInputTooShort() {
    var suppdata = $('#supplier').select2('data');
    $('#supplier').select2('data', { id: -2, text: 'اضافة عميل جديد' }).change();
    $('#supplieridBeforeChange').val(suppdata.id);
    $('#suppliernameBeforeChange').val(suppdata.text);
}
function getNoOfUsingthegeneraldiscountFuncTillFinishLoadingAtEdit() {
    //##to fix clientType == 1     makes payment = total even if payment = 0 in case of billsetting makes client nakdi "clientType setting"
    let temp = 0;
    if ($("[name='oldid']").length > 0) {//if in edit
        var myolditrreturn = document.getElementById("returnhidden_itr").value;
        if (myolditrreturn > 0) {
            //1 for each retproduct
            //+1 for using customeditsellbill "the ret part"
            temp = temp + $("input[id^='returnproprice']").length + 1;
        }

        var myolditr = document.getElementById("hidden_itr").value;
        if (myolditr > 0) {
            //1 for each product
            //+1 for using customeditsellbill "the sell part"
            temp = temp + $("input[id^='proprice']").length + 1;
        }

        temp = temp + 2;//s getclientdebtSuccess func is defined twice
    } else {
        temp = -10;//add
    }
    return temp;
}
var TillFinishLoadingCountNeeded = getNoOfUsingthegeneraldiscountFuncTillFinishLoadingAtEdit();
var generaldiscountUsesCountFlag = 0;
jQuery.fn.forcepositiveNum = function () {

    return this.each(function () {
        $(this).keydown(function (e) {
            var key = e.which || e.keyCode;
            //alert(key);
            if (!e.shiftKey && !e.altKey && !e.ctrlKey &&
                // numbersا
                key >= 48 && key <= 57 ||
                // Numeric keypad
                key >= 96 && key <= 105 ||
                // comma, period and minus, . on keypad
                //key == 190 || key == 188 || key == 109 || key == 110 ||
                // Backspace and Tab and Enter
                key == 8 || key == 9 || key == 13 ||
                // Home and End
                key == 35 || key == 36 ||
                // left and right arrows
                key == 37 || key == 39 ||
                // Del and Ins
                key == 46 || key == 45)
                return true;
            return false;
        });
    });
}

jQuery(document).ready(function () {


    $("#typeclient").select2({
        placeholder: "اختر  نوع العميل",
        multiple: false,
        quietMillis: 100,
        ajax: {
            url: "clientControllerAjax.php?do=typeclient",
            type: "post",
            dataType: 'json',
            data: function (term, page) {
                return {
                    searchTerm: term,
                    clientid: $('#supplier').val(),
                };
            },
            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);
        }
    });


    var priceupdate = document.getElementById("priceupdate").value;
    if (priceupdate == 0) {
        //alert(0);
        $("input[id^='proprice']").prop('readonly', true);
        $('.editTotal').prop('readonly', true);
    } else {
        //alert(1);
        $("input[id^='proprice']").prop('readonly', false);
        $('.editTotal').prop('readonly', false);
    }

    $("span.discountSpan").live('click', function () {
        //check if sellprice less than buyprice
        var itr = Number($(this).data('itr'));
        if ($('#prodis' + itr).is(':visible')) {//means discount is cash , changing to percentage
            $('#prodis' + itr).addClass('hidden');
            $('#discounttype' + itr).removeClass('hidden');
            $(this).html('%');
        } else if ($('#discounttype' + itr).is(':visible')) {//means discount is percentage , changing to cash
            $('#discounttype' + itr).addClass('hidden');
            $('#prodis' + itr).removeClass('hidden');
            $(this).html('C');
        }
    });
    $("span.retdiscountSpan").live('click', function () {
        //check if sellprice less than buyprice
        var itr = Number($(this).data('itr'));
        if ($('#returnprodis' + itr).is(':visible')) {//means discount is cash , changing to percentage
            $('#returnprodis' + itr).addClass('hidden');
            $('#returndiscounttype' + itr).removeClass('hidden');
            $(this).html('%');
        } else if ($('#returndiscounttype' + itr).is(':visible')) {//means discount is percentage , changing to cash
            $('#returndiscounttype' + itr).addClass('hidden');
            $('#returnprodis' + itr).removeClass('hidden');
            $(this).html('C');
        }
    });
    $("span.prosellDiscountPerTypeSpan").live('click', function () {
        //check if sellprice less than buyprice
        var itr = Number($(this).data('itr'));
        if (Number($('#prosellDiscountPerType' + itr).val()) === 0) {//means add to price "ض", change to "خ"
            $('#prosellDiscountPerType' + itr).val(1);
            $(this).html('خ');
        } else if (Number($('#prosellDiscountPerType' + itr).val()) === 1) {//means discount "خ" , changing to "ض"
            $('#prosellDiscountPerType' + itr).val(0);
            $(this).html('ض');
        }
        $('#prosellDiscountPer' + itr).keyup();
    });
    $("input[id^='proprice']").live('change', function () {
        var compareToBuyPriceAlert = Number($('#compareToBuyPriceAlert').val());
        if (compareToBuyPriceAlert > 0) {
            //check if sellprice less than buyprice
            var rowPrice = Number($(this).val());
            var itr = $(this).attr('id').slice(8);
            var pNum = Number($('#productunit' + itr + ' :selected').data('pu-num'));
            if (defaultUnitPriceAtBill == 0) {
                var lbwdPriceUnit = Number($('#productunit' + itr + ' :selected').data('lbwd-price'));
                var lowestPrice = pNum * lbwdPriceUnit;
            } else {
                var lowestPrice = Number($('#productunit' + itr + ' :selected').data('unit-price'));
            }

            lowestPrice = getValueInTermsOfSelectedCurrency(lowestPrice);
            if (rowPrice < lowestPrice) {
                if ($('#hideBuyPrice').val() == 1)
                    alert('انتبه سعر البيع الحالى اقل من سعر الشراء');
                else
                    alert('انتبه سعر البيع الحالى اقل من سعر الشراء وهو ' + lowestPrice);
            }
        }
    });
    //########################################
    $("input[id^='prodis']").live('change', function () {//&&&returnprodis//
        var itr = $(this).attr('id').slice(6);
        var rowDiscount = Number($('#discounttype' + itr).val());
        var weightedDiscount = $('#product' + itr).select2('data').weightedDiscount;
        if (rowDiscount < weightedDiscount) {
            alert('انتبه الخصم الحالى اقل من الخصم المرجح وهو ' + weightedDiscount + '%');
        }
    });
    $("input[id^='discounttype']").live('change', function () {//&&&returnprodis//discounttype1
        var itr = $(this).attr('id').slice(12);
        var rowDiscount = Number($(this).val());
        var weightedDiscount = $('#product' + itr).select2('data').weightedDiscount;
        if (rowDiscount < weightedDiscount) {
            alert('انتبه الخصم الحالى اقل من الخصم المرجح وهو ' + weightedDiscount + '%');
        }
    });
    //########################################
    $(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);
        //check if sellprice less than buyprice
        $("#proprice" + thecolnmu).change();
    });
    /*function matcher(term, text, opt) {
     //var label = $(opt).val();//.attr('id');
     var mobile = String($(opt).data('mobile')); //data of option to search into it too
     var phone = String($(opt).data('phone')); //data of option to search into it too
     var code = String($(opt).data('clientcode')); //data of option to search into it too
     var id = String($(opt).data('id')); //data of option to search into it too

     term = term.toUpperCase(); //term to search
     text = text.toUpperCase(); //text of option

     if (text.indexOf(term) > -1
     || (mobile !== undefined && mobile.toUpperCase().indexOf(term) > -1)
     || (phone !== undefined && phone.toUpperCase().indexOf(term) > -1)
     || (code !== undefined && code.toUpperCase().indexOf(term) > -1)
     || (id !== undefined && id.toUpperCase().indexOf(term) > -1)) {
     return true;
     }

     return false;
     }
     $('.select2Supp').select2({
     matcher: matcher
     });
     $("#tempclientName").val($("#supplier option[value='" + $("#supplier").val() + "']").text());*/
    $(".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: "clientControllerAjax.php?do=select2ClientsAjax",
            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("select2-selecting", function (e) {
        // the class to make diffrence of change from select2 itself "choose another option" ,it wont exist for triggering change
        $('#supplier').addClass('selectingClass');
    })
    //this is needed for ajax =>to obtain id from it  and use in ajax
    $('#supplier').select2('data', { id: $('#oldsupplierid').val(), text: $('#oldsuppliername').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() });
        if (manyParcodesFlag != 1 && $("[name='oldid']").length < 1) {
            let oldTmpName = $('#supplier').select2('data').text;
            let tmpName = oldTmpName.split('-')[1]
            if (!tmpName)
                tmpName = oldTmpName;
            $("#tempclientName").val(tmpName).change();
        }
    }, 0)

    if (Number($('#clientidFromGET').val())) {
        $('#supplier').select2("enable", false);
    }

    $(".select2sellToSupplier").select2({
        placeholder: "المورد",
        minimumInputLength: document.getElementById("clientsearchvalue").value,
        //inimumInputLength: 0,
        multiple: false,
        quietMillis: 100,
        ajax: {
            url: "supplierAjaxController.php?do=select2supplier",
            dataType: 'json',
            data: function (term, page) {
                return {
                    term: term, //search term
                    page_limit: 7, // page size
                    withAddOption: 0,
                    withNakdi: 0,
                    //jsonRowRet: 1,
                };
            },
            results: function (data) {
                return { results: data };
            }
        },
        formatResult: function (data) {
            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
    });
    $('#sellToSupplier').select2('data', { id: $('#oldsellToSupplierid').val(), text: $('#oldsellToSuppliername').val() });
    /* no need for it it is comming with supplier trigger change
     //    $.ajax({
     //        type: 'GET',
     //        url: 'sellbillAjaxController.php?do=clientstore&id=' + $("#supplier").val(),
     //        success: function (data) {
     //            //alert(data)
     //            var current_store = Number($('#storeid option:selected').val());
     //
     //            data = data.split(',,,,,');
     //            $(".clientstore").not('[id^="s2id_"]').find('option').remove().end().append(data[0]);
     //            // ## now we are in document ready if ther is store selected choose it or choose first choice
     //            if (current_store > 0) {
     //                $(".clientstore").val(current_store).trigger('change');
     //            } else {
     //                $(".clientstore").val($(".clientstore option:first").val()).trigger('change');
     //            }
     //
     //            $('.clientstoretxt').html(data[1]);
     //            $('#userstoreidForClient').val(data[2]);
     //        }
     //    });
     */
    $(".positiveNo").forcepositiveNum();
    $("#parcode1").focus();
    $(document).live('keypress', function (e) {
        var elementId = e.srcElement.id;
        //to stop the submit of the form
        if (elementId == "manyParcodes") {
            return true;
        }

        $firstitration = $aw_i - 1;
        $seconditration = $aw_i - 2;
        var code = (e.keyCode);
        //to stop the submit of the form

        //        if (code == 9)//tab ##this code was preventing tab in firefox #fixed
        //        {
        //            // alert($aw_i);
        //            if ($("#parcode" + $firstitration).is(":focus")) {
        //
        //                e.preventDefault();
        //            }
        //            if ($("#pronum" + $seconditration).is(":focus")) {
        //                e.preventDefault();
        //                $("#parcode" + $firstitration).focus();
        //            }
        //        }
        if (code == 13) {

            if ($("#pronum" + $seconditration).is(":focus")) {
                e.preventDefault();
                $("#gendis").focus();
            }

        }

        //        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");
            //            if (!$('#sellbillForm').hasClass('processing')) {//to stop multi submitting
            //                $('#sellbillForm').addClass('processing');
            //                $("#supplier").change();
            //                $('#sellbillForm').submit();
            //            }
            //            $("#saveBill").click();
            //            return false;
        }
    });
    var settingdate = document.getElementById("settingdate").value;
    var settingclient = document.getElementById("settingclient").value;
    if (settingclient == 0) {
        // spryclient = new Spry.Widget.ValidationSelect("spryclient", {isRequired: false, invalidValue: "-2"});

        // sprytempname = new Spry.Widget.ValidationTextField("sprytempname");

    } else {
        //spryclient.reset();
        //spryclient.destroy();
    }


    if (settingdate == 0) {
        sprydate = new Spry.Widget.ValidationTextField("sprydate");
    } else {
        //sprydate.reset();
        //sprydate.destroy();
    }



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



    //add new row in bill
    //on click the add button
    /************************/
    $("#addpro").click(function () {
        $("#addunit").empty();
        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
        $('select').select2();
        return false;
    });
    /************************/
    var hideBarcodeCheckClass = '';
    if (window.matchMedia("(max-width: 1100px)").matches)  {
        $('.getProByBarcode').removeClass('hidden');
        hideBarcodeCheckClass = '';
    }
    else{
        $('.getProByBarcode').addClass('hidden');
        hideBarcodeCheckClass = 'hidden';
    }


    //add new row in bill
    /**************************/
    addrow = function ($aw_if, $tabindexnumf) {
        /* alert(111);
         alert(scunitname);*/
        var showbouns = document.getElementById("showbouns").value;
        var shownumber = document.getElementById("shownumber").value;
        var settingparcode = document.getElementById("settingparcode").value;
        var settingdiscount = document.getElementById("settingdiscount").value;
        var discountrowtype = document.getElementById("discountrowtype").value;
        var settingcomment = document.getElementById("settingcomment").value;
        var sendBillToRestaurant = document.getElementById("sendBillToRestaurant").value;
        var settingUnit = document.getElementById("settingUnit").value;
        var settingNewproduct = document.getElementById("settingnewproduct").value;
        var morestore = document.getElementById("morestore").value;
        var userstoreid = document.getElementById("userstoreid").value;
        var showrowPriceType = document.getElementById("showrowPriceType").value;
        var ebillclient = document.getElementById("ebillclient").value;
        var canEditAddDiscountPercentage = document.getElementById("canEditAddDiscountPercentage").value;
        var showCatDiscount = $('#showCatDiscount').val();
        var hideBillPricesClass = '';
        var hideCatDiscountClass = '';
        if (showCatDiscount == 0) {
            hideCatDiscountClass = 'hidden';
        }

        if (hideBillPrices == 1) {
            hideBillPricesClass = 'hidden';
        }

        if (ebillclient != 1) {
            ebillclient = 'hidden';
        }
        //alert('userstoreid'+userstoreid);
        //alert('morestore'+morestore);
        $xx = '';
        $xx += '<tr id="productraw' + $aw_if + '">';
        if (settingNewproduct == 0) {
            $xx += '<td>';
        } else {
            $xx += '<td  style="display:none !important">';
        }

        $xx += '<a onClick="javascript:showProductModal(' + $aw_if + ', ' + $tabindexnumf + ');" class="newLink btn btn-primary btn-xs conformdelProduct" >جديد</a>';
        //alert('aw_if'+$aw_if);
        if (shownumber == 0) {
            $xx += '<td>';
        } else {
            $xx += '<td  style="display:none !important">';
        }

        //# check to hide
        var hidden_parcode = '';
        $('#containerpros .check_tr_parcode:first').each(function (e) {
            var ths = $(this);
            if (ths.hasClass('hidden')) {
                hidden_parcode = 'hidden';
                return false;
            }
        });
        var proSellTrackingSerialClassVar = 'hidden';
        if ($('.proSellTrackingSerialClass').length > 0) {
            proSellTrackingSerialClassVar = '';
        }
        $xx += '<span class="proDetails" data-pro="product' + $aw_if + '">' + $aw_if + '</span></td>';
        $xx += '<td class="' + proSellTrackingSerialClassVar + '">' +
            '      <input type="text" name="proSellTrackingSerial' + $aw_if + '" id="proSellTrackingSerial' + $aw_if + '"  class="form-control txt-nonraduis autoSaveBillRow" tabindex="7"  size="3"/>' +
            ' </td>';
        //        if (settingparcode == 0)
        //        {
        $xx += '<td class="' + hidden_parcode + '">';
        //        } else
        //        {
        //            $xx += '<td  style="display:none !important">';
        //        }



        $xx += '<div id="productparcode' + $aw_if + '">'
            + '  <input type="text" name="parcode' + $aw_if + '" id="parcode' + $aw_if + '" class="form-control  txt-nonraduis autoSaveBillRow" tabindex="' + $tabindexnumf + '" onkeypress="getproductbyParcode(event,this.value, ' + $aw_if + ');" size="3"  placeholder="الباركود" />'

            + ' <input name="parcodeType' + $aw_if + '" id="parcodeType' + $aw_if + '" type="hidden"/> '
            + '<input name="productserailid' + $aw_if + '" id="productserailid' + $aw_if + '" type="hidden" /> '
            + ' <input name="productQty' + $aw_if + '" id="productQty' + $aw_if + '" type="hidden" />'
            + '</div>'
            +'<span class="getProByBarcode hidden correcticon'+ hideBarcodeCheckClass +'" data-itr="' + $aw_if + '"></span>'
            +'</td>';
        //البيع من اكثر من مخزن
        $storeClass = '';
        if (morestore == 0) {
            $storeClass = '';
        } else {
            $storeClass = 'hidden';
            //            //even it is not visible is important as i use selector to loop products depend on column number in function sumProduct()
            //            $xx += '<td style="display:none !important"></td>';

        }

        //alert(morestore);

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

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



        $xx += '<td>'
            + '<div id="productdiv' + $aw_if + '">'
            + '<input type="hidden"id="product' + $aw_if + '" name="product' + $aw_if + '"  class="select2product' + $aw_if + ' wdt100 autoSaveBillRow"  data-placeholder="اختر منتج" tabindex="' + $tabindexnumf + '" />'

            + '</div>'
            + '</td>';
        if (settingcomment == 0) {
            $xx += '<td>';
        } else {
            $xx += '<td  style="display:none !important">';
        }

        if (sendBillToRestaurant == 1) {
            $xx += '<img class="drinkDetails" data-productid="" data-itr="' + $aw_if + '" width="20px" height="20px" src="../views/default/assets/img/notes2.png" alt="">' +
                '<span id="notes' + $aw_if + '"></span>' +
                ' <input type="hidden" name="hiddenNotes' + $aw_if + '" id="hiddenNotes' + $aw_if + '" value="">';
        } else {
            $xx += '<textarea class="form-control txt-nonraduis enteraction autoSaveBillRow" name="comment' + $aw_if + '" id="comment' + $aw_if + '" rows="1" tabindex="' + $tabindexnumf + '"></textarea>';
        }
        $xx += '</td>';
        //# check to hide
        var hidden_unit = '';
        $('#containerpros .check_tr_unit:first').each(function (e) {//first only is enough with is in table head
            var ths = $(this);
            if (ths.hasClass('hidden')) {
                hidden_unit = 'hidden';
                return false;
            }
        });
        var hidden_Height = '';
        $('#containerpros .check_tr_Height:first').each(function (e) {//first only is enough with is in table head
            var ths = $(this);
            if (ths.hasClass('hidden')) {
                hidden_Height = 'hidden';
                return false;
            }
        });
        var hidden_Width = '';
        $('#containerpros .check_tr_Width:first').each(function (e) {//first only is enough with is in table head
            var ths = $(this);
            if (ths.hasClass('hidden')) {
                hidden_Width = 'hidden';
                return false;
            }
        });
        var hidden_quantity = '';
        $('#containerpros .check_tr_quantity:first').each(function (e) {//first only is enough with is in table head
            var ths = $(this);
            if (ths.hasClass('hidden')) {
                hidden_quantity = 'hidden';
                return false;
            }
        });
        //        if (settingUnit == 0)
        //        {
        $xx += '<td class="' + hidden_unit + '">';
        //        } else
        //        {
        //            $xx += '<td  style="display:none !important">';
        //        }

        $xx += '<div id="productunitdiv' + $aw_if + '">'
            + '<input type="hidden" name="proNum' + $aw_if + '" id="proNum' + $aw_if + '" value=""/>'
            + '<select id="productunit' + $aw_if + '" name="productunit' + $aw_if + '" class="select2 wdt100 autoSaveBillRow" tabindex="' + $tabindexnumf + '">'

            + $("#addunit").html()
            + '</select>'
            + '</div>'
            + '</td> '


        $xx += '<td class="wdt100n check_tr_Height ' + hidden_Height + '">'
            + '                    <input type="text" name="proHeight' + $aw_if + '" id="proHeight' + $aw_if + '"  value="1" class="form-control txt-nonraduis enteraction numberinput positivefloat autoSaveBillRow" onKeyUp="calcQuantity(' + $aw_if + ', event);" tabindex="7" />'
            + '                </td>'
            + '<td class="wdt100n check_tr_Width ' + hidden_Width + '">'
            + '                    <input type="text" name="proWidth' + $aw_if + '" id="proWidth' + $aw_if + '"  value="1" class="form-control txt-nonraduis enteraction numberinput positivefloat autoSaveBillRow" onKeyUp="calcQuantity(' + $aw_if + ', event);" tabindex="7" />'
            + '                </td>';
        $xx += '<td class="' + hidden_quantity + '">'
            + '<input type="text" name="pronum' + $aw_if + '" id="pronum' + $aw_if + '"  class="form-control txt-nonraduis getprototal enteraction numberinput ' + numClass + ' autoSaveBillRow" onKeyUp="checkquantity(' + $aw_if + ', event);" value="1" tabindex="' + $tabindexnumf + '" />'
            + '</td>'


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

        if (showbouns == 0) {
            $xx += '<td>';
        } else {
            $xx += '<td  style="display:none !important">';
        }

        $xx += '<input type="text" name="bouns' + $aw_if + '" id="bouns' + $aw_if + '"  class="form-control txt-nonraduis  enteraction numberinput positiveNo autoSaveBillRow"  value="0" tabindex="' + $tabindexnumf + '" />'
            + '</td>';
        //# check to hide
        var hidden_RowPriceType = '';
        $('#containerpros .showrowPriceType:first').each(function (e) {
            var ths = $(this);
            if (ths.hasClass('hidden')) {
                hidden_RowPriceType = 'hidden';
                return false;
            }
        });
        var priceOptions = '';
        if ($('#showpriceall').val() == 1)
            priceOptions += '<option value="0">جملة</option>';
        if ($('#showpriceunit').val() == 1)
            priceOptions += '<option value="1">تجزئة</option>';
        if ($('#showpricehalf').val() == 1)
            priceOptions += '<option value="2">نصف جملة</option>';
        if ($('#showprice4').val() == 1)
            priceOptions += '<option value="4">سعر4</option>';
        if ($('#showprice5').val() == 1)
            priceOptions += '<option value="5">سعر5</option>';
        if ($('#showprice6').val() == 1)
            priceOptions += '<option value="6">سعر6</option>';
        if ($('#showprice7').val() == 1)
            priceOptions += '<option value="7">سعر7</option>';
        if ($('#showprice8').val() == 1)
            priceOptions += '<option value="8">سعر8</option>';
        if ($('#showprice9').val() == 1)
            priceOptions += '<option value="9">سعر9</option>';
        if ($('#showprice10').val() == 1)
            priceOptions += '<option value="10">سعر10</option>';
        if ($('#showprice11').val() == 1)
            priceOptions += '<option value="11">سعر11</option>';
        if ($('#showprice12').val() == 1)
            priceOptions += '<option value="12">سعر12</option>';
        if ($('#showprice13').val() == 1)
            priceOptions += '<option value="13">سعر13</option>';

        $xx += '<td class="showrowPriceType ' + hidden_RowPriceType + '">' +
            '   <select class="select2 wdt100 autoSaveBillRow" name="pricetypepro' + $aw_if + '" id="pricetypepro' + $aw_if + '">' +
            priceOptions +
            '</select>' +
            '</td>';
        $xx += '<td class="' + hideCatDiscountClass + ' ' + hideBillPricesClass + '">'
            + '<input type="text" name="pricebeforcatdis' + $aw_if + '" id="pricebeforcatdis' + $aw_if + '" readonly="readonly" class="form-control txt-nonraduis" value="0"/>'
            + '</td>';
        $xx += '<td class="' + hideCatDiscountClass + '">'
            + '<input type="text" name="catdis' + $aw_if + '" id="catdis' + $aw_if + '" readonly="readonly" class="form-control txt-nonraduis sumProDis  positiveNo autoSaveBillRow" value="0"/>'
            + '</td>';
        $xx += '<td class="' + hideBillPricesClass + '"><div id="propricechange' + $aw_if + '">'
            + '<input type="text" name="proprice' + $aw_if + '" id="proprice' + $aw_if + '"  class="form-control getprototal enteraction numberinput txt-nonraduis positivefloat autoSaveBillRow" value="0" tabindex="' + $tabindexnumf + '"  />'

            + '</div></td>';
        //# check to hide
        var hidden_discount = '';
        $('#containerpros .check_tr_discount:first').each(function (e) {
            var ths = $(this);
            if (ths.is(':visible') === false) {
                hidden_discount = 'hidden';
                return false;
            }
        });
        //        if (settingdiscount == 0)
        //        {
        $xx += '<td class="' + hidden_discount + ' ' + hideBillPricesClass + '">';
        //        } else
        //        {
        //            $xx += '<td  style="display:none !important">';
        //        }



        $cashDiscountClass = $PercentageDiscountClass = $discountSpanHtml = '';
        if (discountrowtype == 0) {
            $cashDiscountClass = '';
            $PercentageDiscountClass = 'hidden';
            $discountSpanHtml = 'C';
        } else if (discountrowtype == 1) {
            $cashDiscountClass = 'hidden';
            $PercentageDiscountClass = '';
            $discountSpanHtml = '%';
        }
        $xx += '<div class="input-group">';

        $xx += '<input name="prodis' + $aw_if + '" id="prodis' + $aw_if + '" class="form-control txt-nonraduis getprototal enteraction numberinput positiveNo autoSaveBillRow ' + $cashDiscountClass + '" value="0" tabindex="' + $tabindexnumf + '"/>';
        $xx += '<input name="discounttype' + $aw_if + '" id="discounttype' + $aw_if + '" class="form-control txt-nonraduis getprototal enteraction numberinput positivefloat autoSaveBillRow ' + $PercentageDiscountClass + '" value="0" tabindex="' + $tabindexnumf + '"/>';
        $xx += '<span class="input-group-addon small-addon discountSpan" data-itr="' + $aw_if + '">' + $discountSpanHtml + '</span>';

        $xx += '</div> </td>';
        //////////////////////////////value dicount by hazem///////////////////////////
        /* if (settingdiscount == 0)
         {
         $xx += '<td>';
         }
         else
         {
         $xx += '<td  style="display:none !important">';
         }


         $xx += '<input type="text" name="prodisper' + $aw_if + '" id="prodisper' + $aw_if + '"  class="form-control txt-nonraduis getprototal enteraction numberinput" value="0" tabindex="' + $tabindexnumf + '"  />'
         + '</td>';*/

        //////////////////////////////value dicount by hazem///////////////////////////
        //# check to hide
        var hidden_selldiscount = '';
        $('.selldiscountClass:first').each(function (e) {
            var ths = $(this);
            if (ths.hasClass('hidden')) {
                hidden_selldiscount = 'hidden';
                return false;
            }
        });

        $xx += '<td class="selldiscountClass ' + hidden_selldiscount + '">';
        if (canEditAddDiscountPercentage != 1) {
            $xx += '<span id="prosellDiscountPer_span' + $aw_if + '">0</span>' +
                '      <input name="prosellDiscountPer' + $aw_if + '" id="prosellDiscountPer' + $aw_if + '" value="0"' +
                '      class="prosellDiscountPerClass getprototal" tabindex="7" type="hidden"/>';
        } else {
            $xx += ' <div class="input-group">' +
                '                         <input name="prosellDiscountPer' + $aw_if + '" id="prosellDiscountPer' + $aw_if + '" value="0"' +
                '                                class="form-control txt-nonraduis positiveNo prosellDiscountPerClass getprototal" tabindex="7"' +
                '                                type="text" />' +
                '                        <span class="input-group-addon small-addon prosellDiscountPerTypeSpan" id="prosellDiscountPerTypeSpan' + $aw_if + '" data-itr="' + $aw_if + '">ض</span></div>';


        }
        $xx += ' <input name="prosellDiscountPerType' + $aw_if + '" id="prosellDiscountPerType' + $aw_if + '" value="0" type="hidden"/>' +
            '<input name="prosellDiscountVal' + $aw_if + '" id="prosellDiscountVal' + $aw_if + '"  value="" type="hidden"/></td>';

        $xx += '<td class="' + hideBillPricesClass + '">'
            + '<input  name="hidden_prototal' + $aw_if + '" id="hidden_prototal' + $aw_if + '" class="editTotal form-control txt-nonraduis enteraction numberinput positiveNo" value="0" type="text"/>'
            + '</td>'
        var hidden_soldSerials = '';
        $('#containerpros .check_tr_soldSerials:first').each(function (e) {
            var ths = $(this);
            if (ths.hasClass('hidden')) {
                hidden_soldSerials = 'hidden';
                return false;
            }
        });
        $xx += '<td class="' + hidden_soldSerials + '">'
            + ' <input type="hidden" name="proSerials' + $aw_if + '" id="proSerials' + $aw_if + '" data-itr="' + $aw_if + '" class="autoSaveBillRow" value=""/> '
            + '</td>';
        if (ebillclient == 1) {
            $xx += '<td>'
                + ' <button type="button" class="btn btn-primary Taxes" data-toggle="modal" data-mitr="' + $aw_if + '" data-whatever="@mdo"></button>'
                + '</td>';
            $xx2 = '  <div class="modal fade" id="ebillclient' + $aw_if + '"  role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="false">'
                + '    <div class="modal-dialog modal-lg" role="document">'
                + '        <div class="modal-content">'
                + '           <div class="modal-header">'
                + '            <button type="button" class="close pull-left" data-dismiss="modal" aria-hidden="false">×</button>'
                + '            </div>'
                + '            <div class="modal-body">'
                + '            <div style="display:none">'
                + '                <button type="button" class="btn green-meadow btn-sm pull-right addtaxes" id="addtaxes' + $aw_if + '" data-mitr="' + $aw_if + '" style="background: #55ff55"> اضافه ضريبه </button>'
                + '                <button type="button"  style="background: #f34141" class="btn green-meadow btn-sm pull-right removetaxes" id="removetaxes" data-edit="0" data-mitr="' + $aw_if + '"> حذف </button>'
                + '                <input type="hidden" id="taxesitr_' + $aw_if + '" data-mitr="' + $aw_if + '" name="taxesitr_' + $aw_if + '" value="1" >'
                + '            </div>'
                + '            <div style="clear: both;"></div>'
                + '               <ul id="taxes' + $aw_if + '">'
                + '                    <li id="litaxes' + $aw_if + '_1">'
                + '                        <div style="    width: 20% !important;float: right;">'
                + '                             <input type="hidden" name="type_' + $aw_if + '_1" data-mitr="' + $aw_if + '" data-itr="1" class="eTaxType" id="eTaxType_' + $aw_if + '_1"> '
                + '                        </div>'
                + '                        <div style="    width: 20% !important;float: right;">'
                + '                            <input type="hidden" name="subtype_' + $aw_if + '_1"  data-mitr="' + $aw_if + '" data-itr="1" class="eTaxsubtype" id="eTaxsubtype_' + $aw_if + '_1"> '
                + '                        </div>'
                + '                        <div style="    width: 20% !important;float: right;">'
                + '                            <input type="text" name="rate_' + $aw_if + '_1" data-mitr="' + $aw_if + '" data-itr="1" class="form-control must_go_req ncloseebill rates rate_' + $aw_if + '"   id="rate_' + $aw_if + '_1" placeholder="نسبه">'
                + '                        </div>'
                + '                        <div style="    width: 20% !important;float: right;">'
                + '                            <input type="text" name="amount_' + $aw_if + '_1" data-mitr="' + $aw_if + '"  data-itr="1" class="form-control must_go_req ncloseebill amounts amount_' + $aw_if + '"    id="amount_' + $aw_if + '_1" placeholder="المبلغ">'
                + '                        </div>'
                + '                        <div style="    width: 20% !important;float: right;">'
                + '                            <!--<button type="button"  style="background: #f34141"  class="btn green-meadow btn-sm pull-right removeellbilldetailtax" '
                + '                            data-edit="0" data-mitr="' + $aw_if + '" data-itr="1"> x </button>-->'
                + '                        </div>'
                + '                    </li>'
                + '                    <div style="clear: both;"></div>'
                + '                </ul>'
                + '            </div>'
                + '            <div class="modal-footer" style="text-align: center !important">'
                + '             <button type="button" style="opacity: 1;background: blue" class="close closeebill" data-mitr="' + $aw_if + '" data-dismiss="modal" aria-hidden="true" >اعتماد</button>'
                + '            </div>'
                + '        </div>'
                + '    </div>'
                + '</div>';
            $("#taxesitr").append($xx2);



        }

        $xx += '<td>'
            + '   <input type="hidden" name="tempSaveBillIdRow' + $aw_if + '" id="tempSaveBillIdRow' + $aw_if + '" value="0">'
            + '	<button id="remove' + $aw_if + '"  data-mitr="' + $aw_if + '" data-itr="' + $aw_if + '" type="button" class="close flt-none removeicon removeproduct autoDelBillRow" aria-hidden="true">&times;</button>'
            + '</td>'
            + '</tr>';
        $("#containerpros").append($xx);
        $(".positiveNo").forcepositiveNum();
        $(".numberinput").forceNumeric();
        $(".positivefloat").forcepositivefloat();
        $("#proSerials" + $aw_if).select2({
            placeholder: "",
            //minimumInputLength: document.getElementById("searchvalue").value,
            inimumInputLength: 0,
            multiple: true,
            //maximumSelectionSize: 2,
            quietMillis: 100,
            ajax: {
                url: "sellbillAjaxController.php?do=productAvailableParcodes",
                dataType: 'json',
                data: function (term, page) {
                    return {
                        term: term, //search term
                        pro: $('#product' + $aw_if).val(),
                        store: $('#prstorid' + $aw_if).val(),
                    };
                },
                results: function (data) {
                    return { results: data };
                }
            },
            formatResult: function (data) {
                $html = '<span>' + data.text + '</span >/<span style="color:chocolate">' + parseFloat(data.don) + '</span >';
                if (data.enddate != "0000-00-00")
                    $html += '/<span>' + data.enddate + '</span >';
                return $html;
            },
            formatSelection: function (data) {
                $html = '<span>' + data.text + '</span >/<span style="color:chocolate">' + parseFloat(data.don) + '</span >';
                if (data.enddate != "0000-00-00")
                    $html += '/<span>' + data.enddate + '</span >';
                return $html;
            },
            initSelection: function (element, callback) {
                var item = element.val().split(':');
                //  var data = {id: item[0], text: item[1]};
                var data = { id: item[0], text: item[1] };
                callback(data);
            },
            //dropdownCssClass: "bigdrop", // apply css that makes the dropdown taller

        }).on('change, select2-close', function (e) {
            var id = e.target.id;
            var selectedData = $("#" + id).select2('data');
            //var requiredQuantity = $("#" + id).data('quantity');//e.target.dataset.quantity;
            var itr = $("#" + id).data('itr'); //e.target.dataset.quantity;
            var pNum = Number($('#productunit' + itr + ' :selected').data('pu-num'));
            var quantity = Number($('#pronum' + itr).val());
            var requiredQuantity = quantity * pNum;
            var selctedQuantity = 0;
            for (var i = 0; i < selectedData.length; i++) {
                selctedQuantity += Number(selectedData[i].don);
            }

            $("#" + id).parent().find('ul').removeClass('serial-success serial-error');
            $("#" + id).parent().find('li').removeClass('serial-success serial-error');
            $("#" + id).removeClass('serial-success serial-error');
            if (selctedQuantity > 0) {
                if (selctedQuantity >= requiredQuantity) {
                    $("#" + id).parent().find('ul').addClass('serial-success');
                    $("#" + id).parent().find('li').addClass('serial-success');
                    $("#" + id).addClass('serial-success');
                } else {
                    $("#" + id).parent().find('ul').addClass('serial-error');
                    $("#" + id).parent().find('li').addClass('serial-error');
                    $("#" + id).addClass('serial-error');
                }
            }
        });


        $("#pricetypepro" + $aw_if).val($("#pricetype").val());
        // varaible to contains the common itration
        var n = $aw_if;
        var tbindexn = $tabindexnumf;
        //assign select2 properties
        if (morestore == 0) {

            // alert( document.getElementById("prstorid"+n).value );


            $(".select2product" + n).select2({
                placeholder: "إسم المنتج",
                minimumInputLength: document.getElementById("searchvalue").value,
                //minimumInputLength: 3,
                multiple: false,
                quietMillis: 100,
                ajax: {
                    url: "sellbillAjaxController.php?do=getProducts",
                    dataType: 'json',
                    data: function (term, page) {
                        return {
                            term: term, //search term
                            page_limit: 10, // page size
                            storeid: document.getElementById("prstorid" + n).value,
                            hiddenpricetype: document.getElementById("pricetypepro" + n).value, //pricetype
                            suppplier: document.getElementById("supplier").value,
                            searchWithCatAndProductNameOnly: document.getElementById("searchWithCatAndProductNameOnly").value,
                        };
                    },
                    results: function (data) {
                        //alert())
                        //  console.log('44444444444444');


                        return { results: data };
                    }
                },
                formatResult: formatResult,
                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);
                },
                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-open', function () {
                $('#select2-drop').addClass('largeWidthForDropDown');
            }).on('select2-close', function () {
                $('#select2-drop').removeClass('largeWidthForDropDown');
            });
        } else {
            // alert('in else');
            //alert(document.getElementById("storeid").value);
            //   console.log('yyyyyyyyyyyyyy');

            $(".select2product" + n).select2({
                placeholder: "إسم المنتج",
                minimumInputLength: document.getElementById("searchvalue").value,
                //minimumInputLength: 3,
                multiple: false,
                quietMillis: 100,
                ajax: {
                    url: "sellbillAjaxController.php?do=getProducts",
                    dataType: 'json',
                    data: function (term, page) {
                        return {
                            term: term, //search term
                            page_limit: 10, // page size
                            storeid: document.getElementById("storeid").value,
                            hiddenpricetype: document.getElementById("pricetypepro" + n).value, //pricetype
                            suppplier: document.getElementById("supplier").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]};
                    var data = { id: item[0], text: item[1], productquantity: item[2], price: item[3] };
                    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-open', function () {
                $('#select2-drop').addClass('largeWidthForDropDown');
            }).on('select2-close', function () {
                $('#select2-drop').removeClass('largeWidthForDropDown');
            });
        }
        //choose main store for the row
        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_if).val($("#storeid").val()).trigger('change.select2');
        }

        let lastStoreVal = $('#prstorid' + ($aw_if - 1)).val();
        if (lastStoreVal != undefined && Number(lastStoreVal) > 0)
            $("#prstorid" + $aw_if).val(lastStoreVal).trigger('change.select2');

        ///////////////////////discount by value by hazem/////////////////////////////////
        $("#prodisper1").keyup(function () {

            $noOfDecimalPlaces = $("#noOfDecimalPlaces").val();
            var totaldiscountnew = Number($("#hidden_prototal1").val()) * (Number($("#prodisper1").val()) / 100);
            //alert(totaldiscountnew);
            $("#prodis1").val((totaldiscountnew).toFixed($noOfDecimalPlaces));
            calcuproduct(1);
        })
        $("#prodisper" + n).keyup(function () {

            $noOfDecimalPlaces = $("#noOfDecimalPlaces").val();
            var totaldiscountnew = Number($("#hidden_prototal" + n).val()) * (Number($("#prodisper" + n).val()) / 100);
            //alert(totaldiscountnew);
            $("#prodis" + n).val((totaldiscountnew).toFixed($noOfDecimalPlaces));
            calcuproduct(n);
        })
        //////////////////////////////////////////////////////////////////////////////////////
        //action in change of created dropdown list  to load the price
        $("#product" + n).change(function () {
            let pro = $("#product" + n).select2("data");

            var pricetype = document.getElementById("pricetypepro" + n).value//pricetype
            var supplier = document.getElementById("supplier").value;
            $previousPriceStatus = $('#previousPriceStatus').val();
            if ($previousPriceStatus == 1)//don't show previous product price
            {
                supplier = "";
            }

            //here  will get the price for every product
            //the selected value in drop down list
            var theselectedvalue = $(this).val();
            if (theselectedvalue != "" && theselectedvalue != "null" && theselectedvalue != null && theselectedvalue != "-1") {
                checkForRepeatedProducts(n, 0);
                //var storeid = document.getElementById("storeid").value;
                //using the load method to load the price
                //$("#productunitdiv" + n).html('<img src="../views/default/images/loader/6.gif" alt="">');
                $("#addunit").empty();
                //////////////////////////////////////////////////
                if (theselectedvalue.indexOf("hasSizeColor") == 0) {
                    //when selecting sizecolor product make sure not to sent parcode
                    //not stoping it in php to keep case of using sizecolor parcode working
                    var productParcode = '';
                } else {
                    var productParcode = $("#parcode" + n).val();
                }


                //                var productData = $("#product" + n).select2('data');
                var OtherParameters = '';
                //                if (productData.isProUnitParcode == 1) {
                //                    OtherParameters = '&comingproserial=1&parcode=' + productData.userEnteredParcode;
                //                }

                ///load unit , parcode, and price
                $.ajax({
                    url: '' + productpricepagename + '?do=getunit&itrs=' + n + '&tabindex=' + tbindexn + '&productid=' + theselectedvalue + '&pricetype=' + pricetype + '&clientid=' + supplier + '&parcode=' + productParcode + '&billnameid=' + $('#billnameid').val() + OtherParameters,
                    type: "get",
                    success: function (data) {
                        var response = $.parseJSON(data);
                        //populate unit
                        $('#productunitdiv' + n).html(response.unitString);
                        //  $("#addunit").empty();

                        $("#productunitdiv" + n + " option").clone().appendTo("#addunit");
                        //maximun product quantity
                        $("#productQty" + n).val(response.productQty);
                        //populate buy price
                        $('#propricechange' + n).html(response.priceString);

                        if (pro.fromOfferPrice == 1)
                            $('#proprice' + n).val(pro.price);

                        $('#catdis' + n).val($('#selldiscount' + n).val());
                        $('#pricebeforcatdis' + n).val(Number($('#selldiscount' + n).val()) + Number($('#proprice' + n).val()));
                        sumProDis();
                        //--fatma
                        if ($('#parcodeBalance_data_hidden' + n).length > 0) {
                            var parcodeBalance_data = $('#parcodeBalance_data_hidden' + n).val();
                            parcodeBalance_data = parcodeBalance_data.split('*');
                            var useParcodeBalance = parcodeBalance_data[0];
                            var WeightPricePart = parcodeBalance_data[1];
                            var posType = parcodeBalance_data[2];
                            if (useParcodeBalance == 1 && posType == 1) {
                                $('#proprice' + n).val(WeightPricePart);
                                $('#pronum' + n).val(1);
                            }
                        }
                        //change price of product from main curr to slected curr val
                        $('#proprice' + n).val(getValueInTermsOfSelectedCurrency($('#proprice' + n).val()));

                        $("#parcodeType" + n).val(response.parcodeType);
                        $("#productQty" + n).val(response.productQty);
                        $("#productserailid" + n).val(response.productserailid);
                        //----



                        var productData = $("#product" + n).select2('data');
                        $('#prosellDiscountPer' + n).val(productData.selldiscountpercent);
                        $('#prosellDiscountPer_span' + n).html(productData.selldiscountpercent);
                        $('#prosellDiscountPerType' + n).val(productData.sellpercenttype);
                        var prosellDiscountPerTypeSpanTxt = (productData.sellpercenttype == 0) ? 'ض' : 'خ';
                        $('#prosellDiscountPerTypeSpan' + n).html(prosellDiscountPerTypeSpanTxt);


                        //--fatma -last discount
                        if ($("#lastClientDisVal" + n).length > 0 && Number($("#lastClientDisVal" + n).val() > 0)) {
                            $('#prodis' + n).val($("#lastClientDisVal" + n).val());
                            $('#discounttype' + n).val($("#lastClientDisPer" + n).val());
                            $('#prodis' + n).css('background-color', '#b7dfa4');
                            $('#discounttype' + n).css('background-color', '#b7dfa4');
                        } else {
                            $('#prodis' + n).val(0);
                            $('#discounttype' + n).val(0);
                            $('#prodis' + n).css('background-color', '#fff');
                            $('#discounttype' + n).css('background-color', '#fff');
                        }
                        //----


                        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 priceupdate = document.getElementById("priceupdate").value;
                        if (priceupdate == 0) {
                            //alert(0);
                            $('#proprice' + n).prop('readonly', true);
                            $('#hidden_prototal' + n).prop('readonly', true);
                        } else {
                            //alert(1);
                            $('#proprice' + n).prop('readonly', false);
                            $('#hidden_prototal' + n).prop('readonly', false);
                        }
                        //check if sellprice less than buyprice
                        $("#proprice" + n).change();
                        $('#productparcode' + n).html(response.parcodeString);
                        var parcodeType = document.getElementById("parcodeType" + n).value;
                        if (parcodeType == "serialnumber") {
                            $('#pronum' + n).val(1);
                            // $('#pronum' + n).attr('readonly', true);
                        } else {
                            $('#pronum' + n).attr('readonly', false);
                        }

                        //here all code that will happend with loading contants
                        //the number of rows of products
                        var noitr = document.getElementById("hidden_itr").value;
                        document.getElementById("pronum" + n).value = 1;
                        document.getElementById("prodis" + n).value = 0;
                        //to calculate the price and amount with discount
                        calcuproduct(n);
                        //get the total price of sell
                        selltotalprice(noitr);
                        // get the total price of sell and return sell
                        totalprice();
                        //get the general discount
                        thegeneraldiscount();
                        checkthepayed();
                        //get the general payed
                        thegeneralpayed();
                        // calculate the rest of debt
                        therestofdebt();
                        document.getElementById("hiddenpricetype").value = document.getElementById("pricetype").value;
                        var settingQuantitiyFocus = document.getElementById("settingQuantitiyFocus").value;
                        if ((Number($aw_i) - Number(n)) == 1) {
                            $("#addunit").empty();
                            addrow($aw_i, $tabindexnum);
                            if (settingQuantitiyFocus == 0 && parcodeType != "serialnumber") {
                                $("#pronum" + n).focus();
                                $("#pronum" + n).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++;
                        } else {
                            if (settingQuantitiyFocus == 0 && parcodeType != "serialnumber") {
                                $("#pronum" + n).focus();
                                $("#pronum" + n).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');
                                }
                            }
                        }

                        //تنبيه بالكمية المتاحة من المنتج
                        var settingQuantityAlert = document.getElementById('settingQuantityAlert').value;
                        if (settingQuantityAlert == 0) {
                            //alert('n'+n);
                            var storeid;
                            if (morestore == 0) {
                                storeid = $("#prstorid" + n).val();
                            } else {
                                storeid = $("#storeid").val();
                            }
                            //alert('storeid'+storeid);
                            $.ajax({
                                type: 'POST',
                                url: '' + productpricepagename + '?do=getProductQuantity&productid=' + theselectedvalue + '&storeid=' + storeid,
                                success: function (data) {
                                    if (data <= 0) {
                                        $("#errorquantity").html(data);
                                        $('#storemodel').modal('show');
                                        // $('#storenegative').val(0);
                                    }
                                }
                            });
                        }
                        $('select').select2();
                    },
                    error: function () {
                        alert("لقد حدث خطأ أثناء إجراء العملية");
                    }
                });
                //////////////////////////////////////////////////
            }
        });
    }
    /**************************/


    // the delete action that delete row of products
    /************************/
    $(document).on('click', '.removeproduct', function () {

        var allowBillDelete = Number($('#allowBillDelete').val());
        var itr = $(this).attr('data-itr');
        if (allowBillDelete == 0) {

            //this_is.unbind('click').click();
            delFunc($(this).attr('id'));
            $('#ebillclient' + itr).remove();
            closeebill(itr);
        } else {
            $('#delBtnId').val($(this).attr('id'));
            $('#ckPassModal').modal('show');
        }
    });
    $(document).on('click', '#ckPassDel', function () {
        ckPass();
    });
    function delFunc(id) {
        autoDelBillRowFunc($('#' + id));
        // delete by partents
        $('#' + id).parent().parent().remove();
        // get the itration from itration colum
        $remitr = document.getElementById("hidden_itr").value


        //get the total price of sell
        selltotalprice($remitr);
        // get the total price of sell and return sell
        totalprice();
        //get the general discount
        thegeneraldiscount();
        checkthepayed();
        //get the general payed
        thegeneralpayed();
        // calculate the rest of debt
        therestofdebt();
        sumProDis();
        return false;
    }
    function ckPass() {
        var pass = $('#pass').val();
        if (pass == "") {
            $('#pass').css('background-color', 'yellow');
        } else {
            $('#pass').css('background-color', 'white');
            $.ajax({
                type: "POST",
                url: 'sellbillAjaxController.php?do=ckpass',
                data: { pass: pass },
                async: false,
                success: function (data) {
                    data = Number(data);
                    if (data == 1) {
                        $('#pass').css('background-color', 'white');
                        $('#pass').val("");
                        $('#ckPassModal').modal('hide');
                        delFunc($('#' + $('#delBtnId').val()).attr('id'));
                    }
                    if (data == 0) {
                        $('#pass').css('background-color', 'red');
                    }
                }
            });
        }
    }
    /************************/

    // calculating the product price
    // on keyup action
    /************************/
    $(document).on('keyup', ".getprototal", function () {
        //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":
                thecolnmu = currentId.substr(6);
                let halfPriceStart = $('#halfPriceStart').val();
                let allPriceStart = $('#allPriceStart').val();
                let val = Number($(this).val());
                if (halfPriceStart != undefined && allPriceStart != undefined) {
                    if (val >= allPriceStart && allPriceStart > 0)
                        $('#pricetypepro' + thecolnmu).val(0).trigger('change');
                    else if (val >= halfPriceStart && halfPriceStart > 0)
                        $('#pricetypepro' + thecolnmu).val(2).trigger('change');
                    else
                        $('#pricetypepro' + thecolnmu).val(1).trigger('change');
                }

                sumProDis();
                break;
            case "prod":
                thecolnmu = currentId.substr(6);
                break;
            case "pros":
                thecolnmu = currentId.substr(18);
                break;
            /*case "xpro":

             thecolnmu = currentId.substr(10);
             alert(thecolnmu);
             var totaldiscountnew = Number($("#hidden_prototal"+thecolnmu).val())*( Number($("#prodisper"+thecolnmu).val())/100 );
             alert(totaldiscountnew);
             $("#prodis"+thecolnmu).val((totaldiscountnew).toFixed(2));
             break;
             */
            default:
                thecolnmu = 0;
        }


        // get the total of product
        calcuproduct(thecolnmu);
        //get the total price of sell
        selltotalprice($aw_i);
        // get the total price of sell and return sell
        totalprice();
        //get the general discount
        thegeneraldiscount();
        checkthepayed();
        //get the general payed
        thegeneralpayed();
        // calculate the rest of debt
        therestofdebt();
    });
    /************************/
    $(document).on('keyup', ".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);
        }
        //change price of product from main curr to slected curr val
        $('#proprice' + thecolnmu).val(getValueInTermsOfSelectedCurrency($('#proprice' + thecolnmu).val()));
        //get the total price of sell
        selltotalprice($aw_i);
        // get the total price of sell and return sell
        totalprice();
        //get the general discount
        thegeneraldiscount();
    });
    /***************************************/
    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(5));
        data.lastbuyprice = Number((data.price * cfactor).toFixed(5));


        $choice = data.text;
        if (hideBillPrices != 1)
            $choice += '<span style="text-align: left;  float: left;  width: 20%;">' + Number(data.price) + '</span >';
        $choice += '<span  style="text-align: left;float: left;  width :10%;"  > ' + Number(data.productquantity) + '</span >';
        if (data.sellStat != null)
            $choice += '<span style="text-align: left; float: left; margin-left: 5px; width:10%; color:green;"  >' + data.sellStat + '</span>';
        if (data.weightedDiscount != null && Number(data.weightedDiscount) > 0)
            $choice += '<span style="text-align: left; float: left; margin-left: 5px; width:10%; color:red;"  >' + data.weightedDiscount + '%</span>';
        if (data.lastbuyprice)
            $choice += '<span style="text-align: left; float: left; margin-left: 5px; width:10%; color:blue;"  >' + Number(data.lastbuyprice) + '</span>';
        return $choice;
        /* return   s= ' + <table  border="1"> <tr>'
         '+  <td>'+data.text+'</td>'
         '+<td>'+data.productquantity+'</td>'
         '+ <td>'+data.price+'</td>'
         '+ </tr>'
         '+</table>';*/
    }


    //assign select2 properties
    var morestore = document.getElementById("morestore").value;
    //storeid: document.getElementById("prstorid"+n).value ,

    if (morestore == 0) {


        $(".select2product").select2({
            placeholder: "إسم المنتج",
            minimumInputLength: document.getElementById("searchvalue").value,
            multiple: false,
            quietMillis: 100,
            ajax: {
                url: "sellbillAjaxController.php?do=getProducts",
                dataType: 'json',
                data: function (term, page) {
                    //alert("sellbillAjaxController.php?do=getProducts&term="+term+"&page_limit=10&storeid="+document.getElementById("storeid").value);
                    return {
                        term: term, //search term
                        page_limit: 10, // page size,
                        storeid: document.getElementById("prstorid1").value,
                        hiddenpricetype: document.getElementById("pricetypepro1").value, //pricetype
                        suppplier: document.getElementById("supplier").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], productquantity: item[2], price: item[3] };
                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-open', function () {
            $('#select2-drop').addClass('largeWidthForDropDown');
        }).on('select2-close', function () {
            $('#select2-drop').removeClass('largeWidthForDropDown');
        });
    } else {
        // console.log('333333333333333');


        $(".select2product").select2({
            placeholder: "إسم المنتج",
            minimumInputLength: document.getElementById("searchvalue").value,
            multiple: false,
            quietMillis: 100,
            ajax: {
                url: "sellbillAjaxController.php?do=getProducts",
                dataType: 'json',
                data: function (term, page) {
                    //alert("sellbillAjaxController.php?do=getProducts&term="+term+"&page_limit=10&storeid="+document.getElementById("storeid").value);
                    return {
                        term: term, //search term
                        page_limit: 10, // page size,

                        storeid: document.getElementById("storeid").value,
                        //storeid: document.getElementById("prstorid1").value,
                        //storeid: '1',

                        hiddenpricetype: document.getElementById("pricetypepro1").value, //pricetype
                        suppplier: document.getElementById("supplier").value,
                        searchWithCatAndProductNameOnly: document.getElementById("searchWithCatAndProductNameOnly").value,
                    };
                },
                results: function (data) {
                    //console.log(data);
                    return { results: data };
                }
            },
            formatResult: formatResult,
            initSelection: function (element, callback) {

                var item = element.val().split(':');
                var data = { id: item[0], text: item[1], productquantity: item[2], price: item[3] };
                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-open', function () {
            $('#select2-drop').addClass('largeWidthForDropDown');
        }).on('select2-close', function () {
            $('#select2-drop').removeClass('largeWidthForDropDown');
        });
    }


    // here the frist action on frist dropdownlist
    /************************/
    $("#product1").change(function () {
        let pro = $("#product1").select2("data");

        var pricetype = document.getElementById("pricetypepro1").value//pricetype
        var supplier = document.getElementById("supplier").value;
        var priceupdate = document.getElementById("priceupdate").value;
        $previousPriceStatus = $('#previousPriceStatus').val();
        if ($previousPriceStatus == 1)//don't show previous product price
        {
            supplier = "";
        }

        //here get the price of product from ajax
        //the selected value of drop downlsit
        var theselectedvalue = $(this).val();
        if (theselectedvalue != "" && theselectedvalue != "null" && theselectedvalue != null && theselectedvalue != "-1") {
            checkForRepeatedProducts(1, 0);
            //using the load method to load the price
            // $("#productunitdiv1").html('<img src="../views/default/images/loader/6.gif" alt="">');
            //////////////////////////////////////////////////

            if (theselectedvalue.indexOf("hasSizeColor") == 0) {
                //when selecting sizecolor product make sure not to sent parcode
                //not stoping it in php to keep case of using sizecolor parcode working
                var productParcode = '';
            } else {
                var productParcode = $("#parcode1").val();
            }


            //            var productData = $("#product1").select2('data');
            var OtherParameters = '';
            //            if (productData.isProUnitParcode == 1) {
            //                OtherParameters = '&comingproserial=1&parcode=' + productData.userEnteredParcode;
            //            }

            $.ajax({
                url: '' + productpricepagename + '?do=getunit&itrs=1&tabindex=7&productid=' + theselectedvalue + '&pricetype=' + pricetype + '&clientid=' + supplier + '&parcode=' + productParcode + '&billnameid=' + $('#billnameid').val() + OtherParameters,
                type: "get",
                success: function (data) {
                    var response = $.parseJSON(data);
                    //populate unit
                    $('#productunitdiv1').html(response.unitString);
                    $("#addunit").empty();
                    $("#productunitdiv1 option").clone().appendTo("#addunit");
                    if (response.parcodeString != '' && response.parcodeString != null) {
                        $('#productparcode1').html(response.parcodeString);
                    }

                    //maximun product quantity
                    //$("#productQty1").val(response.productQty);

                    //populate buy price
                    $('#propricechange1').html(response.priceString);

                    if (pro.fromOfferPrice == 1)
                        $('#proprice1').val(pro.price);

                    $('#catdis1').val($('#selldiscount1').val());
                    $('#pricebeforcatdis1').val(Number($('#selldiscount1').val()) + Number($('#proprice1').val()));
                    sumProDis();

                    //--fatma
                    if ($('#parcodeBalance_data_hidden1').length > 0) {
                        var parcodeBalance_data = $('#parcodeBalance_data_hidden1').val();
                        parcodeBalance_data = parcodeBalance_data.split('*');
                        var useParcodeBalance = parcodeBalance_data[0];
                        var WeightPricePart = parcodeBalance_data[1];
                        var posType = parcodeBalance_data[2];
                        if (useParcodeBalance == 1 && posType == 1) {
                            $('#proprice1').val(WeightPricePart);
                            $('#pronum1').val(1);
                        }
                    }



                    //change price of product from main curr to slected curr val
                    $('#proprice1').val(getValueInTermsOfSelectedCurrency($('#proprice1').val()));

                    $("#parcodeType1").val(response.parcodeType);
                    $("#productQty1").val(response.productQty);
                    $("#productserailid1").val(response.productserailid);
                    //----

                    var productData = $("#product1").select2('data');
                    $('#prosellDiscountPer1').val(productData.selldiscountpercent);
                    $('#prosellDiscountPer_span1').html(productData.selldiscountpercent);
                    $('#prosellDiscountPerType1').val(productData.sellpercenttype);
                    var prosellDiscountPerTypeSpanTxt = (productData.sellpercenttype == 0) ? 'ض' : 'خ';
                    $('#prosellDiscountPerTypeSpan1').html(prosellDiscountPerTypeSpanTxt);


                    //--fatma -last discount
                    if ($("#lastClientDisVal1").length > 0 && Number($("#lastClientDisVal1").val() > 0)) {
                        $('#prodis1').val($("#lastClientDisVal1").val());
                        $('#discounttype1').val($("#lastClientDisPer1").val());
                        $('#prodis1').css('background-color', '#b7dfa4');
                        $('#discounttype1').css('background-color', '#b7dfa4');
                    } else {
                        $('#prodis1').val(0);
                        $('#discounttype1').val(0);
                        $('#prodis1').css('background-color', '#fff');
                        $('#discounttype1').css('background-color', '#fff');
                    }
                    //----


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


                    if (priceupdate == 0) {
                        //alert(0);
                        $('#proprice1').prop('readonly', true);
                        $('#hidden_prototal1').prop('readonly', true);
                    } else {
                        //alert(1);
                        $('#proprice1').prop('readonly', false);
                        $('#hidden_prototal1').prop('readonly', false);
                    }

                    //check if sellprice less than buyprice
                    $("#proprice1").change();
                    var parcodeType = document.getElementById("parcodeType1").value;
                    if (parcodeType == "serialnumber") {
                        $('#pronum1').val(1);
                        // $('#pronum1').attr('readonly', true);
                    } else {
                        $('#pronum1').attr('readonly', false);
                    }

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

                    $(".positivefloat").forcepositivefloat();
                    // get the total of product
                    calcuproduct(1);
                    //get the total price of sell
                    selltotalprice(noitr);
                    // get the total price of sell and return sell
                    totalprice();
                    //get the general discount
                    thegeneraldiscount();
                    checkthepayed();
                    //get the general payed
                    thegeneralpayed();
                    // calculate the rest of debt
                    therestofdebt();
                    //********************************************//
                    //daiable price  type
                    //$('#pricetype').attr('disabled', true);
                    //$("#pricetype").trigger('liszt:updated');

                    document.getElementById("hiddenpricetype").value = document.getElementById("pricetype").value;
                    //********************************************//
                    var settingQuantitiyFocus = document.getElementById("settingQuantitiyFocus").value;
                    if (Number($aw_i) - 1 == 1) {
                        $("#addunit").empty();
                        addrow($aw_i, $tabindexnum);
                        if (settingQuantitiyFocus == 0 && parcodeType != "serialnumber") {
                            $("#pronum1").focus();
                            $("#pronum1").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++;
                    }

                    //تنبيه بالكمية المتاحة من المنتج
                    var settingQuantityAlert = document.getElementById('settingQuantityAlert').value;
                    if (settingQuantityAlert == 0) {
                        //alert('n'+n);
                        var storeid;
                        if (morestore == 0) {
                            storeid = $("#prstorid1").val();
                        } else {
                            storeid = $("#storeid").val();
                        }
                        //alert('storeid'+storeid);
                        $.ajax({
                            type: 'POST',
                            url: '' + productpricepagename + '?do=getProductQuantity&productid=' + theselectedvalue + '&storeid=' + storeid,
                            success: function (data) {
                                if (data <= 0) {
                                    $("#errorquantity").html(data);
                                    $('#storemodel').modal('show');
                                    // $('#storenegative').val(0);
                                }
                            }
                        });
                    }
                    $('select').select2();
                },
                error: function () {
                    alert("لقد حدث خطأ أثناء إجراء العملية");
                }
            });
            //////////////////////////////////////////////////
        }
    });
    $("#proSerials1").select2({
        placeholder: "",
        //minimumInputLength: document.getElementById("searchvalue").value,
        inimumInputLength: 0,
        multiple: true,
        //maximumSelectionSize: 2,
        quietMillis: 100,
        ajax: {
            url: "sellbillAjaxController.php?do=productAvailableParcodes",
            dataType: 'json',
            data: function (term, page) {
                return {
                    term: term, //search term
                    pro: $('#product1').val(),
                    store: $('#prstorid1').val(),
                };
            },
            results: function (data) {
                return { results: data };
            }
        },
        formatResult: function (data) {
            $html = '<span>' + data.text + '</span >/<span style="color:chocolate">' + parseFloat(data.don) + '</span >';
            if (data.enddate != "0000-00-00")
                $html += '/<span>' + data.enddate + '</span >';
            return $html;
        },
        formatSelection: function (data) {
            $html = '<span>' + data.text + '</span >/<span style="color:chocolate">' + parseFloat(data.don) + '</span >';
            if (data.enddate != "0000-00-00")
                $html += '/<span>' + data.enddate + '</span >';
            return $html;
        },
        initSelection: function (element, callback) {
            var item = element.val().split(':');
            //  var data = {id: item[0], text: item[1]};
            var data = { id: item[0], text: item[1] };
            callback(data);
        },
        //dropdownCssClass: "bigdrop", // apply css that makes the dropdown taller

    }).on('change, select2-close', function (e) {
        var id = e.target.id;
        var selectedData = $("#" + id).select2('data');
        //var requiredQuantity = $("#" + id).data('quantity');//e.target.dataset.quantity;
        var itr = $("#" + id).data('itr'); //e.target.dataset.quantity;
        var pNum = Number($('#productunit' + itr + ' :selected').data('pu-num'));
        var quantity = Number($('#pronum' + itr).val());
        var requiredQuantity = quantity * pNum;
        var selctedQuantity = 0;
        for (var i = 0; i < selectedData.length; i++) {
            selctedQuantity += Number(selectedData[i].don);
        }

        $("#" + id).parent().find('ul').removeClass('serial-success serial-error');
        $("#" + id).parent().find('li').removeClass('serial-success serial-error');
        $("#" + id).removeClass('serial-success serial-error');
        if (selctedQuantity > 0) {
            if (selctedQuantity >= requiredQuantity) {
                $("#" + id).parent().find('ul').addClass('serial-success');
                $("#" + id).parent().find('li').addClass('serial-success');
                $("#" + id).addClass('serial-success');
            } else {
                $("#" + id).parent().find('ul').addClass('serial-error');
                $("#" + id).parent().find('li').addClass('serial-error');
                $("#" + id).addClass('serial-error');
            }
        }
    });
    /************************/


    // get the total price
    /************************/
    selltotalprice = function ($ix) {
        // varaible that will carry total price
        var thealltotal = "";
        //loop to sum the all prices
        var totalprosellDiscountVal = 0;
        $totalQty = 0;
        $totalQtyToShow = new Array();
        for ($x = 1; $x <= $ix; $x++) {
            var numco = $x;
            var inputname = "#hidden_prototal" + numco;
            //to make sure that all input is created
            if ($("#product" + numco).val() == "-1" || $("#product" + numco).val() == "" || $("#product" + numco).val() == null) {
                continue;
            } else {
                //Calculate it again to make sure that there are no errors in calculations
                calcuproduct(numco);

                if (addServiceToBill == 1 && $("#product" + numco).select2('data').isService == 1) {
                    //dont count no of servise only value
                } else {
                    $totalQty = $totalQty + Number(document.getElementById("pronum" + numco).value);
                    $proQty = Number(document.getElementById("pronum" + numco).value);
                    $unitName = $('#productunit' + numco + ' option:selected').text();
                    if (!$totalQtyToShow[$unitName]) {
                        $totalQtyToShow[$unitName] = 0;
                    }
                    $totalQtyToShow[$unitName] = $totalQtyToShow[$unitName] + $proQty;
                }
                // sum method
                thealltotal = Number(thealltotal) + Number(document.getElementById("hidden_prototal" + numco).value)
                //####
                //                var prosellDiscountPer = Number($('#prosellDiscountPer' + numco).val()) / 100;
                var prosellDiscountPerType = Number($('#prosellDiscountPerType' + numco).val());
                if (prosellDiscountPerType == 0) {//+
                    totalprosellDiscountVal += Number($('#prosellDiscountVal' + numco).val());
                } else if (prosellDiscountPerType == 1) {//-
                    totalprosellDiscountVal -= Number($('#prosellDiscountVal' + numco).val());
                }


                //####

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

                $("#sellbilltotal").html(thealltotal);
                /////////////////////add by sara ////
                document.getElementById("sellbillprice").value = thealltotal;
            }
        }
        //--this way is for modern browsers
        //        Object.keys($totalQtyToShow).forEach(function (key, index) {
        //            console.log("Key is " + key + ", value is" + this[key]);
        //        }, $totalQtyToShow);
        //--this way is for all
        $allUnitsTotal = '';
        for (var k in $totalQtyToShow) {
            if ($totalQtyToShow.hasOwnProperty(k)) {
                $allUnitsTotal += '<span style="font-weight: bold">' + $totalQtyToShow[k] + k + ' </span>,';
                //console.log("Key is " + k + ", value is" + $totalQtyToShow[k]);
            }
        }
        $allUnitsTotal = $allUnitsTotal.slice(0, -1);
        //$('#unitsQty').html($allUnitsTotal);
        $("#totalQty").html($allUnitsTotal);
        $("#sellQuantity").val($totalQty);
        $round_numbers = $("#round_numbers").val();
        $noOfDecimalPlaces = $("#noOfDecimalPlaces").val();
        //check round number property
        if ($round_numbers == 0) //التقريب لأقرب عدد صحيح
        {
            thealltotal = Math.round(thealltotal);
        } else //التقريب لأقرب رقم
        {

            /*alert(Math.round(thealltotal * 10) / 10);
             alert(555);
             // thealltotal = Math.round(thealltotal * 10) / 10;
             thealltotal = ((Number(thealltotal)).toFixed($noOfDecimalPlaces));
             ;
             /* alert(thealltotal)
             thealltotal = thealltotal.toFixed($noOfDecimalPlaces);
             alert(thealltotal)*/


        }

        //insert the value in div
        $("#sellbilltotal").html(thealltotal);
        $("#totalprosellDiscountVal").html(totalprosellDiscountVal);
        $("#totalprosellDiscountVal_hidden").val(totalprosellDiscountVal);
        /////////////////////add by sara ////
        document.getElementById("sellbillprice").value = thealltotal;
    }
    /************************/


    // get the total price
    /************************/
    totalprice = function () {
        //alert(111111)
        var sellbillprice = document.getElementById("sellbillprice").value;
        var returnsellbillprice = document.getElementById("returnsellbillprice").value;
        $round_numbers = $("#round_numbers").val();
        $noOfDecimalPlaces = $("#noOfDecimalPlaces").val();
        $roundnumbersbilltotal = $("#roundnumbersbilltotal").val();
        // sum method
        var total = Number(sellbillprice) - Number(returnsellbillprice)

        //######################################################################
        var ebillclient = document.getElementById("ebillclient").value;
        if (ebillclient == 1) {
            closeebill();
        }
        //alert('total'+total);
        //check round number property
        if ($roundnumbersbilltotal == 0) //التقريب لأقرب عدد صحيح
        {
            total = total + Number($('#etotal').val());
        } else //التقريب لأقرب رقم
        {
            // total = Math.round(total * 10) / 10;
            //alert(total);
            total = (total + Number($('#etotal').val())).toFixed($noOfDecimalPlacesBillTotal);
        }

        //insert the value in div
        $("#gentotal").html(Number(total).toFixed($noOfDecimalPlacesBillTotal));

        if ($('#isMedicalBill').val() == 1)
            calcMed();
        /////////////////////add by sara ////
        document.getElementById("sellbilltotalbill").value = Number(total).toFixed($noOfDecimalPlacesBillTotal);
        howMuchDiscount(total);

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

        //if there is client rather than نقدي
        if ($("#supplier").val() != '-1' && $("#supplier").val() != '-2' && (($("#multiclient").val() == 1 && $("#supplier").val() != '1') || ($("#multiclient").val() == 0 && $("#supplier").val().indexOf("1") != -1))) {
            if (clientType == 1 && !$('#sellbillForm').hasClass('processing') && (TillFinishLoadingCountNeeded == -10 || TillFinishLoadingCountNeeded < generaldiscountUsesCountFlag)) {//nakdi as client type @billsetting
                if (total > 0) {
                    document.getElementById("genpay").value = total;
                    document.getElementById("genpayvisa").value = 0;
                } else {
                    document.getElementById("genpay").value = -1 * total;
                    document.getElementById("genpayvisa").value = 0;
                }
            }
            $('#genpay').removeAttr('readonly');
            $('#genpayvisa').removeAttr('readonly');
            //document.getElementById("genpay").value = 0;
        } else {//nakdi
            if (total > 0) {
                document.getElementById("genpay").value = total;
                document.getElementById("genpayvisa").value = 0;
            } else {
                document.getElementById("genpay").value = -1 * total;
                document.getElementById("genpayvisa").value = 0;
            }
            $('#genpay').attr('readonly', 'readonly');
            //            $('#genpayvisa').attr('readonly', 'readonly');
        }
    }
    /************************/


    // method that calculate discount
    /************************/
    thegeneraldiscount = function () {

        generaldiscountUsesCountFlag = generaldiscountUsesCountFlag + 1;

        //calculate the dicount
        var genetalprice = Math.abs($("#gentotal").html());
        $round_numbers = $("#round_numbers").val();
        $noOfDecimalPlaces = $("#noOfDecimalPlaces").val();
        var valueaddeddiscount = $("#valueaddeddiscount").val();
        //extre discount
        //if its calulated before
        var useExtraDiscount = Number($('#useExtraDiscount').val());
        var extraDiscountPlace = Number($('#extraDiscountPlace').val());
        var extraDiscountPer = Number($('#extraDiscountPer').val());
        if (useExtraDiscount == 1 && extraDiscountPer > 0 && extraDiscountPlace == 1) {
            extraDiscountPer = extraDiscountPer / 100;
            var extraDiscountVal = extraDiscountPer * genetalprice;
            //check round number property
            if ($round_numbers == 0) //التقريب لأقرب عدد صحيح
            {
                extraDiscountVal = Math.round(extraDiscountVal);
            } else //التقريب لأقرب رقم
            {
                //netprice = Math.round(netprice * 10) / 10;
                extraDiscountVal = extraDiscountVal.toFixed($noOfDecimalPlaces);
            }

            //
            $('#extraDiscountVal').val(extraDiscountVal);
            $('#extraDiscountVal_h').val(extraDiscountVal);
            genetalprice = genetalprice - extraDiscountVal;
        }




        //  var generaldiscount = Math.abs(document.getElementById("gendis").value);
        var generaldiscount = $("#gendis").val(); //(document.getElementById("gendis").value);
        //  alert('generaldiscount'+generaldiscount)
        var distype = document.getElementById("distype").value;
        //var directDiscount=//document.getElementById("directDiscount").value
        var percentageDiscount = document.getElementById("percentageDiscount").value;
        var directDiscount = (Number(percentageDiscount) / 100) * genetalprice;
        //يوجد خصم للمجموعة ومسموح بتخطى الخصم اذن نجعل الخصم يصل ل 100%
        if (stopDiscountOfTotalControl == 1 && discountOfTotalControlMTGDA == 0) {
            percentageDiscount = 100; //make max discount 100% of bill value not more
            directDiscount = (Number(percentageDiscount) / 100) * genetalprice;
        }
        //alert(directDiscount);
        ;
        //خصم مباشر
        if (distype == 1) {
            // $('#percentageSignDiv').removeClass('input-group');
            $('#percentageSignSpan').addClass('hide');
            $('#percentageValSpan').removeClass('hide');

            ////////////////add by sara////////////////////////////

            //لو الخصم اكبر من المسموح بيه
            if (generaldiscount >= genetalprice || generaldiscount >= directDiscount) {

                if (directDiscount >= genetalprice) {

                    document.getElementById("gendis").value = genetalprice;
                    var generaldiscount = document.getElementById("gendis").value;
                } else {

                    document.getElementById("gendis").value = directDiscount;
                    var generaldiscount = document.getElementById("gendis").value;
                }
            } else {

                document.getElementById("gendis").value = generaldiscount;
                var generaldiscount = document.getElementById("gendis").value;
            }
            ///////////////////////end/////////////////////////////
            var resultdiscount = generaldiscount;
        }
        //خصم نسبة
        else if (distype == 2) {
            $('#percentageSignDiv').addClass('input-group');
            $('#percentageSignSpan').removeClass('hide');
            $('#percentageValSpan').addClass('hide');

            //alert(percentageDiscount)
            ////////////////add by sara////////////////////////////
            if (percentageDiscount > 0) {

                if (Number(generaldiscount) > percentageDiscount) {
                    document.getElementById("gendis").value = percentageDiscount;
                    var generaldiscount = document.getElementById("gendis").value;
                } else {
                    document.getElementById("gendis").value = generaldiscount;
                    var generaldiscount = document.getElementById("gendis").value;
                }
                ///////////////////////end/////////////////////////////

            } else {
                //alert(222);

                var generaldiscount = 0;
                document.getElementById("gendis").value = 0;
            }

            var resultdiscountbefore = Number(generaldiscount) / 100;
            var resultdiscount = resultdiscountbefore * genetalprice;
        }




        if (useExtraDiscount == 1 && extraDiscountPer > 0 && extraDiscountPlace == 0) {
            extraDiscountPer = extraDiscountPer / 100;
            var genetalpriceAfterDiscount = Number(genetalprice - resultdiscount);
            var extraDiscountVal = Number(extraDiscountPer * genetalpriceAfterDiscount);
            //check round number property
            if ($round_numbers == 0) //التقريب لأقرب عدد صحيح
            {
                extraDiscountVal = Math.round(extraDiscountVal);
            } else //التقريب لأقرب رقم
            {
                //netprice = Math.round(netprice * 10) / 10;
                extraDiscountVal = extraDiscountVal.toFixed($noOfDecimalPlaces);
            }

            //
            $('#extraDiscountVal').val(extraDiscountVal);
            $('#extraDiscountVal_h').val(extraDiscountVal);
            resultdiscount = Number(resultdiscount) + Number(extraDiscountVal);
        }


        //var netprice =Number(genetalprice) - Number(resultdiscount);

        if (Number($("#gentotal").html()) > 0) {
            //alert('in if');
            var netprice = Number(genetalprice) - Number(resultdiscount);
        } else {
            var sellbillprice = Number(document.getElementById("sellbillprice").value);
            //alert('sellbillprice'.sellbillprice)
            //alert('in else');
            //alert('igenetalprice'+genetalprice);
            //alert('resultdiscount'+resultdiscount);
            if (sellbillprice > 0) {
                ///alert( -(Number(genetalprice) - Number(resultdiscount)));
                //alert('in if');
                var netprice = -(Number(genetalprice) + Number(resultdiscount));
            } else {
                //alert('in else');
                var netprice = -(Number(genetalprice) - Number(resultdiscount));
            }
        }

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

        }



        //alert( document.getElementById("tax").value);
        //cal taxOfDiscountVal for netprice "total after discount"
        var taxOfDiscountPercentage = Number($('#taxOfDiscountPercentage').val()) / 100;
        var taxOfDiscountVal = taxOfDiscountPercentage * netprice;
        $('#taxOfDiscountVal').val(taxOfDiscountVal.toFixed($noOfDecimalPlaces));
        $('#taxOfDiscountVal_h').val(taxOfDiscountVal.toFixed($noOfDecimalPlaces));
        var mytax = Number(document.getElementById("tax").value) / 100;
        if (valueaddeddiscount == 1) {
            var taxVal = mytax * genetalprice;
        } else {
            var taxVal = mytax * netprice;
        }
        $('#taxVal').val(taxVal.toFixed($noOfDecimalPlacesBillTotal));
        //
        var aftertax = netprice - taxOfDiscountVal + taxVal;
        aftertax = aftertax.toFixed($noOfDecimalPlacesBillTotal);
        if ($('#vatIncludedTotalIfRow').val() != "") {
            aftertax = Number($('#vatIncludedTotalIfRow').val());
        }

        $("#gen2total").html(aftertax);
        document.getElementById("sellbillaftertotalbill").value = aftertax;
        calcProfit();
        //if there is client rather than نقدي
        if ($("#supplier").val() != '-1' && $("#supplier").val() != '-2' && (($("#multiclient").val() == 1 && $("#supplier").val() != '1') || ($("#multiclient").val() == 0 && $("#supplier").val().indexOf("1") != -1))) {
            if (clientType == 1 && !$('#sellbillForm').hasClass('processing') && (TillFinishLoadingCountNeeded == -10 || TillFinishLoadingCountNeeded < generaldiscountUsesCountFlag)) {//nakdi as client type @billsetting
                if (Number(netprice) < 0) {
                    $("#genpay").val(aftertax * -1);
                    $("#genpayvisa").val(0);
                } else {
                    $("#genpay").val(aftertax);
                    $("#genpayvisa").val(0);
                }
            }
            $('#genpay').removeAttr('readonly');
            $('#genpayvisa').removeAttr('readonly');
            //$("#genpay").val(0);
        } else {
            if (Number(netprice) < 0) {
                $("#genpay").val(aftertax * -1);
                $("#genpayvisa").val(0);
            } else {
                $("#genpay").val(aftertax);
                $("#genpayvisa").val(0);
            }
            $('#genpay').attr('readonly', 'readonly');
            //            $('#genpayvisa').attr('readonly', 'readonly');
        }
        $('#delivery').keyup();
    }
    /************************/


    // general pay , calaclution in key up
    /************************/
    $(document).on('blur', "#genpay, #genpayvisa", function () {
        //if there is client rather than نقدي
        if ($("#supplier").val() != '-1' && $("#supplier").val() != '-2' && (($("#multiclient").val() == 1 && $("#supplier").val() != '1') || ($("#multiclient").val() == 0 && $("#supplier").val().indexOf("1") != -1))) {

        } else {//nakdi
            var sellbillaftertotalbill = Math.abs(Number($('#sellbillaftertotalbill').val()));
            if ($(this).attr('id') == "genpayvisa") {
                var genpayvisaPayed = Number($(this).val());
                $('#genpay').val(sellbillaftertotalbill - genpayvisaPayed);

            }
        }
        checkPayed();
        checkthepayed();
        //get the general payed
        thegeneralpayed();
        // calculate the rest of debt
        therestofdebt();
    });
    /************************/


    // calculate the general payed
    /************************/
    thegeneralpayed = function () {
        var netprice = $("#gen2total").html();
        var generalpayed = Number(document.getElementById("genpay").value) + Number(document.getElementById("genpayvisa").value);
        var genetalprice = $("#gentotal").html();
        //alert('netprice'+netprice);
        //alert('generalpayed'+generalpayed);
        //alert('generalpayed'+generalpayed);
        if (Number(genetalprice) < 0) {
            //alert('in if');
            var resultpayed = netprice - (-Number(generalpayed));
        } else {
            //alert('in else');
            var resultpayed = netprice - generalpayed;
        }

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

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

    //calculate the rest of debt
    /************************/
    therestofdebt = function () {
        if (billtype == 0) {
            var generalpayed = Number(document.getElementById("genpay").value) + Number(document.getElementById("genpayvisa").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;
                therestdebt = therestdebt.toFixed($noOfDecimalPlaces);
            }


            $("#gen4total").html(therestdebt);
            //$("#gen4totalinput").val(therestdebt);


            /////////////////////add by sara ////
            document.getElementById("clientdebtafter").value = therestdebt;
        } else if (billtype == 1) {
            var generalpayed = Number(document.getElementById("genpay").value) + Number(document.getElementById("genpayvisa").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;
                therestdebt = therestdebt.toFixed($noOfDecimalPlaces);
            }

            $("#gen4total").html(therestdebt);
            // $("#gen4totalinput").val(therestdebt);

            /////////////////////add by sara ////
            document.getElementById("clientdebtafter").value = therestdebt;
        }
    }
    /************************/

    // calculate general discount
    /***********************/
    $(document).on('keyup', "#gendis, #extraDiscountPer", function () {
        if ($(this).val() > 0 && $('#sellbilltotalbill').val() > 0)
            $('#percentageValSpan').html(parseFloat((($(this).val() / $('#sellbilltotalbill').val()) * 100).toFixed(2)) + '%');
        else
            $('#percentageValSpan').html('0%');
        /////// ahmed taha
        //get the total price of sell and return sell
        if (stopDiscountOfTotalControl == 1 && discountOfTotalControlEditable == 1) {
            totalprice();
        }
        //get the general discount
        thegeneraldiscount();
        checkthepayed();
        //get the general payed
        thegeneralpayed();
        //calculate the rest of debt
        therestofdebt();
    });
    /**********************/

    //action of loading the dropdwonlist with new record
    /***********************/
    // the action will determine later
    $("#suppliernotuse").select2().change(function () {

        var couof = $aw_i;
        for ($noof = 1; $noof < couof; $noof++) {
            $("#productdiv" + $noof).html('<img src="../views/default/images/loader/6.gif" alt="">');
            $('#productdiv' + $noof).load('test.php?itrs=' + $noof + '&id=15', function () {

                $('select').select2();
                $("select").trigger("liszt:updated");
            });
        }
    });
    /***********************/

    //action of supplier dropdownlist
    /**********************/
    function getclientdebtSuccess(data, theselectedvalue) {
        //        data = getValueInTermsOfSelectedCurrency2(data);
        //data is client debt
        //theselectedvalue is supplierid
        $('#divclientdata').html(data)
        setTimeout(function () {
            data = getValueInTermsOfSelectedCurrency($('#hidden_debt_main_curr').val());
            $('#debt').html(data);
            document.getElementById("hidden_debt").value = $('#debt').html();
            //$("#tempclientName").val($("#supplier option[value='" + theselectedvalue + "']").text());
            ;
            if (firstLoadingForClientChange == 1) {//&& manyParcodesFlag == 1
                firstLoadingForClientChange = 0;
            } else {
                let oldTmpName = $('#supplier').select2('data').text;
                let tmpName = oldTmpName.split('-')[1]
                if (tmpName == undefined)
                    tmpName = oldTmpName;
                $("#tempclientName").val(tmpName).change();
            }
            ////////////add by sara//////////////////
            //get the total price of sell
            //selltotalprice(noitr);

            // get the total price of sell and return sell
            totalprice();
            //get the general discount
            thegeneraldiscount();
            checkthepayed();
            //get the general payed
            thegeneralpayed();
            therestofdebt();
            if (theselectedvalue == "1") {
                $('#genpay').attr('readonly', true);
                //                $('#genpayvisa').attr('readonly', true);
            } else {
                $('#genpay').attr('readonly', false);
                $('#genpayvisa').attr('readonly', false);
            }
        }, 0);
    }
    $("#supplier").change(function (e, changePrice, initialSupp_PriceType = '', dontRepeat = '', action = '') {
        $("#divclientdata").html('<img src="../views/default/images/6.gif" alt="">');
        if ($('#initialSupp_Debt').length > 0) {
            $('#hidden_debt_main_curr').val($('#initialSupp_Debt').val());
            getclientdebtSuccess($('#initialSupp_Debt').val(), $('#supplier').val());
            $('#initialSupp_Debt').remove();
        } else {
            $.ajax({
                type: 'GET',
                url: '' + supplierpagename + '?do=getclientdebt&clientid=' + $('#supplier').val() + '',
                async: false,
                success: function (data) {
                    $('#hidden_debt_main_curr').val(data);
                    getclientdebtSuccess(data, theselectedvalue);
                }
            });
        }
        // $("#typeclient").val('').trigger('change');


        //        if ((allowSupplierChange == 1 && $("#supplier").val() == '-2') || $("#supplier").val() == '-2') {
        if (allowSupplierChange == 1 || supplier_id == -2) {
            var suppdata = $('#supplier').select2('data');
            $('#specialDiscount_').val(suppdata.specialDiscount);
            $('#specialDiscountVal_').val(suppdata.specialDiscountVal);
            if ($("#supplier").val() == 1 || ($("#multiclient").val() == 0 && $("#supplier").val().indexOf("1") != -1)) {
                //نقدى
                //يتم دفع قيمة الفاتورة كاملة
                //ولا يستطيع التعديل فى المدفوع
                $('#genpay').val($('#sellbillaftertotalbill').val());
                $('#genpayvisa').val(0);
                $('#genpay').attr('readonly', 'readonly');
                //                $('#genpayvisa').attr('readonly', 'readonly');
            } else {
                if (clientType == 1 && action != "submit" && (TillFinishLoadingCountNeeded == -10 || TillFinishLoadingCountNeeded < generaldiscountUsesCountFlag)) {//nakdi as client type @billsetting
                    $('#genpay').val($('#sellbillaftertotalbill').val());
                    $('#genpayvisa').val(0);
                }
                $('#genpay').removeAttr('readonly');
                $('#genpayvisa').removeAttr('readonly');
            }

            if (Number($("#supplier").val()) > 0) {
                $.ajax({
                    type: 'GET',
                    url: 'sellbillAjaxController.php?do=clientstore&id=' + $("#supplier").val(),
                    success: function (data) {
                        var current_store = Number($('#storeid option:selected').val());
                        var morestore = document.getElementById("morestore").value;

                        //alert(data)
                        data = data.split(',,,,,');
                        $(".clientstore").not('[id^="s2id_"]').find('option').remove().end().append(data[0]);
                        //## choose default store of client @add,@edit , dont change old stores in rows @edit
                        if (morestore == 0) {
                            $('#storeid').val(data[3]);
                            if ($("[name='oldid']").length == 0 || ($("[name='oldid']").length > 0 && pageLoadFlagForStore == 0)) {
                                if (typeof data[3] !== 'undefined' && data[3] !== null) {
                                    $('#storeid').trigger('change');
                                }
                            }
                        } else {
                            if ($("[name='oldid']").length == 0 || ($("[name='oldid']").length > 0 && pageLoadFlagForStore == 0)) {
                                if (typeof data[3] !== 'undefined' && data[3] !== null) {
                                    $('#storeid').val(data[3]).trigger('change');
                                }
                            }
                        }
                        // ## now we are in document ready if ther is store selected choose it or choose first choice
                        if ($("[name='oldid']").length > 0 || (pageLoadFlagForStore == 0 && activateAutoSave == 1) || activateAutoSave == 0) {
                            //storeid: document.getElementById("prstorid"+n).value ,
                            if (morestore == 0) {// store per row
                                $("select[id^='prstorid']").each(function () {
                                    var storeitr = $(this).attr('id').slice(8);
                                    var val = $('#prstorid' + storeitr).select2('data').id;
                                    if (val > 0) {
                                        $("#prstorid" + storeitr).val(val).trigger('change');
                                    } else {
                                        $("#prstorid" + storeitr).val($(".clientstore option:first").val()).trigger('change');
                                    }
                                })
                                $("select[id^='reprstorid']").each(function () {
                                    var storeitr = $(this).attr('id').slice(10);
                                    var val = $('#reprstorid' + storeitr).select2('data').id;
                                    if (val > 0) {
                                        $("#reprstorid" + storeitr).val(val).trigger('change');
                                    } else {
                                        $("#reprstorid" + storeitr).val($(".clientstore option:first").val()).trigger('change');
                                    }
                                })
                            } else if (morestore == 1) {//1 store
                                if (current_store > 0) {
                                    $(".clientstore").val(current_store).trigger('change');
                                } else {
                                    $(".clientstore").val($(".clientstore option:first").val()).trigger('change');
                                }
                            }
                        }
                        pageLoadFlagForStore = 0;
                        $('.clientstoretxt').html(data[1]);
                        $('#userstoreidForClient').val(data[2]);
                        userstoreidForUser = data[3];
                    }
                });
            }
            var theselectedvalue = $(this).val();
            multiclient = $("#multiclient").val();
            //alert( var multiclient);
            //alert('sellbillAjaxController.php?do=clientprice&id='+theselectedvalue);
            if (multiclient == 1) {
                var usePriceTypeOfClient = $('#usePriceTypeOfClient').val();
                if (theselectedvalue != 1 && usePriceTypeOfClient == "1" && changePrice == 'yes') {// && changePrice != 'no') {
                    $.ajax({
                        type: 'GET',
                        url: 'sellbillAjaxController.php?do=clientprice&id=' + theselectedvalue,
                        success: function (data) {

                            //alert(data)
                            if (data > -1) {
                                //جمبه
                                if (data == 0) {
                                    //alert('جملة');
                                    $("#pricetype").select2("data", { id: data, text: 'جملة' });
                                    //alert('جملة');

                                }
                                //تجزئة
                                else if (data == 1) {	//alert('تجزئة');
                                    $("#pricetype").select2("data", { id: data, text: 'تجزئة' });
                                    //alert('تجزئة');
                                }

                                //نصف جمله
                                else if (data == 2) {
                                    //alert('نصف جملة');
                                    $("#pricetype").select2("data", { id: data, text: 'نصف جملة' });
                                    //alert('نصف جملة');

                                }
                                $("#pricetype").change();
                                ;
                            } else {

                                //alert('fff');
                            }

                        }
                    });
                }


                $(".numberinput").forceNumeric();
                if (theselectedvalue == "-2") {
                    var elemposition = $(this).data('position');
                    $("#myModal1").find(".savemodel1").attr('data-position', elemposition);
                    $('#myModal1').modal('show');
                } else {
                    $("#debt").html('<img src="../views/default/images/6.gif" alt="">');
                    //get client data
                    /*it is comming with    do=getclientdata     to optimize time
                     //                $.ajax({
                     //                    type: 'GET',
                     //                    url: '' + supplierpagename + '?do=getclientcommentAZ&clientid=' + theselectedvalue + '',
                     //                    success: function (data) {
                     //
                     //                        $("#commentAZ").html('<img src="../views/default/images/6.gif" alt="">');
                     //                        $('#commentAZ').html(data)
                     //                    }
                     });*/

                    if ($('#showclientdetail').val() == "0" || $('#showCommentAZ').val() == "0") {
                        //it is no need to get if it is hidden ===> so this will optimize time
                        $.ajax({
                            type: 'GET',
                            url: '' + supplierpagename + '?do=getclientdata&clientid=' + theselectedvalue + '',
                            success: function (data) {
                                $("#divclientdata").html('<img src="../views/default/images/6.gif" alt="">');
                                $('#divclientdata').html(data)
                                $('#commentAZ').html($('#tempCommentAz').html());
                                $('#tempCommentAz').remove();
                            }
                        });
                    }
                }
                return false;
            }

        }

    });
    if ($("[name='oldid']").length > 0 || ($('#manyParcodesVal_h').length > 0 && $('#manyParcodesVal_h').val() == 1)) {
        $("#supplier").trigger('change', ['no']);
    } else {
        $("#supplier").trigger('change', ['yes', $('#initialSupp_PriceType').val()]);
    }

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

    // 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) {
        //save product number of unit
        $('#proNum' + thecolnmux).val($('#productunit' + thecolnmux + ' option:selected').data('pu-num'));
        //alert('index'+thecolnmux);
        //thecolnmux=3;
        var totalpricex;
        //## have to consider row discount type too
        var discountrowtype = $("#discountrowtype").val();
        if ($('#prodis' + thecolnmux).is(':visible')) {//means discount is cash , changing to percentage
            discountrowtype = 0;
        } else if ($('#discounttype' + thecolnmux).is(':visible')) {//means discount is percentage , changing to cash
            discountrowtype = 1;
        }
        //##

        var showdiscountrow = $("#showdiscountrow").val();
        var price = Number($("#proprice" + thecolnmux).val());
        var amount = Number($("#pronum" + thecolnmux).val());
        var pricebefore = price * amount;
        //القيمه المباشره
        var discountbefore = Number($("#prodis" + thecolnmux).val());
        //القيمه النسبيه
        var discounttype = $("#discounttype" + thecolnmux).val();
        $noOfDecimalPlaces = $("#noOfDecimalPlaces").val();
        ////////////////add by sara////////////////////////////
        //خصم مباشر
        if (discountrowtype == 0) {

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

            var totalpricex = pricebefore - discountbefore;
            //();
            $("#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);
        } else {

            var totalpricex = pricebefore;
        }
        ///////////////////////end/////////////////////////////

        var prosellDiscountPer = Number($('#prosellDiscountPer' + thecolnmux).val()) / 100;
        var prosellDiscountPerType = Number($('#prosellDiscountPerType' + thecolnmux).val());
        $PercentageValue = prosellDiscountPer * totalpricex;
        if (prosellDiscountPerType == 0) {//+
            totalpricex += $PercentageValue;
        } else if (prosellDiscountPerType == 1) {//-
            totalpricex -= $PercentageValue;
        }
        $('#prosellDiscountVal' + thecolnmux).val($PercentageValue);

        //alert('step'+2);
        $round_numbers = round_numbersForRows;//$("#round_numbers").val();
        $noOfDecimalPlaces = noOfDecimalPlacesForRows;//$("#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 == 114)//f3  //114 = r not f3 stop this code//fatma
        //        {
        //            //            $("#gendis").val("0");
        //            //            $("#saveAndNew").click();
        //            //            return false;
        //        }
        //        if (e.which == 113)//f2
        //        {
        //            $("#gendis").val("0");
        //            if (!$('#sellbillForm').hasClass('processing')) {//to stop multi submitting
        //                $('#sellbillForm').addClass('processing');
        //                $("#supplier").change();
        //                $('#sellbillForm').submit();
        //            }
        //            return false;
        //        }

        if (e.which == 13) {

            //add the new row with itration and with all propperties
            addrow($aw_i, $tabindexnum);
            /*$("#gendis").focus();
             //here to make focus in dropdown list
             $('.chzn-single').focus(function (e) {
             e.preventDefault();
             });
             $('#product' + $aw_i + '_chzn a.chzn-single').focus();
             $('#product' + $aw_i + '_chzn a.chzn-single').select();*/

            var parcodeType = document.getElementById("parcodeType" + $aw_i).value;
            var settingQuantitiyFocus = document.getElementById("settingQuantitiyFocus").value;
            if (settingQuantitiyFocus == 0 && parcodeType != "serialnumber") {
                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').select2();
            //$.getScript('../views/default/js/head_scripts.js');

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

    //to use enter and click to submit the form
    /*******************************/
    //    $("#billsure").keypress(function(e) {
    //        if (e.which == 13) {
    //
    //            if (!$('#sellbillForm').hasClass('processing')) {//to stop multi submitting
    //                        $('#sellbillForm').addClass('processing');
    //                        $("#supplier").change();
    //                        $('#sellbillForm').submit();
    //                    }
    //        }
    //    });
    /******************************/

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

        var code = (e.keyCode ? e.keyCode : e.which);
        var elementId = e.srcElement.id;
        //to stop the submit of the form
        if (elementId == "manyParcodes") {
            return true;
        }
        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 sell
                selltotalprice($remitr);
                // get the total price of sell and return sell
                totalprice();
                //get the general discount
                thegeneraldiscount();
                checkthepayed();
                //get the general payed
                thegeneralpayed();
                // calculate the rest of debt
                therestofdebt();
            }
            return false;
        }
    });
    /*******************************/

    /////////////////////add by sara////////////////
    checkthepayed = function () {

        var netpriceto = Math.abs($("#gen2total").html()); //الصافى
        var generalpayedto = Math.abs(Number(document.getElementById("genpay").value) + Number(document.getElementById("genpayvisa").value)); //المدفوع
        var generaldiscountto = Math.abs(document.getElementById("gendis").value); //الخصم
        var genetalpriceto = netpriceto; // Math.abs($("#gentotal").html());//الاجمالى العام

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

            //badawy
            if (Number(generalpayedto) > Number(genetalpriceto)) {
                //  document.getElementById("genpay").value = genetalpriceto;
            }
        }
    }
    /*******************************/

    //action of store dropdownlist
    /**********************/
    $("#storeid").select2().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');
        } else {
            $(".clientstore").val($(".clientstore option:first").val()).trigger('change.select2');
        }

        // var theselectedvalue = $(this).val();


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

        //if($remitr >= 2)
        //{
        // for($j=2 ; $j <= $remitr ; $j++)
        //{
        // $("#remove"+$j).parent().parent().parent().remove();
        // }
        //}

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

        //document.getElementById("proprice1").value=0;
        //document.getElementById("pronum1").value=1;
        //document.getElementById("prodis1").value=0;
        //document.getElementById("genpay").value=0;
        //document.getElementById("gendis").value=0;
        //$("#gen3total").html(0);

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

        // 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();

        // $("#productdiv1").html('<img src="../views/default/images/loader/6.gif" alt="">');
        //$('#productdiv1').load(''+storepagename+'?do=getproduct&storeid='+theselectedvalue+'',function() {

        // $("#addrowcreated").empty();
        // $("#productdiv1 option").clone().appendTo("#addrowcreated");



        // //$('select').chosen();

        //});

    });
    /**********************/

    /////////////////////End////////////////

    //using esc button to do delete the row
    /********************************/
    /*$(function(){
     $('a.anything').escape(function() {

     // 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();

     //get the general payed
     thegeneralpayed();

     // calculate the rest of debt
     therestofdebt();

     });
     });*/
    /*************************************/

    $(document).on('click', ".addManyParcodes", function () {
        $('#addManyParcodesType').val($(this).data('type')); //sell or ret
        $('#myModalManyParcodes').modal('show');
        setTimeout(function () {
            $('#manyParcodes').focus();
        }, 800);
    });
    $(document).on('click', "#doAddManyParcodes", function () {
        if ($('#manyParcodes').val() != '') {
            var billnameid = $('#billnameid').val();
            $('#manyParcodesSupplier').val($('#supplier').val());
            $('#manyParcodesPriceType').val($('#pricetype').val());
            $('#manyParcodesStoreid').val($('#storeid').val());
            $('#manyParcodesSellerid').val($('#sellerid').val());
            $('#manyParcodesSaveid').val($('#saveid').val());
            $('#addManyParcodebillnameid').val(billnameid);
            $('#addManyParcodebilloperationid').val($('#billoperationid').val());
            $('#addManyParcodebillCurrencyId').val($('#currencyId').val());
            $('#addManyParcodebillCFactor').val($('#cFactor').val());
            $('#addManyParcodebillOtherCFactor').val($('#otherCFactor').val());
            $('#addManyParcodeobgyBillType').val($('[name="obgyBillType"]:checked').val());
            $('#addManyParcodeknownwayId').val($('#know_way').val());
            $('#manyParcodesForm').submit();
        } else {
            alert('عفوا لم تدخل اى باركود');
        }

    });
    $(document).on('click', ".proDetails", function () {
        var pro = $(this).data('pro');
        var id = $('#' + pro).val();
        if (Number($('#' + pro).val()) > 0 || $('#' + pro).val().indexOf("hasSizeColor") == 0) {
            $.ajax({
                url: 'productController.php?do=editAjax&id=' + id + '&lastSellNote=1',
                success: function (data) {
                    $('#productDetailsForm').html(data);
                    $('#productDetailsModal').modal('show')

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

    setTimeout(function () {//dely it till customeditsellbill fill data to prevent making gendis = 0 @edit
        $("#currencyId").trigger('change', ['atPageLoading']);
    })

});

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

//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) {
    $('#currencyText').text($('#currencyId').select2('data').text);
    if ($(this).attr('id') != "cFactor" && $(this).attr('id') != "otherCFactor" && (callingAtWhichEvent != 'atPageLoading' || $('#cFactor').val() == "" || $('#otherCFactor').val() == "")) {
        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) {
        if (callingAtWhichEvent == 'atPageLoading') {
            oldCFactor = 1;// by default at loading its valu =
        }
        $("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(5));
            $(this).val(buyPriceInNewCurr).keyup();
        });
        $("input[id^='returnproprice']").each(function () {
            var itr = Number($(this).attr('id').slice(14));
            var BuyPrice = Number($(this).val());
            var buyPriceInNewCurr = (BuyPrice * cfactor) / oldCFactor;
            buyPriceInNewCurr = Number(buyPriceInNewCurr.toFixed(5));
            $(this).val(buyPriceInNewCurr).keyup();
        });
    }
    setTimeout(function () {
        if (callingAtWhichEvent != 'atPageLoading')
            getclientdebtSuccess($('#debt').html(), $('#supplier').val())
        //finally
        oldCFactor = cfactor;
        //populateDebtAfter();
    })


});

//##############################################################################
//change price of product from main curr to slected curr val
function getValueInTermsOfSelectedCurrency(val) {
    var cfactor = $('#cFactor').val();
    //    if (cfactor == '') {// as value may not exist till page load done
    //        cfactor = $('#currencyId').select2("data").element[0].attributes['data-cfactor'].value;
    //    }
    val = Number((val * cfactor).toFixed(5));
    return val;
}
function getValueInTermsOfSelectedCurrency2(val) {
    //affect existing prices of products
    var cfactor = $('#cFactor').val();
    //    if (cfactor == '') {// as value may not exist till page load done
    //        cfactor = $('#currencyId').select2("data").element[0].attributes['data-cfactor'].value;
    //    }
    if (oldCFactor != 0) {
        val = (val * cfactor) / oldCFactor;
        val = Number(val.toFixed(5));
    } else {
        val = Number((val * cfactor).toFixed(5));
    }
    return val;
}

function checkquantity(i, e) {
    //alert(i);
    //alert(e);
    //var currentQuantity= Number(document.getElementById("quantity"+i).value);
    //var quantity= Number(document.getElementById("pronum"+i).value);

    //if(quantity > currentQuantity)
    //{
    //document.getElementById("pronum"+i).value=currentQuantity;
    //}
    var maxProductQTY = $('#productQty' + i).val(); //عدد المنتجات في سيريال معين
    var parcodeType = $('#parcodeType' + i).val();
    var currentQTY = $('#pronum' + i).val();
    //alert('currentQTY'+currentQTY);

    if (maxProductQTY == 'undefined')//في حالة إن الرقم باركود مش سيريال
    {
    } else if (maxProductQTY != 'undefined' && Number(currentQTY) < Number(maxProductQTY) && parcodeType == "serialnumber") {
        //alert("<");
        var noitr = document.getElementById("hidden_itr").value;
        // get the total of product
        calcuproduct(i);
        //get the total price of sell
        selltotalprice(noitr);
        // get the total price of sell and return sell
        totalprice();
        //get the general discount
        thegeneraldiscount();
        checkthepayed();
        //get the general payed
        thegeneralpayed();
        // calculate the rest of debt
        therestofdebt();
    } else if (maxProductQTY != 'undefined' && Number(currentQTY) > Number(maxProductQTY) && parcodeType == "serialnumber") {
        //$('#pronum' + i).val(maxProductQTY);
        //alert("لا يمكن بيع أكثر من " + maxProductQTY + " قطع لأنها مرتبطة بسيريال واحد");
        alert("احترس من فضلك انت تبيع اكثر من الكمية المتاحة فى هذا السيريال وهى " + maxProductQTY + "");
    }

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

}


function getunitprice(n) {
    //here  will get the price for every product
    //the selected value in drop down list
    var theselectedvalue = document.getElementById("productunit" + n).value;
    if (theselectedvalue != "") {
        var pricetype = document.getElementById("pricetypepro" + n).value//pricetype
        var productid = document.getElementById("product" + n).value;
        //var storeid = document.getElementById("storeid").value;
        var supplier = document.getElementById("supplier").value;
        var priceupdate = document.getElementById("priceupdate").value;
        var x = $("#parcode" + n).attr("tabindex");
        //using the load method to load the price
        //$("#propricechange" + n).html('<img src="../views/default/images/loader/6.gif" alt="">');


        $('#propricechange' + n).load('' + productpricepagename + '?do=getpriceByOnlyProduct&itrs=' + n + '&tabindex=' + x + '&productunit=' + theselectedvalue + '&productid=' + productid + '&pricetype=' + pricetype + '&clientid=' + 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");
            }


            if (priceupdate == 0) {
                //alert(0);
                $('#proprice' + n).prop('readonly', true);
                $('#hidden_prototal' + n).prop('readonly', true);
            } else {
                //alert(1);
                $('#proprice' + n).prop('readonly', false);
                $('#hidden_prototal' + n).prop('readonly', false);
            }
            //--fatma -last discount
            if ($("#lastClientDisVal" + n).length > 0 && Number($("#lastClientDisVal" + n).val() > 0)) {
                $('#prodis' + n).val($("#lastClientDisVal" + n).val());
                $('#discounttype' + n).val($("#lastClientDisPer" + n).val());
                $('#prodis' + n).css('background-color', '#b7dfa4');
                $('#discounttype' + n).css('background-color', '#b7dfa4');
            } else {
                $('#prodis' + n).val(0);
                $('#discounttype' + n).val(0);
                $('#prodis' + n).css('background-color', '#fff');
                $('#discounttype' + n).css('background-color', '#fff');
            }
            //----

            //check if sellprice less than buyprice
            $("#proprice" + n).change();
            //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 sell
            selltotalprice(noitr);
            // get the total price of sell and return sell
            totalprice();
            //get the general discount
            thegeneraldiscount();
            checkthepayed();
            //get the general payed
            thegeneralpayed();
            // calculate the rest of debt
            therestofdebt();
            //load the jquery checker for number only
            // $.getScript('../views/default/js/head_scripts.js');
        });
    }
}


function getproductbyParcode(e, value, n) {
    //\s means "one space", and \s+ means "one or more spaces".
    value = value.replace(/\s+/g, ''); //\s is the regex for "whitespace", and g is the "global" flag, meaning match ALL \s (whitespaces).
    var pricetype = document.getElementById("pricetypepro" + n).value//pricetype
    var storeid = document.getElementById("prstorid" + n).value//pricetype
    var supplier = document.getElementById("supplier").value;
    $previousPriceStatus = $('#previousPriceStatus').val();
    if ($previousPriceStatus == 1)//don't show previous product price
    {
        supplier = "";
    }

    var code = (e.keyCode ? e.keyCode : e.which);
    //to stop the submit of the form
    if (e.which == 13 && value != "") {
        // var storeid = document.getElementById("storeid").value;
        // if(storeid != "-1")
        // {
        var usedParcode = Number($('#usedParcode').val());
        var billnameid = $('#billnameid').val();
        if (usedParcode == 1) {
            value = value.replace("ه", "i"); //this replacement is for parcode reader
            value = value.replace("÷", "i"); //this replacement is for parcode reader
            value = value.replace("/", "i"); //this replacement is for parcode reader
            value = value.replace("I", "i"); //this replacement is for parcode reader
        } else {
            value = value;
        }
        //alert(value.charAt(0));
        $.ajax({
            url: 'sellbillAjaxController.php?do=getproductNamebyOnlyParcode&parcode=' + value + '&billnameid=' + billnameid + '&storeid=' + storeid,
            success: function (data) {

                var response = $.parseJSON(data);
                //$("#product" + n).select2('val', ['' + response.id + ':' + response.text + ''], true);
                $("#product" + n).select2('data', {
                    id: response.id, text: response.text
                    , isProUnitParcode: response.isProUnitParcode
                    , productunitid: response.productunitid
                    , unitid: response.unitid
                    , proUnitSellAllPrice: response.proUnitSellAllPrice
                    , proUnitSellHalfPrice: response.proUnitSellHalfPrice
                    , proUnitSellUnitPrice: response.proUnitSellUnitPrice
                    , userEnteredParcode: value
                    , productquantity: response.productQty
                    , isService: response.isService
                    , selldiscountpercent: response.selldiscountpercent
                    , sellpercenttype: response.sellpercenttype
                }, false);
                $("#parcodeType" + n).val(response.parcodeType);
                $("#productQty" + n).val(response.productQty);
                $("#productserailid" + n).val(response.productserailid);
                if (response.chassisNo && response.motorNo) {
                    $("#comment" + n).val("رقم الشاسيه	 : " + response.chassisNo + " <br/> رقم الموتور : " + response.motorNo + " <br/> اللون : " + response.theColor + "");
                } else {
                    $("#comment" + n).val("");
                }
                //---fatma
                var useParcodeBalance = response.useParcodeBalance;
                var WeightPricePart = response.WeightPricePart;
                var posType = response.posType;
                var parcodeBalance_data = useParcodeBalance + "*" + WeightPricePart + "*" + posType;
                if ($('#parcodeBalance_data_hidden' + n).length > 0) {
                    $('#parcodeBalance_data_hidden' + n).val(parcodeBalance_data);
                } else {
                    $('#pronum' + n).closest('td').append('<input type="hidden" name="parcodeBalance_data_hidden' + n + '" id="parcodeBalance_data_hidden' + n + '" value="' + parcodeBalance_data + '" />');
                }
                //----

                var productid = document.getElementById("product" + n).value;
                if (productid != "" && productid != "null" && productid != null && productid != "-1") {
                    checkForRepeatedProducts(n, 0);
                    //using the load method to load the price
                    // $("#productunitdiv" + n).html('<img src="../views/default/images/loader/6.gif" alt="">');

                    //////////////////////////////////////////////////
                    var productParcode = $("#parcode" + n).val();
                    ///load unit , parcode, and price
                    $.ajax({
                        url: '' + productpricepagename + '?do=getunit&itrs=' + n + '&tabindex=' + $tabindexnum + '&productid=' + productid + '&pricetype=' + pricetype + '&clientid=' + supplier + '&comingproserial=1&parcode=' + productParcode + '&billnameid=' + $('#billnameid').val(),
                        type: "get",
                        success: function (data) {
                            var response = $.parseJSON(data);
                            //populate unit
                            $('#productunitdiv' + n).html(response.unitString);
                            //  $("#addunit").empty();

                            $("#productunitdiv" + n + " option").clone().appendTo("#addunit");
                            //maximun product quantity
                            $("#productQty" + n).val(response.productQty);
                            //populate buy price
                            $('#propricechange' + n).html(response.priceString);
                            $('#catdis' + n).val($('#selldiscount' + n).val());
                            $('#pricebeforcatdis' + n).val(Number($('#selldiscount' + n).val()) + Number($('#proprice' + n).val()));
                            sumProDis();

                            //--fatma
                            if ($('#parcodeBalance_data_hidden' + n).length > 0) {
                                var parcodeBalance_data = $('#parcodeBalance_data_hidden' + n).val();
                                parcodeBalance_data = parcodeBalance_data.split('*');
                                var useParcodeBalance = parcodeBalance_data[0];
                                var WeightPricePart = parcodeBalance_data[1];
                                var posType = parcodeBalance_data[2];
                                if (useParcodeBalance == 1 && posType == 1) {
                                    $('#proprice' + n).val(WeightPricePart);
                                    $('#pronum' + n).val(1);
                                }
                            }
                            //change price of product from main curr to slected curr val
                            //$('#proprice' + n).val(getValueInTermsOfSelectedCurrency($('#proprice' + n).val()));

                            $("#parcodeType" + n).val(response.parcodeType);
                            $("#productQty" + n).val(response.productQty);
                            $("#productserailid" + n).val(response.productserailid);
                            //----
                            var productData = $("#product" + n).select2('data');
                            $('#prosellDiscountPer' + n).val(productData.selldiscountpercent);
                            $('#prosellDiscountPer_span' + n).html(productData.selldiscountpercent);
                            $('#prosellDiscountPerType' + n).val(productData.sellpercenttype);
                            var prosellDiscountPerTypeSpanTxt = (productData.sellpercenttype == 0) ? 'ض' : 'خ';
                            $('#prosellDiscountPerTypeSpan' + n).html(prosellDiscountPerTypeSpanTxt);
                            //--fatma -last discount
                            if ($("#lastClientDisVal" + n).length > 0 && Number($("#lastClientDisVal" + n).val() > 0)) {
                                $('#prodis' + n).val($("#lastClientDisVal" + n).val());
                                $('#discounttype' + n).val($("#lastClientDisPer" + n).val());
                                $('#prodis' + n).css('background-color', '#b7dfa4');
                                $('#discounttype' + n).css('background-color', '#b7dfa4');
                            } else {
                                $('#prodis' + n).val(0);
                                $('#discounttype' + n).val(0);
                                $('#prodis' + n).css('background-color', '#fff');
                                $('#discounttype' + n).css('background-color', '#fff');
                            }
                            //----

                            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 priceupdate = document.getElementById("priceupdate").value;
                            if (priceupdate == 0) {
                                //alert(0);
                                $('#proprice' + n).prop('readonly', true);
                                $('#hidden_prototal' + n).prop('readonly', true);
                            } else {
                                //alert(1);
                                $('#proprice' + n).prop('readonly', false);
                                $('#hidden_prototal' + n).prop('readonly', false);
                            }
                            $('#productparcode' + n).html(response.parcodeString);
                            var parcodeType = document.getElementById("parcodeType" + n).value;
                            if (parcodeType == "serialnumber") {

                                $('#pronum' + n).val(1);
                                //$('#pronum' + n).attr('readonly', true);
                            } else {

                                $('#pronum' + n).attr('readonly', false);
                            }

                            //here all code that will happend with loading contants
                            //the number of rows of products
                            var noitr = document.getElementById("hidden_itr").value;
                            document.getElementById("pronum" + n).value = 1;
                            document.getElementById("prodis" + n).value = 0;
                            if (useParcodeBalance == 1 && posType == 0) {
                                $('#pronum' + n).val(WeightPricePart);
                            } else {
                                $('#pronum' + n).val(1);
                            }

                            var productData = $("#product" + n).select2('data');
                            if (productData.isProUnitParcode == 1) {
                                $('#productunit' + n).val(productData.productunitid);
                                switch (Number($('#pricetypepro' + n).val())) {
                                    case 0:
                                        $('#proprice' + n).val(productData.proUnitSellAllPrice);
                                        break;
                                    case 1:
                                        $('#proprice' + n).val(productData.proUnitSellUnitPrice);
                                        break;
                                    case 2:
                                        $('#proprice' + n).val(productData.proUnitSellHalfPrice);
                                        break;
                                    default:
                                        $('#proprice' + n).val(productData.proUnitSellAllPrice);
                                        break;
                                }
                            }
                            $('#prosellDiscountPer' + n).val(productData.selldiscountpercent);
                            $('#prosellDiscountPer_span' + n).html(productData.selldiscountpercent);
                            $('#prosellDiscountPerType' + n).val(productData.sellpercenttype);
                            var prosellDiscountPerTypeSpanTxt = (productData.sellpercenttype == 0) ? 'ض' : 'خ';
                            $('#prosellDiscountPerTypeSpan' + n).html(prosellDiscountPerTypeSpanTxt);
                            //change price of product from main curr to slected curr val
                            $('#proprice' + n).val(getValueInTermsOfSelectedCurrency($('#proprice' + n).val()));
                            //check if sellprice less than buyprice
                            $("#proprice" + n).change();

                            //to calculate the price and amount with discount
                            calcuproduct(n);
                            //get the total price of sell
                            selltotalprice(noitr);
                            // get the total price of sell and return sell
                            totalprice();
                            //get the general discount
                            thegeneraldiscount();
                            checkthepayed();
                            //get the general payed
                            thegeneralpayed();
                            // calculate the rest of debt
                            therestofdebt();
                            document.getElementById("hiddenpricetype").value = document.getElementById("pricetype").value;
                            $('select').select2();
                            var settingQuantitiyFocus = document.getElementById("settingQuantitiyFocus").value;
                            if ((Number($aw_i) - Number(n)) == 1) {
                                $("#addunit").empty();
                                addrow($aw_i, $tabindexnum);
                                if (settingQuantitiyFocus == 0 && parcodeType != "serialnumber") {
                                    $("#pronum" + n).focus();
                                    $("#pronum" + n).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++;
                            } else {
                                if (settingQuantitiyFocus == 0 && parcodeType != "serialnumber") {
                                    $("#pronum" + n).focus();
                                    $("#pronum" + n).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');
                                    }
                                }
                            }

                            var settingQuantityAlert = document.getElementById('settingQuantityAlert').value;
                            if (settingQuantityAlert == 0) {
                                //var storeid = $("#storeid").val();
                                var morestore = document.getElementById("morestore").value;

                                var storeid;
                                if (morestore == 0) {
                                    storeid = $("#prstorid" + n).val();
                                } else {
                                    storeid = $("#storeid").val();
                                }

                                $.ajax({
                                    type: 'POST',
                                    url: '' + productpricepagename + '?do=getProductQuantity&productid=' + productid + '&storeid=' + storeid,
                                    success: function (data) {
                                        if (data <= 0) {
                                            $("#errorquantity").html(data);
                                            $('#storemodel').modal('show');
                                            // $('#storenegative').val(0);
                                        }
                                    }
                                });
                            }

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

                }
            }
        });
        // }
    }
}


$(document).on('click','.getProByBarcode',function(){
    let barItr = $(this).data('itr');
    getProByBarcode($('#parcode'+barItr).val(),barItr);
});

function getProByBarcode(value, n) {
    //\s means "one space", and \s+ means "one or more spaces".
    value = value.replace(/\s+/g, ''); //\s is the regex for "whitespace", and g is the "global" flag, meaning match ALL \s (whitespaces).
    var pricetype = document.getElementById("pricetypepro" + n).value//pricetype
    var storeid = document.getElementById("prstorid" + n).value//pricetype
    var supplier = document.getElementById("supplier").value;
    $previousPriceStatus = $('#previousPriceStatus').val();
    if ($previousPriceStatus == 1)//don't show previous product price
    {
        supplier = "";
    }
    var usedParcode = Number($('#usedParcode').val());
    var billnameid = $('#billnameid').val();
    if (usedParcode == 1) {
        value = value.replace("ه", "i"); //this replacement is for parcode reader
        value = value.replace("÷", "i"); //this replacement is for parcode reader
        value = value.replace("/", "i"); //this replacement is for parcode reader
        value = value.replace("I", "i"); //this replacement is for parcode reader
    } else {
        value = value;
    }
    //alert(value.charAt(0));
    $.ajax({
        url: 'sellbillAjaxController.php?do=getproductNamebyOnlyParcode&parcode=' + value + '&billnameid=' + billnameid + '&storeid=' + storeid,
        success: function (data) {
            var response = $.parseJSON(data);
            $("#product" + n).select2('data', {
                id: response.id, text: response.text
                , isProUnitParcode: response.isProUnitParcode
                , productunitid: response.productunitid
                , unitid: response.unitid
                , proUnitSellAllPrice: response.proUnitSellAllPrice
                , proUnitSellHalfPrice: response.proUnitSellHalfPrice
                , proUnitSellUnitPrice: response.proUnitSellUnitPrice
                , userEnteredParcode: value
                , productquantity: response.productQty
                , isService: response.isService
                , selldiscountpercent: response.selldiscountpercent
                , sellpercenttype: response.sellpercenttype
            }, false);
            $("#parcodeType" + n).val(response.parcodeType);
            $("#productQty" + n).val(response.productQty);
            $("#productserailid" + n).val(response.productserailid);
            if (response.chassisNo && response.motorNo) {
                $("#comment" + n).val("رقم الشاسيه	 : " + response.chassisNo + " <br/> رقم الموتور : " + response.motorNo + " <br/> اللون : " + response.theColor + "");
            } else {
                $("#comment" + n).val("");
            }
            //---fatma
            var useParcodeBalance = response.useParcodeBalance;
            var WeightPricePart = response.WeightPricePart;
            var posType = response.posType;
            var parcodeBalance_data = useParcodeBalance + "*" + WeightPricePart + "*" + posType;
            if ($('#parcodeBalance_data_hidden' + n).length > 0) {
                $('#parcodeBalance_data_hidden' + n).val(parcodeBalance_data);
            } else {
                $('#pronum' + n).closest('td').append('<input type="hidden" name="parcodeBalance_data_hidden' + n + '" id="parcodeBalance_data_hidden' + n + '" value="' + parcodeBalance_data + '" />');
            }
            //----
            var productid = document.getElementById("product" + n).value;
            if (productid != "" && productid != "null" && productid != null && productid != "-1") {
                checkForRepeatedProducts(n, 0);
                //using the load method to load the price
                //////////////////////////////////////////////////
                var productParcode = $("#parcode" + n).val();
                ///load unit , parcode, and price
                $.ajax({
                    url: '' + productpricepagename + '?do=getunit&itrs=' + n + '&tabindex=' + $tabindexnum + '&productid=' + productid + '&pricetype=' + pricetype + '&clientid=' + supplier + '&comingproserial=1&parcode=' + productParcode + '&billnameid=' + $('#billnameid').val(),
                    type: "get",
                    success: function (data) {
                        var response = $.parseJSON(data);
                        //populate unit
                        $('#productunitdiv' + n).html(response.unitString);
                        $("#productunitdiv" + n + " option").clone().appendTo("#addunit");
                        //maximun product quantity
                        $("#productQty" + n).val(response.productQty);
                        //populate buy price
                        $('#propricechange' + n).html(response.priceString);
                        $('#catdis' + n).val($('#selldiscount' + n).val());
                        $('#pricebeforcatdis' + n).val(Number($('#selldiscount' + n).val()) + Number($('#proprice' + n).val()));
                        sumProDis();
                        //--fatma
                        if ($('#parcodeBalance_data_hidden' + n).length > 0) {
                            var parcodeBalance_data = $('#parcodeBalance_data_hidden' + n).val();
                            parcodeBalance_data = parcodeBalance_data.split('*');
                            var useParcodeBalance = parcodeBalance_data[0];
                            var WeightPricePart = parcodeBalance_data[1];
                            var posType = parcodeBalance_data[2];
                            if (useParcodeBalance == 1 && posType == 1) {
                                $('#proprice' + n).val(WeightPricePart);
                                $('#pronum' + n).val(1);
                            }
                        }
                        //change price of product from main curr to slected curr val
                        $("#parcodeType" + n).val(response.parcodeType);
                        $("#productQty" + n).val(response.productQty);
                        $("#productserailid" + n).val(response.productserailid);
                        //----
                        var productData = $("#product" + n).select2('data');
                        $('#prosellDiscountPer' + n).val(productData.selldiscountpercent);
                        $('#prosellDiscountPer_span' + n).html(productData.selldiscountpercent);
                        $('#prosellDiscountPerType' + n).val(productData.sellpercenttype);
                        var prosellDiscountPerTypeSpanTxt = (productData.sellpercenttype == 0) ? 'ض' : 'خ';
                        $('#prosellDiscountPerTypeSpan' + n).html(prosellDiscountPerTypeSpanTxt);
                        //--fatma -last discount
                        if ($("#lastClientDisVal" + n).length > 0 && Number($("#lastClientDisVal" + n).val() > 0)) {
                            $('#prodis' + n).val($("#lastClientDisVal" + n).val());
                            $('#discounttype' + n).val($("#lastClientDisPer" + n).val());
                            $('#prodis' + n).css('background-color', '#b7dfa4');
                            $('#discounttype' + n).css('background-color', '#b7dfa4');
                        } else {
                            $('#prodis' + n).val(0);
                            $('#discounttype' + n).val(0);
                            $('#prodis' + n).css('background-color', '#fff');
                            $('#discounttype' + n).css('background-color', '#fff');
                        }
                        //----
                        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 priceupdate = document.getElementById("priceupdate").value;
                        if (priceupdate == 0) {
                            //alert(0);
                            $('#proprice' + n).prop('readonly', true);
                            $('#hidden_prototal' + n).prop('readonly', true);
                        } else {
                            //alert(1);
                            $('#proprice' + n).prop('readonly', false);
                            $('#hidden_prototal' + n).prop('readonly', false);
                        }
                        $('#productparcode' + n).html(response.parcodeString);
                        var parcodeType = document.getElementById("parcodeType" + n).value;
                        if (parcodeType == "serialnumber") {
                            $('#pronum' + n).val(1);
                            //$('#pronum' + n).attr('readonly', true);
                        } else {
                            $('#pronum' + n).attr('readonly', false);
                        }
                        //here all code that will happend with loading contants
                        //the number of rows of products
                        var noitr = document.getElementById("hidden_itr").value;
                        document.getElementById("pronum" + n).value = 1;
                        document.getElementById("prodis" + n).value = 0;
                        if (useParcodeBalance == 1 && posType == 0) {
                            $('#pronum' + n).val(WeightPricePart);
                        } else {
                            $('#pronum' + n).val(1);
                        }

                        var productData = $("#product" + n).select2('data');
                        if (productData.isProUnitParcode == 1) {
                            $('#productunit' + n).val(productData.productunitid);
                            switch (Number($('#pricetypepro' + n).val())) {
                                case 0:
                                    $('#proprice' + n).val(productData.proUnitSellAllPrice);
                                    break;
                                case 1:
                                    $('#proprice' + n).val(productData.proUnitSellUnitPrice);
                                    break;
                                case 2:
                                    $('#proprice' + n).val(productData.proUnitSellHalfPrice);
                                    break;
                                default:
                                    $('#proprice' + n).val(productData.proUnitSellAllPrice);
                                    break;
                            }
                        }
                        $('#prosellDiscountPer' + n).val(productData.selldiscountpercent);
                        $('#prosellDiscountPer_span' + n).html(productData.selldiscountpercent);
                        $('#prosellDiscountPerType' + n).val(productData.sellpercenttype);
                        var prosellDiscountPerTypeSpanTxt = (productData.sellpercenttype == 0) ? 'ض' : 'خ';
                        $('#prosellDiscountPerTypeSpan' + n).html(prosellDiscountPerTypeSpanTxt);
                        //change price of product from main curr to slected curr val
                        $('#proprice' + n).val(getValueInTermsOfSelectedCurrency($('#proprice' + n).val()));
                        //check if sellprice less than buyprice
                        $("#proprice" + n).change();
                            
                        //to calculate the price and amount with discount
                        calcuproduct(n);
                        //get the total price of sell
                        selltotalprice(noitr);
                        // get the total price of sell and return sell
                        totalprice();
                        //get the general discount
                        thegeneraldiscount();
                        checkthepayed();
                        //get the general payed
                        thegeneralpayed();
                        // calculate the rest of debt
                        therestofdebt();
                        document.getElementById("hiddenpricetype").value = document.getElementById("pricetype").value;
                        $('select').select2();
                        var settingQuantitiyFocus = document.getElementById("settingQuantitiyFocus").value;
                        if ((Number($aw_i) - Number(n)) == 1) {
                            $("#addunit").empty();
                            addrow($aw_i, $tabindexnum);
                            if (settingQuantitiyFocus == 0 && parcodeType != "serialnumber") {
                                $("#pronum" + n).focus();
                                $("#pronum" + n).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++;
                        } else {
                            if (settingQuantitiyFocus == 0 && parcodeType != "serialnumber") {
                                $("#pronum" + n).focus();
                                $("#pronum" + n).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');
                                }
                            }
                        }

                        var settingQuantityAlert = document.getElementById('settingQuantityAlert').value;
                        if (settingQuantityAlert == 0) {
                            //var storeid = $("#storeid").val();
                            var morestore = document.getElementById("morestore").value;

                            var storeid;
                            if (morestore == 0) {
                                storeid = $("#prstorid" + n).val();
                            } else {
                                storeid = $("#storeid").val();
                            }

                            $.ajax({
                                type: 'POST',
                                url: '' + productpricepagename + '?do=getProductQuantity&productid=' + productid + '&storeid=' + storeid,
                                success: function (data) {
                                    if (data <= 0) {
                                        $("#errorquantity").html(data);
                                        $('#storemodel').modal('show');
                                    }
                                }
                            });
                        }
                        $('select').select2();
                    },
                    error: function () {
                        alert("لقد حدث خطأ أثناء إجراء العملية");
                    }
                });
                //////////////////////////////////////////////////
            }
        }
    });
}

function checkdisValue() {

    var noitr = document.getElementById("hidden_itr").value;
    //get the total price of sell
    selltotalprice(noitr);
    // get the total price of sell and return sell
    if (stopDiscountOfTotalControl == 1 && discountOfTotalControlEditable == 1) {
        totalprice();
    }
    //get the general discount
    thegeneraldiscount();
    checkthepayed();
    //get the general payed
    thegeneralpayed();
    // calculate the rest of debt
    therestofdebt();
    //##
    if ($('#distype').val() == 1) {
        // $('#percentageSignDiv').removeClass('input-group');
        $('#percentageSignSpan').addClass('hide');
    } else {
        $('#percentageSignDiv').addClass('input-group');
        $('#percentageSignSpan').removeClass('hide');
    }
}


function calculateremain(payed) {
    var generalpayed = Number($("#genpay").val()) + Number($("#genpayvisa").val());
    var remain = Number(payed) - Number(generalpayed);
    $("#gen3total2").html(remain);
}

$("#saveBill, #saveAndPrint, #saveAndSend, #saveAndNew, #saveAndNewOrder").on('click', function (e) {
    if (!$('#sellbillForm').hasClass('processing')) {//to stop multi submitting
        $('#sellbillForm').addClass('processing');
        var theBtn = $(this);
        e.preventDefault();
        var ret = checkPayed();
        if (ret == 0) {
            $('#sellbillForm').removeClass('processing');
            return false;
        }
        if (Number($("#supplier").val()) > 0) {
        } else {
            alert('عفوا اختر عميل');
            $('#sellbillForm').removeClass('processing');
            return false;
        }
        if (Number($('[name="obgyBillType"]:checked').val()) > 0) {
        } else {
            if ($('[name="obgyBillType"]:first').is(":visible")) {
                alert('عفوا اختر نوع الفاتورة مباشر ام مستهلك');
                $('#sellbillForm').removeClass('processing');
                return false;
            }
        }
        document.getElementById("hiddenpricetype").value = document.getElementById("pricetype").value;
        thegeneralpayed();
        if ($("#supplier").val() == 1 || ($("#multiclient").val() == 0 && $("#supplier").val().indexOf("1") != -1)) {
            //نقدى
            //يتم دفع قيمة الفاتورة كاملة
            //ولا يستطيع التعديل فى المدفوع
            $('#genpay').val($('#sellbillaftertotalbill').val());
            $('#genpayvisa').val(0);
            $('#genpay').attr('readonly', 'readonly');
            //            $('#genpayvisa').attr('readonly', 'readonly');
        } else {
            $('#genpay').removeAttr('readonly');
            $('#genpayvisa').removeAttr('readonly');
        }
        var debitlimit = checkClientDebtLimit();
        if (debitlimit == 1) {
            $('#sellbillForm').removeClass('processing');
            return false;
        } else {

            var bsn = $('#bns').val();
            var flag = 1;
            var oldid = 0;
            if ($("[name='oldid']").length > 0) {
                oldid = document.getElementsByName("oldid")[0].value;
            }
            $.post("sellbillAjaxController.php?do=checkserial", { bsn: bsn, oldid: oldid }, function (data) {
                if (data == -1 || bsn == "") {
                    alert('عفوا سيريال الفاتورة مكرر');
                    flag = 0;
                    $('#sellbillForm').removeClass('processing');
                }
                //        else if (data == 1)
                //        {
                //            if ($("#settingreturn").val() == 1)
                //            {
                //                if ($("#sellbillprice").val() == 0)
                //                {
                //                    alert('من فضلك أدخل المنتجات');
                //                    flag = 0;
                //                }
                //            }
                //            else
                //            {
                //                if ($("#sellbillprice").val() == 0 && $("#returnsellbillprice").val() == 0)
                //                {
                //                    alert('من فضلك أدخل المنتجات');
                //                    flag = 0;
                //                }
                //            }
                //        }
                if (flag == 1) {
                    e.preventDefault();
                    var productSell = 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() != "") {
                                if (Number($('#product' + i).val()) > 0 || $('#product' + i).val().indexOf("hasSizeColor") == 0) {
                                    productSell = 1;
                                    //break;
                                }
                            }
                            if (($('#product' + i).val() == "" || $('#product' + i).val() == "-1" || !$('#productunit' + i).val()) && Number($('#proprice' + i).val()) > 0) {
                                productNeedCheckFlag = 1;
                                $('#product' + i).parents('tr').addClass('unsufficient');
                            } else {
                                $('#product' + i).parents('tr').removeClass('unsufficient');
                            }
                        }

                    }
                    if ($('#containerReturn').is(":visible")) {
                        var itr = $('#returnhidden_itr').val();
                        for (i = 1; i <= itr; i++) {
                            if ($('#returnproduct' + i).val()) {
                                //if ($('#returnproduct' + i).val() != "") {
                                if (Number($('#returnproduct' + i).val()) > 0 || $('#returnproduct' + i).val().indexOf("hasSizeColor") == 0) {
                                    productRet = 1;
                                    //break;
                                }
                            }
                            if (($('#returnproduct' + i).val() == "" || $('#returnproduct' + i).val() == "-1" || !$('#returnproductunit' + i).val()) && Number($('#returnproprice' + i).val()) > 0) {
                                productNeedCheckFlag = 1;
                                $('#returnproduct' + i).parents('tr').addClass('unsufficient');
                            } else {
                                $('#returnproduct' + i).parents('tr').removeClass('unsufficient');
                            }
                        }
                    }
                    if ((productSell == 1 || productRet == 1) && productNeedCheckFlag == 0) {
                        if ($('#sellerIsRequired').val() == "1" && $('#sellerid').val() == "-1") {
                            alert('عفوا لم تخترالبائع - المندوب -الطبيب');
                            $('#sellbillForm').removeClass('processing');
                        } else {
                            $('#bn').removeAttr('disabled');
                            if (stopRetProIfNotBoughtBefore() == 1 || checkInUse() != 1) {
                                if (stopRetProIfquantityMorthanBought() == 1) {
                                    if (check_negative_store_value() == 1) {
                                        var validFlag = 1;
                                        $("[id^='proSerials']").each(function () {//for checking sell & ret Both
                                            $(this).trigger('select2-close');
                                            if ($(this).hasClass('serial-success') || $(this).val() == "") {

                                            } else {
                                                validFlag = 0;
                                                alert('تأكد من ادخال جميع السريلات وبالكميات المطلوبة');
                                                return false;
                                            }
                                        });
                                        var myForm = document.getElementById("sellbillForm");
                                        var SS = Spry.Widget.Form.validate(myForm);
                                        if (SS == true && validFlag == 1) {
                                            $("#supplier").trigger('change', ['no', '', 'dontRepeat', 'submit']);
                                            //$("#supplier").change();

                                            //it is save btn,but i need after save open new bill so use action of save and new
                                            if ($('#saveBtnGoesTo').val() == 1 && theBtn.attr('id') == "saveBill") {
                                                //save and go to new bill after print
                                                $("#sellbillForm").attr("action", "sellbillController.php?do=addAndRetuen");
                                            }
                                            $('#supplier').select2("enable");
                                            markStoreDetailInUse();
                                            $('#sellbillForm').submit();
                                        } else {
                                            $('#sellbillForm').removeClass('processing');
                                        }
                                    } else {
                                        $('#sellbillForm').removeClass('processing');
                                    }
                                } else {
                                    $('#sellbillForm').removeClass('processing');
                                }
                            } else {
                                $('#sellbillForm').removeClass('processing');
                            }
                        }

                    } else {
                        alert('عفوا لم تختر منتجات');
                        $('#sellbillForm').removeClass('processing');
                        return false;
                    }
                }
            });
        }
    }
});
function prepareInputs() {
    //sell
    $('#containerpros tbody td input, #containerpros tbody td select, #containerpros tbody td textarea').each(function () {
        $(this).removeAttr('name');
    });
    let lastItr = $('#hidden_itr').val();
    if ($('#product' + lastItr).val() > 0) {
        $('#proprice' + lastItr).trigger('keyup');
    } else {
        lastItr--;
        $('#proprice' + lastItr).trigger('keyup');
    }
    $('#containerpros tbody tr').each(function () {
        var itr = $(this).find("input[id^='proprice']").first().attr('id').slice(8);
        let row = {
            proSellTrackingSerial: $('#proSellTrackingSerial' + itr).val(),
            parcode: $('#parcode' + itr).val(),
            parcodeType: $('#parcodeType' + itr).val(),
            productserailid: $('#productserailid' + itr).val(),
            product: $('#product' + itr).val(),
            productunit: $('#productunit' + itr).val(),
            proHeight: $('#proHeight' + itr).val(),
            proWidth: $('#proWidth' + itr).val(),
            pronum: $('#pronum' + itr).val(),
            proprice: $('#proprice' + itr).val(),
            prodis: $('#prodis' + itr).val(),
            hidden_prototal: $('#hidden_prototal' + itr).val(),
            comment: $('#comment' + itr).val(),
            prstorid: $('#prstorid' + itr).val(),
            discounttype: $('#discounttype' + itr).val(),
            scunitname: $('#scunitname' + itr).val(),
            pricetypepro: $('#pricetypepro' + itr).val(),
            proSerials: $('#proSerials' + itr).val(),
            playstationPlayId: $('#playstationPlayId' + itr).val(),
            proNum: $('#proNum' + itr).val(),
            hiddenNotes: $('#hiddenNotes' + itr).html(),
            tempSaveBillIdRow: $('#tempSaveBillIdRow' + itr).val(),
            prosellDiscountPer: $('#prosellDiscountPer' + itr).val(),
            prosellDiscountPerType: $('#prosellDiscountPerType' + itr).val(),
            prosellDiscountVal: $('#prosellDiscountVal' + itr).val(),
            catdis: $('#catdis' + itr).val(),

            [`type_${itr}_1`]: $('#type_' + itr + '_1').val(),
            [`subtype_${itr}_1`]: $('#subtype_' + itr + '_1').val(),
            [`rate_${itr}_1`]: $('#rate_' + itr + '_1').val(),
            [`amount_${itr}_1`]: $('#amount_' + itr + '_1').val(),
        }

        row[`taxesitr__${itr}`] = $('#taxesitr_' + itr).val();
        var taxesitr = $('#taxesitr_' + itr).val();
        for (let r = 1; r <= taxesitr; r++) {
            row[`type_${itr}_${r}`] = $('#type_' + itr + '_' + r).val();
            row[`subtype_${itr}_${r}`] = $('#subtype_' + itr + '_' + r).val();
            row[`rate_${itr}_${r}`] = $('#rate_' + itr + '_' + r).val();
            row[`amount_${itr}_${r}`] = $('#amount_' + itr + '_' + r).val();
        }
        row = JSON.stringify(row);//{"type":"Fiat","model":"500","color":"White"}
        //        row = row.replace(/"([^"]+)":/g, '$1:');//{type:"Fiat",model:"500",color:"White"}
        row = row.replaceAll("\"", "'");//{type:'Fiat',model:'500',color:'White'}
        //        $('#containerpros').parent().append("<input type='hidden' name='obj" + itr + "' id='obj" + itr + "' value=" + row + ">");
        $('#containerpros').parent().append('<input type="hidden" name="obj' + itr + '" id="obj' + itr + '" value="' + row + '">');

    });
    ///////////
    //ret
    $('#containerReturn tbody td input, #containerReturn tbody td select, #containerReturn tbody td textarea').each(function () {
        $(this).removeAttr('name');
    });
    $('#containerReturn tbody tr').each(function () {
        var itr = $(this).find("input[id^='returnproprice']").first().attr('id').slice(14);
        let row = {
            retproSellTrackingSerial: $('#retproSellTrackingSerial' + itr).val(),
            returnparcode: $('#returnparcode' + itr).val(),
            returnparcodeType: $('#returnparcodeType' + itr).val(),
            returnproductserailid: $('#returnproductserailid' + itr).val(),
            returnproduct: $('#returnproduct' + itr).val(),
            returnproductunit: $('#returnproductunit' + itr).val(),
            returnproHeight: $('#returnproHeight' + itr).val(),
            returnproWidth: $('#returnproWidth' + itr).val(),
            returnpronum: $('#returnpronum' + itr).val(),
            returnproprice: $('#returnproprice' + itr).val(),
            returnprodis: $('#returnprodis' + itr).val(),
            returnhidden_prototal: $('#returnhidden_prototal' + itr).val(),
            returncomment: $('#returncomment' + itr).val(),
            returndiscounttype: $('#returndiscounttype' + itr).val(),
            reprstorid: $('#reprstorid' + itr).val(),
            returnscunitname: $('#returnscunitname' + itr).val(),
            retpricetypepro: $('#retpricetypepro' + itr).val(),
            proSerialsRet: $('#proSerialsRet' + itr).val(),
            retProNum: $('#retProNum' + itr).val(),
            //hiddenNotes: $('#hiddenNotes' + itr).html(),
            tempSaveBillIdRowRet$h: $('#tempSaveBillIdRowRet' + itr).val(),
        }
        row = JSON.stringify(row);//{"type":"Fiat","model":"500","color":"White"}
        //        row = row.replace(/"([^"]+)":/g, '$1:');//{type:"Fiat",model:"500",color:"White"}
        row = row.replaceAll("\"", "'");//{type:'Fiat',model:'500',color:'White'}
        //        $('#containerpros').parent().append("<input type='hidden' name='objRet" + itr + "' id='objRet" + itr + "' value=" + row + ">");
        $('#containerpros').parent().append('<input type="hidden" name="objRet' + itr + '" id="objRet' + itr + '" value="' + row + '">');

    });
}
function addDataOnly() {
    $('#bn').removeAttr('disabled');
    $("#sellbillForm").attr("action", "sellbillController.php?do=add");
    return true;
}


function addDataAndReturn() {
    $('#bn').removeAttr('disabled');
    $("#sellbillForm").attr("action", "sellbillController.php?do=addAndRetuen");
    return true;
}

function addDataAndSend() {
    $('#bn').removeAttr('disabled');
    $("#sellbillForm").attr("action", "sellbillController.php?do=addAndSend");
    return true;
}

function addDataAndPrint() {
    $('#bn').removeAttr('disabled');
    $("#sellbillForm").attr("action", "sellbillController.php?do=addAndPrint");
    return true;
}


function addDataAndReturnOrder() {
    $('#bn').removeAttr('disabled');
    $("#sellbillForm").attr("action", "sellbillController.php?do=addAndRetuen&sellorder=1");
    return true;
}

function printData() {
    print_Custom('mycustomheader');
}




////////////////////////////////////
function moveProgressBar(finished, total) {
    var elem = document.getElementById("myBar");
    var width = (Number(finished) / Number(total)) * 100; //get ratio completed
    width = Number(width.toFixed());
    elem.style.width = width + "%";
    elem.innerHTML = width + "%";
    if (width < 100) {
        $('#progressBarContainer').show();
        $('#progressBarContainer').css("overflow", "visible");
    } else if (width == 100) {
        setTimeout(function () {
            $('#progressBarContainer').hide('slow');
        }, 1500)
    }
}
function getpriceallForBillRowFunc(theselectedvalue, productunit, pricetype, $n, rowType) {// rowType = 0 for sell,1 for ret
    setTimeout(function () {
        $.ajax({
            url: 'sellbillAjaxController.php?do=getpriceall&productid=' + theselectedvalue + '&productunit=' + productunit + '&pricetype=' + pricetype + '&itrs=' + $n,
            type: "get",
            async: false,
            success: function (data) {
                data = data.split("/");
                //use  data and affect progessbar
                if (rowType == 0) {
                    $('#proprice' + data[1]).val(data[0]);
                    //change price of product from main curr to slected curr val
                    $('#proprice' + data[1]).val(getValueInTermsOfSelectedCurrency($('#proprice' + data[1]).val()));
                    $('#proprice' + data[1]).trigger('keyup');
                    moveProgressBar((itr_finished + itr_ret_finished), noORowsToUpdate);
                    itr_finished++;
                } else if (rowType == 1) {
                    $('#returnproprice' + data[1]).val(data[0]);
                    //change price of product from main curr to slected curr val
                    $('#returnproprice' + data[1]).val(getValueInTermsOfSelectedCurrency($('#returnproprice' + data[1]).val()));
                    $('#returnproprice' + data[1]).trigger('keyup');
                    moveProgressBar((itr_finished + itr_ret_finished), noORowsToUpdate);
                    itr_ret_finished++;
                }


                //validate complete of all rows
                if (noORowsToUpdate == (itr_finished + itr_ret_finished)) {
                    moveProgressBar(noORowsToUpdate, noORowsToUpdate);
                    $('#sellbillForm').removeClass('processing');
                }
            },
            error: function () {
                alert("لقد حدث خطأ أثناء إجراء العملية");
            }
        });
    }, 0);
}

$('#pricetype').live('change', function () {
    $('#sellbillForm').addClass('processing');
    var pricetype = $(this).val();
    noORowsToUpdate = 0;
    if ($('#header4Sell').is(":visible"))
        noORowsToUpdate += $("[id^='productdiv']").length;
    if ($('#header4retSell').is(":visible"))
        noORowsToUpdate += $("[id^='returnproductdiv']").length;
    itr_finished = 0;
    itr_ret_finished = 0;
    if ($('#header4Sell').is(":visible")) {
        $("[id^='productdiv']").each(function () {
            $n = $(this).attr('id').substr('10');
            var theselectedvalue = $('#product' + $n).val();
            var productunit = $("#productunit" + $n).val();
            var pronum = $("#pronum" + $n).val();
            $('#pricetypepro' + $n).val(pricetype).trigger('change.select2'); //.change();
            if (theselectedvalue != "" && theselectedvalue != "null" && theselectedvalue != null && theselectedvalue != "-1") {
                getpriceallForBillRowFunc(theselectedvalue, productunit, pricetype, $n, 0);
            } else {
                itr_finished++;
                if (noORowsToUpdate == (itr_finished + itr_ret_finished)) {
                    moveProgressBar(noORowsToUpdate, noORowsToUpdate);
                    $('#sellbillForm').removeClass('processing');
                }
            }
        });
    }

    if ($('#header4retSell').is(":visible")) {
        $("[id^='returnproductdiv']").each(function () {
            $n = $(this).attr('id').substr('16');
            var theselectedvalue = $('#returnproduct' + $n).val();
            var productunit = $("#returnproductunit" + $n).val();
            var pronum = $("#returnpronum" + $n).val();
            $('#retpricetypepro' + $n).val(pricetype).trigger('change.select2'); //.change();
            if (theselectedvalue != "" && theselectedvalue != "null" && theselectedvalue != null && theselectedvalue != "-1") {
                getpriceallForBillRowFunc(theselectedvalue, productunit, pricetype, $n, 1);
            } else {
                itr_ret_finished++;
                if (noORowsToUpdate == (itr_finished + itr_ret_finished)) {
                    moveProgressBar(noORowsToUpdate, noORowsToUpdate);
                    $('#sellbillForm').removeClass('processing');
                }
            }
        });
    }
});
$("[id^='pricetypepro']").live('change', function () {
    var pricetype = $(this).val();
    var id = $(this).attr('id');
    $n = id.substring(12);
    var theselectedvalue = $('#product' + $n).val();
    var productunit = $("#productunit" + $n).val();
    var pronum = $("#pronum" + $n).val();
    $('#pricetypepro' + $n).val(pricetype).trigger('change.select2'); //.change();
    if (theselectedvalue != "" && theselectedvalue != "null" && theselectedvalue != null && theselectedvalue != "-1") {
        $.ajax({
            url: 'sellbillAjaxController.php?do=getpriceall&productid=' + theselectedvalue + '&productunit=' + productunit + '&pricetype=' + pricetype + '&itrs=' + $n,
            type: "get",
            async: false,
            success: function (data) {
                data = data.split("/");
                $('#proprice' + data[1]).val(data[0]);
                //change price of product from main curr to slected curr val
                $('#proprice' + data[1]).val(getValueInTermsOfSelectedCurrency($('#proprice' + data[1]).val()));
                $('#proprice' + data[1]).trigger('keyup');
            },
            error: function () {
                alert("لقد حدث خطأ أثناء إجراء العملية");
            }
        });
    }

});
////////////////////////////////////
function check_negative_store_value() {


    //when preventing -ve store values
    //the sold product in sell bill with quantity make store quantity -ve is not allowed
    var flag = 0;
    var storenegative = $('#storenegative').val();
    //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').val();
    for (var i = 0; i <= itr; i++) {
        if ($('#product' + i).length > 0 && (Number($('#product' + i).val()) > 0 || $('#product' + i).val().indexOf("hasSizeColor") == 0)
            && (($('#storeid').length > 0 && Number($('#storeid').val()) > 0) || $('#prstorid' + i).length > 0 && Number($('#prstorid' + i).val()) > 0)) {
            var product_id = Number($('#product' + i).val());
            if ($('#product' + i).val().indexOf("hasSizeColor") == 0) {
                product_id = $('#product' + i).val();
            }

            if ($('#prstorid' + i).length > 0 && Number($('#prstorid' + i).val()) > 0) {
                var store_id = Number($('#prstorid' + i).val());
            } else {
                var store_id = Number($('#storeid').val());
            }

            var unit_id = Number($('#productunit' + i).val());
            var quantity = Number($('#pronum' + 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=checkNegative2',
        data: { product_store_arr: product_store_arr },
        async: false,
        success: function (data) {

            var itr = $('#hidden_itr').val();
            for (var i = 1; i <= itr; i++) {
                if ($('#product' + i).length > 0) {
                    $('#product' + i).parents('tr').removeClass('unsufficient');
                }
            }


            data = JSON.parse(data);
            //console.log(data);
            data.forEach(function (element) {
                element = element.split(",");
                var store_id = element[0];
                var product_id = element[1];
                var cat_setting = element[2];
                var suffecient_flag = element[3];
                //loop to mark un sufficient quantities
                if (suffecient_flag == 1) {
                    flag = 1;
                } else {
                    if (storenegative == 0 || cat_setting == 1) {
                        for (var i = 1; i <= itr; i++) {
                            if ($('#product' + i).length > 0) {
                                var product_id_row = $('#product' + i).val();
                                if ($('#prstorid' + i).length > 0 && Number($('#prstorid' + i).val()) > 0) {
                                    var store_id_row = Number($('#prstorid' + i).val());
                                } else {
                                    var store_id_row = Number($('#storeid').val());
                                }


                                if ($("[name='oldid']").length > 0) {
                                    var pNum = Number($('#productunit' + i + ' :selected').data('pu-num'));
                                    var quantity = Number($('#pronum' + i).val());
                                    var currentQuantity = quantity * pNum;
                                    var oldQuantity = Number($('#oldpronum' + i).val());
                                }
                                if (product_id_row == product_id && store_id_row == store_id && (currentQuantity > oldQuantity && $("[name='oldid']").length > 0 || $("[name='oldid']").length == 0)) {
                                    $('#product' + i).parents('tr').addClass('unsufficient');
                                }
                            }
                        }
                    } else {
                        flag = 1;
                    }
                }

            });

            if ($('.unsufficient').length > 0) {
                $('#check_store_msg').html("بعض الكميات المطلوبة غير موجودة بالمخازن.");
                $('#check_store_div').show();
                alert("بعض الكميات المطلوبة غير موجودة بالمخازن.");
                flag = 0;
            } else {
                flag = 1;
            }

        }

    });


    return flag;
}
function stopRetProIfNotBoughtBefore() {
    if ($('#retOnlySoldProducts').val() == 1 && Number($("#supplier").val()) > 1) {//sold befor//$('#returnproprice' + n).css('background-color') == 'rgb(183, 223, 164)') {
        //alert('لا يمكن رد هذا المنتج حيث ان هذا العميل لم يشتريه مسبقا');
        //$('#returnremove' + n).click();//1-prepare return products group by productid,storeid
        $('#check_store_msg').html("جارى التحقق من المردودات السابقة للعميل .");
        $('#check_store_div').show();

        var flag = 0;

        var productsStr = ''; //object not array
        //return itrations
        var itr = $('#returnhidden_itr').val();
        for (var i = 1; i <= itr; i++) {
            if ($('#returnproduct' + i).length > 0 && (Number($('#returnproduct' + i).val()) > 0 || $('#returnproduct' + i).val().indexOf("hasSizeColor") == 0)) {
                var product_id = Number($('#returnproduct' + i).val());
                if ($('#returnproduct' + i).val().indexOf("hasSizeColor") == 0) {
                    product_id = $('#returnproduct' + i).val();
                }
                productsStr += product_id + ',';
            }
        }
        //        var product_store_arr = JSON.stringify(product_store_arr);
        //$('#product_store_arr').val(product_store_arr);
        if (productsStr != '') {
            $.ajax({
                type: "POST",
                url: 'sellbillAjaxController.php?do=checkClientSoldBefore',
                data: { client: $("#supplier").val(), products: productsStr },
                async: false,
                success: function (data) {

                    var arr = data.split(',');
                    for (var i = 1; i <= itr; i++) {
                        if ($('#returnproduct' + i).length > 0) {
                            $('#returnproduct' + i).parents('tr').removeClass('unsufficient');
                        }
                        var product_id_row = $('#returnproduct' + i).val();
                        $.each(arr, function (index, value) {
                            var product_id = value;
                            if ($('#returnproduct' + (index + 1)).length > 0) {
                                if (product_id_row == product_id) {
                                    $('#returnproduct' + i).parents('tr').addClass('unsufficient');
                                }
                            }
                        });
                    }
                    if ($('.unsufficient').length > 0) {
                        $('#check_store_msg').html("العميل لم يشترى هذه المنتجات من قبل");
                        $('#check_store_div').show();
                        alert('لا يمكن رد هذا المنتج حيث ان هذا العميل لم يشتريه مسبقا');
                    } else {
                        flag = 1;
                        $('#check_store_div').hide();
                    }
                }

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


    return flag;
}

function stopRetProIfquantityMorthanBought() {
    if ($('#checkretsellclient').val() == 2 && Number($("#supplier").val()) > 1) {//sold befor//$('#returnproprice' + n).css('background-color') == 'rgb(183, 223, 164)') {
        //alert('لا يمكن رد هذا المنتج حيث ان هذا العميل لم يشتريه مسبقا');
        //$('#returnremove' + n).click();//1-prepare return products group by productid,storeid
        $('#check_store_msg').html("جارى التحقق من صافي مبيعات العميل .");
        $('#check_store_div').show();

        var flag = 0;

        var productsStr = ''; //object not array
        //return itrations
        var itr = $('#returnhidden_itr').val();
        for (var i = 1; i <= itr; i++) {
            if ($('#returnproduct' + i).length > 0 && (Number($('#returnproduct' + i).val()) > 0 || $('#returnproduct' + i).val().indexOf("hasSizeColor") == 0)) {
                $('#returnproduct' + i).parents('tr').removeClass('unsufficient');
                if ($('#returnpronum' + i).val() > $('#netSellQ' + i).val()) {
                    $('#returnproduct' + i).parents('tr').addClass('unsufficient');
                }
            }
        }
        if ($('.unsufficient').length > 0) {
            $('#check_store_msg').html("الكمية أكبر من صافي مبيعات العميل");
            $('#check_store_div').show();
            alert('لا يمكن رد هذه الكمية حيث انها أكبر من صافي مبيعات العميل');
        } else {
            flag = 1;
            $('#check_store_div').hide();
        }
    } else {
        var flag = 1;
    }


    return flag;
}
function checkPayed() {
    var ret = 1;
    //
    var genpay = Number($('#genpay').val()) + Number($('#genpayvisa').val());
    var payedSetting = Number($('#payedSetting').val());
    var sellbillaftertotalbill = Math.abs(Number($('#sellbillaftertotalbill').val()));

    if ($("#supplier").val() == 1 && genpay != sellbillaftertotalbill) {
        alert('عفوا لابد ان يتساوى المدفوع مع قيمة الفاتورة حيث ان العميل نقدى');
        ret = 0;
    } else {

        if (payedSetting == 0) {
            //payed shouldnot be greater than total
            if (genpay > sellbillaftertotalbill) {
                alert('عفوا المدفوع اكثر من قيمة الفاتورة');
                //var newgenPay = sellbillaftertotalbill;
                var newgenPay = sellbillaftertotalbill - Number($('#genpayvisa').val());
                $('#genpay').val(newgenPay);
                ret = 0;
            }
        }

        if (Number($('#genpayvisa').val()) != 0 && Number($('#visaAccount').val()) < 1) {
            alert('عفوا لم تختر حساب الدفع الالكترونى');
            ret = 0;
        }
    }


    return ret;
}
function checkClientDebtLimit() {
    var flag = 0;
    var sellbillaftertotalbill = Number($('#sellbillaftertotalbill').val());
    if ($("#multiclient").val() == 1) {//only one client
        if ($("#supplier").val() == 1 || sellbillaftertotalbill < 0) {//sellbillaftertotalbill < 0 is return dont check too
            //نقدى
            //will pay it all
        } else {
            $.ajax({
                type: "POST",
                url: 'sellbillAjaxController.php?do=getclientdebtlimit&clientid=' + $("#supplier").val(),
                data: {},
                async: false,
                success: function (data) {
                    data = JSON.parse(data);
                    var debtLimit = Number(data.debtLimit);
                    var clientDefaultDebtLimitControl = data.clientDefaultDebtLimitControl;
                    var clientdebtafter = Number($('#clientdebtafter').val());
                    //$('#genpay').removeAttr('readonly');
                    if (clientdebtafter > debtLimit && debtLimit >= 0 && clientDefaultDebtLimitControl == 1) {
                        alert('عفوا لقد تخطى العميل حد الدين المسموح له');
                        flag = 1;
                    }
                }
            });
        }
    }

    return flag;
}


$('#sellbillForm').live('submit', function (e) {
    if ($("#sumSameProductForStore").length > 0 && $("#sumSameProductForStore").val() == "1") {
        var morestore = $('#morestore').val();
        if (morestore == "1") {
            //only one store
            //1- for sell part
            $("#containerpros div[id^='productdiv'] input[id^='product']").each(function () {
                var proid = Number($(this).val());
                var itr = $(this).attr('id').slice(7);
                if (proid > 0 && $('#product' + itr).length > 0) {//$(this).attr('id').length > 0 to make sure it is no del in the function sumProduct
                    sumProduct(proid, -10, itr);
                }
            });
            //2- for ret part
            $("#containerReturn div[id^='returnproductdiv'] input[id^='returnproduct']").each(function () {
                var proid = Number($(this).val());
                var itr = $(this).attr('id').slice(13);
                if (proid > 0 && $('#returnproduct' + itr).length > 0) {//$(this).attr('id').length > 0 to make sure it is no del in the function sumProduct
                    sumProductRet(proid, -10, itr);
                }
            });
        } else {
            //store at each row so loop on stores first
            //1- for sell part
            $("#containerpros div[id^='productdiv'] input[id^='product']").each(function () {
                var proid = Number($(this).val());
                var itr = $(this).attr('id').slice(7);
                if (proid > 0 && $('#product' + itr).length > 0) {//$(this).attr('id').length > 0 to make sure it is no del in the function sumProduct
                    var storeId = Number($('#prstorid' + itr).val());
                    sumProduct(proid, storeId, itr);
                }
            });
            //2- for ret part
            $("#containerReturn div[id^='returnproductdiv'] input[id^='returnproduct']").each(function () {
                var proid = Number($(this).val());
                var itr = $(this).attr('id').slice(13);
                if (proid > 0 && $('#returnproduct' + itr).length > 0) {//$(this).attr('id').length > 0 to make sure it is no del in the function sumProduct
                    var storeId = Number($('#reprstorid' + itr).val());
                    sumProductRet(proid, storeId, itr);
                }
            });
        }
    }
    prepareInputs();
});
function sumProduct(proid, storeId, itr) {
    itr = Number(itr);
    var pronum = 0;
    var scunitname = 0;
    var proprice = 0;
    var prodis = 0;
    var hidden_prototal = 0;
    var counter = 0
    $noOfDecimalPlaces = noOfDecimalPlacesForRows;//$("#noOfDecimalPlaces").val();
    $("#containerpros div[id^='productdiv'] input[id^='product']").each(function () {
        var loopProId = Number($(this).val());
        var loopItr = $(this).attr('id').slice(7);
        //sum products in same store  or  store == -10 means one store for all bill
        if (loopProId == proid && (storeId == -10 || storeId == Number($('#prstorid' + loopItr).val()))) {
            counter++;
            pronum += Number($('#pronum' + loopItr).val());
            scunitname += Number($('#scunitname' + loopItr).val());
            proprice += Number($('#proprice' + loopItr).val());
            prodis += Number($('#prodis' + loopItr).val());
            hidden_prototal += Number($('#hidden_prototal' + loopItr).val());
            //remove the row
            if (Number(loopItr) > Number(itr)) {
                //$('#remove' + loopItr).click();//this recalculate total in wrong time just remove it with out recalculating
                $('#remove' + loopItr).parent().parent().remove();
            }
        }
    });
    $('#pronum' + itr).val(pronum); //.keyup();
    $('#scunitname' + itr).val(scunitname); //.keyup();
    $('#prodis' + itr).val(prodis); //.keyup();
    $('#prototal' + itr).html(hidden_prototal); //.keyup();
    $('#hidden_prototal' + itr).val(hidden_prototal); //.keyup();
    /* -- Now.proprice is the sum of propricessss so get mean proprice by dividing on number of pieces --  */
    // var newproprice = (hidden_prototal / pronum).toFixed($noOfDecimalPlaces);
    if (counter > 1)
        var newproprice = (hidden_prototal / pronum).toFixed($noOfDecimalPlaces);
    else
        var newproprice = (proprice).toFixed($noOfDecimalPlaces);
    $('#proprice' + itr).val(newproprice)//.keyup();
    //change price of product from main curr to slected curr val
    $('#proprice' + itr).val(getValueInTermsOfSelectedCurrency($('#proprice' + itr).val()));

}
function sumProductRet(proid, storeId, itr) {
    itr = Number(itr);
    var pronum = 0;
    var scunitname = 0;
    var proprice = 0;
    var prodis = 0;
    var hidden_prototal = 0;
    $noOfDecimalPlaces = $("#noOfDecimalPlaces").val();
    $("#containerReturn div[id^='returnproductdiv'] input[id^='returnproduct']").each(function () {
        var loopProId = Number($(this).val());
        var loopItr = $(this).attr('id').slice(13);
        //sum products in same store  or  store == -10 means one store for all bill
        if (loopProId == proid && (storeId == -10 || storeId == Number($('#reprstorid' + loopItr).val()))) {
            pronum += Number($('#returnpronum' + loopItr).val());
            scunitname += Number($('#returnscunitname' + loopItr).val());
            proprice += Number($('#returnproprice' + loopItr).val());
            prodis += Number($('#returnprodis' + loopItr).val());
            hidden_prototal += Number($('#returnhidden_prototal' + loopItr).val());
            //remove the row
            if (Number(loopItr) > Number(itr)) {
                //$('#returnremove' + loopItr).click();//this recalculate total in wrong time just remove it with out recalculating
                $('#returnremove' + loopItr).parent().parent().remove();
            }
        }
    });
    $('#returnpronum' + itr).val(pronum); //.keyup();
    $('#returnscunitname' + itr).val(scunitname); //.keyup();
    $('#returnprodis' + itr).val(prodis); //.keyup();
    $('#reurnprototal' + itr).html(hidden_prototal); //.keyup();
    $('#returnhidden_prototal' + itr).val(hidden_prototal); //.keyup();
    /* -- Now.proprice is the sum of propricessss so get mean proprice by dividing on number of pieces --  */
    var newproprice = (hidden_prototal / pronum).toFixed($noOfDecimalPlaces);
    $('#returnproprice' + itr).val(newproprice); //.keyup();
    //change price of product from main curr to slected curr val
    $('#returnproprice' + itr).val(getValueInTermsOfSelectedCurrency($('#returnproprice' + itr).val()));
}


$("#sellbillidToRet").select2({
    placeholder: "اختر رقم الفاتورة ",
    minimumInputLength: 1,
    //  minimumInputLength: 3,
    multiple: false,
    quietMillis: 100,
    ajax: {
        url: "sellbillAjaxController.php?do=getBillsNumbers",
        dataType: 'json',
        data: function (term, page) {
            //  alert(term);
            return {
                term: term, //search term
                page_limit: 10, // page size
            };
        },
        results: function (data) {

            // alert(term);
            return { results: data };
        }
    },
    formatResult: formatResult,
    initSelection: function (element, callback) {
        var item = element.val().split(':');
        //# to prevent add client .

        var data = { id: item[0], text: item[1] };
        callback(data);


    }
}).on('change', function () {
    window.location.href = window.location.href + "&billtoret=" + $(this).val();
});
//dontRepeat is for .autoSaveBillMainPart when change supplier to stop ininite loop of supplierchange
$("#supplier").on('change', function (e, changePrice, initialSupp_PriceType = '', dontRepeat = '', action = '') {
    if (allowSupplierChange == 1 || supplier_id == -2) {
        var suppdata = $('#supplier').select2('data');
        if (suppdata.id != -2) {
            $('#supplieridBeforeChange').val(suppdata.id);
            $('#suppliernameBeforeChange').val(suppdata.text);
        }

        //need that line anyway
        if ($('#supplier').hasClass('selectingClass')) {// the class to make diffrence of change from select2 itself "choose another option" ,it wont exist for triggering change
            $('#supplier').removeClass('selectingClass')
            var suppName = suppdata.text;
            if (typeof userstoreidForUser !== 'undefined' && userstoreidForUser !== null && suppName.indexOf('/') > -1)
                suppName = suppName.split('/')[0];
            $("#tempclientName").val(suppName).change();
        }

        var supplier_id = $(this).val();
        if (changePrice == 'no' || supplier_id == -2) {
        } else {
            if ($('#collectionType').val() > 0) {
                $('#collectionDate').val($("#supplier").select2('data').postponeDate);
            }
            var hiddenpritype = $("#hiddenpritype").val();
            if (initialSupp_PriceType == '') {//i dont have supp price type get it with ajax
                var usePriceTypeOfClient = $('#usePriceTypeOfClient').val();
                if (usePriceTypeOfClient == "1") {
                    $.post('sellbillAjaxController.php?do=getPricType', { supplier_id: supplier_id }, function (data) {
                        // alert(data);
                        // $('#pricetype').html(data);
                        if (data == -1) {
                            $("#pricetype").val(hiddenpritype).change();
                        } else {
                            $("#pricetype").val(data).change();
                        }

                        //            if (data == 0) {
                        //                $("#pricetype").select2("data", {id: data, text: 'جملة'});
                        //            } else if (data == 1) {
                        //                $("#pricetype").select2("data", {id: data, text: 'تجزئه'});
                        //            } else if (data == 2) {
                        //                $("#pricetype").select2("data", {id: data, text: 'نصف جملة'});
                        //            } else if (data == -1) {
                        //                if (hiddenpritype == 0) {
                        //                    $("#pricetype").select2("data", {id: data, text: 'جملة'});
                        //                } else if (hiddenpritype == 1) {
                        //                    $("#pricetype").select2("data", {id: data, text: 'تجزئه'});
                        //                }
                        //                else if (hiddenpritype == 2) {
                        //                    $("#pricetype").select2("data", {id: data, text: 'نصف جملة'});
                        //                }
                        //            }


                    });
                }
            } else {//happens when iam just entering page so i have value,dont go for it with ajax to optimize time
                if (initialSupp_PriceType == -1) {
                    $("#pricetype").val(hiddenpritype).change();
                } else {
                    $("#pricetype").val(initialSupp_PriceType).change();
                }
            }

        }
    }
});
//
$(document).on('change keyup', '#delivery', function () {
    var piecesNum = Number($('#sellbillaftertotalbill').val());
    $('#delivery').each(function () {
        piecesNum += Number($(this).val());
    });
    $('#valdelivery').html(piecesNum);
    $('#valdeliveryhidden').val(piecesNum);
});
$(document).on('change keyup', '#vatIncludedTotalIfRow', function () {
    var vatIncludedTotalIfRow = $(this).val();
    var vatPerBill = $('#tax').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);
            //change price of product from main curr to slected curr val
            $('#proprice' + $n).val(getValueInTermsOfSelectedCurrency($('#proprice' + $n).val()));
            $('#pronum' + $n).keyup();
        } else {
            $n = getLastUsedRetRow();
            quantity = Number($('#returnpronum' + $n).val());
            var rowTotal = total / quantity;
            $('#returnproprice' + $n).val(rowTotal);
            //change price of product from main curr to slected curr val
            $('#returnproprice' + $n).val(getValueInTermsOfSelectedCurrency($('#returnproprice' + $n).val()));
            $('#returnpronum' + $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 = $('#returnhidden_itr').val();
    var lastItr = 0;
    for (i = itr; i >= 1; i--) {
        if ($('#returnproduct' + i).val()) {
            //if ($('#product' + i).val() != "") {
            if (Number($('#returnproduct' + i).val()) > 0 || $('#returnproduct' + i).val().indexOf("hasSizeColor") == 0) {
                lastItr = i;
                return lastItr;
            }
        }
    }
}
function calcProfit() {
    if ($("[name='oldid']").length == 0) {
        var sellbillaftertotalbill = $('#sellbillaftertotalbill').val();

        var profit = 0;
        if ($('#containerpros').is(":visible")) {
            var itr = $('#hidden_itr').val();
            var cost = 0;
            for (i = 1; i <= itr; i++) {
                if ($('#product' + i).val()) {
                    if (Number($('#product' + i).val()) > 0 || $('#product' + i).val().indexOf("hasSizeColor") == 0) {

                        var pNum = Number($('#productunit' + i + ' :selected').data('pu-num'));
                        if (defaultUnitPriceAtBill == 0) {
                            var profitPriceUnit = Number($('#productunit' + i + ' :selected').data('profit-price'));
                            var profitPriceUnit = pNum * profitPriceUnit;
                        } else {
                            var profitPriceUnit = Number($('#productunit' + i + ' :selected').data('unit-price'));
                        }
                        //lowestPrice = getValueInTermsOfSelectedCurrency(lowestPrice);
                        cost += profitPriceUnit * $('#pronum' + i).val();
                    }
                }
            }
            profit = sellbillaftertotalbill - cost;
        }

        $('#profitVal').val(profit);
    }

}

//azmy add client in sellbill in model


$('#clientareaid').select2({
    placeholder: "اختر الشركة  - المنطقة",
    //minimumInputLength: 2,
    //triggerChange: true,
    //allowClear: true,
    ajax: {
        url: 'clientControllerAjax.php?do=getclientarea',
        dataType: 'json',
        type: "POST",
        data: function (term) {
            return {
                searchTerms: term,
                //governmentid : $('#clientgovernmentid').val()
            };
        },
        results: function (data) {
            return {
                results: data,
            };
        }
    },
    formatResult: formatResult,
    //        initSelection: function (element, callback) {
    //            var item = element.val().split(':');
    //            var data = {id: item[0], name: item[1]};
    //            callback(data);
    //        }
});
//
$('#clientareaid2').select2({
    placeholder: "اختر الشركة  - المنطقة",
    //minimumInputLength: 2,
    //triggerChange: true,
    //allowClear: true,
    ajax: {
        url: 'clientControllerAjax.php?do=getclientarea',
        dataType: 'json',
        type: "POST",
        data: function (term) {
            return {
                searchTerms: term,
                //governmentid : $('#clientgovernmentid').val()
            };
        },
        results: function (data) {
            return {
                results: data,
            };
        }
    },
    formatResult: formatResult,
    //        initSelection: function (element, callback) {
    //            var item = element.val().split(':');
    //            var data = {id: item[0], name: item[1]};
    //            callback(data);
    //        }
});
$("#clientareaid2").select2("data", { id: $('#clientareaId').val(), text: $('#governmentName').val() + ' - ' + $('#clientareaName').val() });
//var proprice1 = $("#proprice1").val();
//var proprice2 = $("#proprice2").val();
//dotheecheckk();
//function dotheecheckk() {
//    p1 = $("#proprice1").val();
//    p2 = $("#proprice2").val();
//    if (proprice1 !== p1) {
//        alert(1);
//    }
//    if (proprice2 !== p2) {
//        alert(2);
//    }
//    setTimeout(function () {
//        dotheecheckk();
//    }, 10);
//}
function calcQuantity(i, e) {
    var height = Number($('#proHeight' + i).val());
    var width = Number($('#proWidth' + i).val());
    $noOfDecimalPlaces = $("#noOfDecimalPlaces").val();
    var quantity = (height * width).toFixed($noOfDecimalPlaces);
    $("#pronum" + i).val(quantity).keyup();
}
function calcQuantityReturn(i, e) {
    var height = Number($('#returnproHeight' + i).val());
    var width = Number($('#returnproWidth' + i).val());
    $noOfDecimalPlaces = $("#noOfDecimalPlaces").val();
    var quantity = (height * width).toFixed($noOfDecimalPlaces);
    $("#returnpronum" + i).val(quantity).keyup();
}
function howMuchDiscount(total) {
    if (stopDiscountOfTotalControl == 1) {
        var specialDiscount = Number($('#specialDiscount_').val());
        var specialDiscountVal = Number($('#specialDiscountVal_').val());
        if (specialDiscount == 1) {
            $('#percentageSignDiv').addClass('input-group');
            $('#percentageSignSpan').removeClass('hide');
            $('#distype').val(2);
            $('#distype').select2('data', { id: 2, text: 'نسبة' });
            $('#gendis').val(specialDiscountVal);
        } else {
            $('#percentageSignDiv').addClass('input-group');
            $('#percentageSignSpan').removeClass('hide');
            var sellbilltotalbill = Number($('#sellbilltotalbill').val());
            allDiscounts.forEach(function (element, index) {
                //console.log(element.totalFrom);
                if (sellbilltotalbill >= Number(element.totalFrom) && sellbilltotalbill <= Number(element.totalTo)) {
                    $('#distype').val(2);
                    $('#distype').select2('data', { id: 2, text: 'نسبة' });
                    $('#gendis').val(element.discount);
                }
            });
        }
    }
}
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 ($('#returnproduct' + rowitr).val()) {
                if (Number($('#returnproduct' + rowitr).val()) > 0 || $('#returnproduct' + rowitr).val().indexOf("hasSizeColor") == 0) {
                    //##
                    var itr = $('#returnhidden_itr').val();
                    for (i = 1; i <= itr; i++) {
                        if ($('#returnproduct' + i).length > 0 && i != rowitr && $('#returnproduct' + i).val() === $('#returnproduct' + rowitr).val()) {
                            $('#returnproduct' + i).parents('tr').addClass('unsufficient');
                            $('#returnproduct' + rowitr).parents('tr').addClass('unsufficient');
                            alert('هذا المنتج مكرر');
                            setTimeout(function () {
                                $('#returnproduct' + i).parents('tr').removeClass('unsufficient');
                                $('#returnproduct' + rowitr).parents('tr').removeClass('unsufficient');
                            }, 2000);
                            break;
                        }
                    }
                }
            }
        }
    }

}
$(function () {

    setTimeout(function () {
        var offerId = Number($('#offerId').val());
        if (offerId > 0 || manyParcodesFlag == 1) {
            //do nothing offer has its store
            var sellbilldiscount = Number($('#sellbilldiscount').val());
            $('#gendis').val(sellbilldiscount).trigger('keyup');
            if (activateAutoSave == 1 && offerId == 0) {
                allowSupplierChange = 0;
            }
        } else {
            if (manyParcodesFlag != 1 && $("[name='oldid']").length == 0) {
                if (typeof userstoreidForUser === 'undefined' || userstoreidForUser === null) {
                    //if "userstoreidForUser" will be empty , use user store for it
                    userstoreidForUser = $('#storeid').val();
                }
                $('#storeid').val(userstoreidForUser).trigger('change');
            }
        }
    }, 1000);
    $('#saveid').on('change', function () {
        var curr = $('#saveid option:selected').data('curr');
        $('#currencyId').val(curr).change();
    });
    //## auto save part ########################################################
    //$(document).on('change', '.autoSaveBillMainPart', function () {
    //dontRepeat is for .autoSaveBillMainPart when change supplier to stop ininite loop of supplierchange
    //changePrice, initialSupp_PriceType = '' are here just to make one order for all parameters sent to change functions
    $('.autoSaveBillMainPart').on('change', function (e, changePrice, initialSupp_PriceType = '', dontRepeat = '') {
        if (activateAutoSave == 1) {

            if (dontRepeat != 'dontRepeat') {
                var tempSaveBillId = Number($('#tempSaveBillId').val());
                var billnameid = Number($('#billnameid').val());
                var supplier = Number($('#supplier').val());
                var itemid = $(this).attr('id');
                var itemval = $(this).val();
                var bns = $('#bns').val();
                var bn = $('#bn').val();
                var storeid = Number($('#storeid').val());
                var saveid = $('#saveid').val();
                var distype = Number($('#distype').val());
                var hasOldBills = 0;
                if (itemid.startsWith("s2id_")) {//stop duplicate trigger from div created by select2
                    return false;
                }
                if ((itemid == "supplier" && supplier < 1) || (itemid == "storeid" && storeid < 1)) {//and stop updating supplier or store when still adding client
                    return false;
                }
                var asyncVal = true;
                if (itemid == "supplier") {
                    asyncVal = false;
                    $.ajax({
                        type: 'POST',
                        url: 'sellbillAjaxController.php?do=checkForOldBill',
                        data: { billnameid: billnameid, supplier: supplier },
                        async: asyncVal,
                        success: function (data) {
                            if (data == -1) {//has no old bills
                                allowSupplierChange = 1;
                                $("#supplier").trigger('change', ['yes', $('#initialSupp_PriceType').val(), 'dontRepeat']);
                                //return false;
                            } else {
                                hasOldBills = 1;
                                $("#oldAutoSaveBillDataForm").html(data);
                                $("#oldAutoSaveBillDataModal").modal('show');
                                return false;
                            }
                        }
                    });
                }

                if (itemid == "pricetype") {//this affect rows
                    //no need to trigger change for $('.autoSaveBillRow'),$('.autoSaveBillRowRet') as choose supplier chage store that change store in each row And that trigger it
                } else {
                    if (hasOldBills == 0) {
                        $.ajax({
                            type: 'POST',
                            url: 'sellbillAjaxController.php?do=autoSaveBill',
                            data: { billnameid: billnameid, tempSaveBillId: tempSaveBillId, supplier: supplier, itemid: itemid, itemval: itemval, bns: bns, bn: bn, storeid: storeid, saveid: saveid, distype: distype },
                            async: asyncVal,
                            success: function (data) {
                                $("#tempSaveBillId").val(Number(data));
                            }
                        });
                    }
                }
            } else {
                allowSupplierChange = 0;
            }
        }
    });
    $('.autoSaveBillRow').live('change', function () {
        var tempSaveBillId = Number($('#tempSaveBillId').val());
        if (tempSaveBillId > 0) {
            var itemid = $(this).attr('id');
            var itemval = $(this).val();
            var distype = Number($('#distype').val());
            var billnameid = Number($('#billnameid').val());
            var pricetype = Number($('#pricetype').val());
            var storeid = $('#storeid').val();
            var itr = $(this).parents('tr').first().find('[id^="proprice"]:input')[0].getAttribute('id').substr(8);
            var productId = Number($('#product' + itr).val());
            if (itemid.startsWith("s2id_") || productId < 1) {//stop duplicate trigger from div created by select2//or empty product
                return false;
            }
            if (itemid.startsWith("prstorid") && Number(itemval) < 1) {//and stop updating supplier or store when still adding client
                return false;
            }
            var rowType = 0; //sell

            //
            //serialize all the form-elements within a div. only
            var rowData = $(this).parents('tr').first().find('select, textarea, input').serializeArray();
            rowData.push({ name: "tempSaveBillId", value: tempSaveBillId });
            rowData.push({ name: "rowType", value: rowType });
            rowData.push({ name: "distype", value: distype });
            rowData.push({ name: "billnameid", value: billnameid });
            rowData.push({ name: "itr", value: itr });
            rowData.push({ name: "itemId", value: itemid });
            rowData.push({ name: "pricetype", value: pricetype });
            rowData.push({ name: "storeid", value: storeid });
            var asyncVal = true;
            if (itemid.startsWith("parcode") || itemid.startsWith("proprice")) {//for event of getting product using parcode make double insert
                asyncVal = false;
            }
            $.ajax({
                type: 'POST',
                url: 'sellbillAjaxController.php?do=autoSaveBillDetails',
                data: rowData,
                async: asyncVal,
                success: function (data) {
                    $("#tempSaveBillIdRow" + itr).val(Number(data));
                    if (itemid.startsWith("product")) {
                        $('#parcode' + itr).trigger('change'); //to save new parcode
                    }
                }
            });
        }
    });
    $('.autoSaveBillRowRet').live('change', function () {
        var tempSaveBillId = Number($('#tempSaveBillId').val());
        if (tempSaveBillId > 0) {
            var itemid = $(this).attr('id');
            var itemval = $(this).val();
            var distype = Number($('#distype').val());
            var billnameid = Number($('#billnameid').val());
            var pricetype = Number($('#pricetype').val());
            var storeid = $('#storeid').val();
            var itr = $(this).parents('tr').first().find('[id^="returnproprice"]:input')[0].getAttribute('id').substr(14);
            var productId = Number($('#returnproduct' + itr).val());
            if (itemid.startsWith("s2id_") || productId < 1) {//stop duplicate trigger from div created by select2//or empty product
                return false;
            }
            if (itemid.startsWith("reprstorid") && Number(itemval) < 1) {//and stop updating supplier or store when still adding client
                return false;
            }
            var rowType = 1; //Ret
            //
            //
            //serialize all the form-elements within a div. only
            var rowData = $(this).parents('tr').first().find('select, textarea, input').serializeArray();
            rowData.push({ name: "tempSaveBillId", value: tempSaveBillId });
            rowData.push({ name: "rowType", value: rowType });
            rowData.push({ name: "distype", value: distype });
            rowData.push({ name: "billnameid", value: billnameid });
            rowData.push({ name: "itr", value: itr });
            rowData.push({ name: "itemId", value: itemid });
            rowData.push({ name: "pricetype", value: pricetype });
            rowData.push({ name: "storeid", value: storeid });
            var asyncVal = true;
            if (itemid.startsWith("returnparcode") || itemid.startsWith("returnproprice")) {//for event of getting product using parcode make double insert
                asyncVal = false;
            }
            $.ajax({
                type: 'POST',
                url: 'sellbillAjaxController.php?do=autoSaveBillDetails',
                data: rowData,
                async: asyncVal,
                success: function (data) {
                    $("#tempSaveBillIdRowRet" + itr).val(Number(data));
                    if (itemid.startsWith("returnproduct")) {
                        $('#returnparcode' + itr).trigger('change'); //to save new parcode
                    }
                }
            });
        }
    });
    //$('.autoDelBillRow').live('click', function () {
    autoDelBillRowFunc = function (thisIs) {

        var tempSaveBillId = Number($('#tempSaveBillId').val());
        var billnameid = Number($('#billnameid').val());
        var itr = thisIs.parents('tr').first().find('[id^="proprice"]:input')[0].getAttribute('id').substr(8);
        var tempSaveBillIdRow = Number($('#tempSaveBillIdRow' + itr).val());
        if (tempSaveBillId > 0 && tempSaveBillIdRow > 0) {
            $.ajax({
                type: 'POST',
                url: 'sellbillAjaxController.php?do=autoDelBillRow',
                data: { tempSaveBillId: tempSaveBillId, billnameid: billnameid, id: tempSaveBillIdRow },
                async: true,
                success: function (data) {

                }
            });
        }
    }
    //$('.autoDelBillRowRet').live('click', function () {
    autoDelBillRowRetFunc = function (thisIs) {
        var tempSaveBillId = Number($('#tempSaveBillId').val());
        var billnameid = Number($('#billnameid').val());
        var itr = thisIs.parents('tr').first().find('[id^="returnproprice"]:input')[0].getAttribute('id').substr(14);
        var tempSaveBillIdRowRet = Number($('#tempSaveBillIdRowRet' + itr).val());
        if (tempSaveBillId > 0 && tempSaveBillIdRow > 0) {
            $.ajax({
                type: 'POST',
                url: 'sellbillAjaxController.php?do=autoDelBillRow',
                data: { tempSaveBillId: tempSaveBillId, billnameid: billnameid, id: tempSaveBillIdRowRet },
                async: true,
                success: function (data) {

                }
            });
        }
    }
    $('.autoSaveOldBillActionBtn').on('click', function () {
        var thisBtn = $(this);
        if (!thisBtn.hasClass('processing...')) {
            var bill_is = $('#bill_is_hidden').val();
            var bill_is_id = $('#bill_is_hidden_id').val();
            var tempSaveBillId = $('#tempSaveBillId').val();
            var supplier = $('#supplier').val();
            var autoSaveOldBillAction = $('[name="autoSaveOldBillAction"]:checked').val();
            $.ajax({
                type: 'POST',
                url: 'sellbillAjaxController.php?do=autoSaveOldBillAction',
                data: { bill_is: bill_is, bill_is_id: bill_is_id, tempSaveBillId: tempSaveBillId, supplier: supplier, autoSaveOldBillAction: autoSaveOldBillAction },
                async: false,
                success: function (data) {
                    if (Number(data) > 0) {
                        window.location.href = window.location.href; //+ "&client=" + supplier;// + "&bill=" + data + "&type" + bill_is;
                    } else {
                        alert('تأكد من بيانات الفواتير والمطلوب وحاول مرة اخرى');
                        thisBtn.removeClass('processing...');
                    }
                }
            });
        }
    });
    if (Number($('#tempSaveBillId').val()) < 1) {
        //$('.autoSaveBillMainPart:first').trigger('change');//no need as storeid always triggered change twice
    }
    //##########################################################################
    sumProDis = function () {
        let totalProDis = 0;
        $('.sumProDis').each(function () {
            let currentId = $(this).attr('id');
            let itr = currentId.substr(6);
            let pronum = $('#pronum' + itr).val();
            let discount = Number($('#selldiscount' + itr).val());
            if (!discount)
                discount = 0;
            let totalDis = discount * pronum;
            // $(this).val(discount * pronum);
            totalProDis = totalProDis + totalDis;
        });
        $('#totalProDis').val(totalProDis);
        $('#productDis').html(totalProDis);
    }

    calcMed = function () {
        let manage_ex = med_hallmark = 0;
        let totalBill = Number($('#gentotal').html());
        med_hallmark = totalBill / 100;
        if (med_hallmark > 20)
            med_hallmark = 20;
        $('#med_hallmark').val(med_hallmark.toFixed(2));

        let itr = $('#hidden_itr').val();
        $('.editTotal').each(function () {
            let id = $(this).attr('id');
            itr = id.substr(15);
            currentId = id.slice(0, 15);
            if (currentId == "hidden_prototal") {
                var prototal = $(this).val();
                var productId = Number($('#product' + itr).val());
                if (productId) {
                    $.post('sellbillAjaxController.php?do=getProductCatId', { productId: productId }, function (data) {
                        if (Number(data) > 0) {
                            if (data != $('#medExCat').val()) {
                                manage_ex = manage_ex + Number(prototal);
                                $('#manage_ex').val(manage_ex);
                            }
                        }
                    });
                }
            }
        });
    }
});


// Fill from price offer
$(document).on('click', ".addFromPriceOffer", function () {
    $('#fillPriceOfferModal').modal('show');
    $.post('priceoffersControllerAjax.php?do=getLastOffers', function (data) {
        $('#offersModalDiv').html(data);
    });

});
$(document).on('click', "#addOfferData", function () {
    let offerId = $('#priceOfferId').val();
    $.post('priceoffersControllerAjax.php?do=getOffer', { id: offerId }, function (data) {
        let res = JSON.parse(data);
        if (res && res.length > 0) {
            for (let i = 0; i < res.length; i++) {
                let proid = res[i].productid;
                let proName = res[i].productname;
                let proPrice = res[i].sellprice;
                let proNum = res[i].pronumber;
                let proTotalPrice = res[i].totalprice;

                if (proid > 0) {
                    var lastRow = $('#containerpros tr:last').attr('id');
                    var lastitr = lastRow.substr(10);
                    if ($('#product' + lastitr).val() != '') {
                        $("#addpro").trigger('click');
                    }

                    var lastRow = $('#containerpros tr:last').attr('id');
                    var newitr = lastRow.substr(10);
                    $('#proprice' + newitr).val(getValueInTermsOfSelectedCurrency(proPrice));
                    $('#pronum' + newitr).val(proNum);
                    $('#hidden_prototal' + newitr).val(proTotalPrice);
                    $('#pronum' + newitr).keyup();
                    // alert(newitr);
                    $('#product' + newitr).select2('data', {
                        id: proid, text: proName
                        , proUnitBuyPrice: proPrice
                        , price: proPrice
                        , productquantity: proNum,
                        fromOfferPrice: 1
                    }, true);
                }
            }

            $('#offersModalDiv').html('');
            $('#fillPriceOfferModal').modal('hide');


        } else
            alert("عرض السعر غير موجود");
    });

});
$(document).on('click', ".slctOffer", function () {
    var offerId = $(this).attr('data-offerId');
    offerCount = $('#offerProCount_' + offerId).val();
    for (let i = 1; i <= offerCount; i++) {
        let proid = $('#offerproid_' + i + '_' + offerId).val();
        let proName = $('#offerproname_' + i + '_' + offerId).val();
        let proPrice = $('#offerprice_' + i + '_' + offerId).val();
        let proNum = $('#offerpronumber_' + i + '_' + offerId).val();
        let proTotalPrice = $('#offertotalprice_' + i + '_' + offerId).val();

        if (proid > 0) {
            var lastRow = $('#containerpros tr:last').attr('id');
            var lastitr = lastRow.substr(10);
            if ($('#product' + lastitr).val() != '') {
                $("#addpro").trigger('click');
            }

            var lastRow = $('#containerpros tr:last').attr('id');
            var newitr = lastRow.substr(10);
            $('#proprice' + newitr).val(getValueInTermsOfSelectedCurrency(proPrice));
            $('#pronum' + newitr).val(proNum);
            $('#hidden_prototal' + newitr).val(proTotalPrice);
            $('#pronum' + newitr).keyup();
            // alert(newitr);
            $('#product' + newitr).select2('data', {
                id: proid, text: proName
                , proUnitBuyPrice: proPrice
                , price: proPrice
                , productquantity: proNum,
                fromOfferPrice: 1
            }, true);
        }
    }

    $('#offersModalDiv').html('');
    $('#fillPriceOfferModal').modal('hide');
});


function checkInUse() {
    var product_store_arr = {}; //object not array
    var itr = $('#hidden_itr').val();
    var flag = 0;
    for (var i = 0; i <= itr; i++) {
        if ($('#product' + i).length > 0 && (Number($('#product' + i).val()) > 0 || $('#product' + i).val().indexOf("hasSizeColor") == 0)
            && (($('#storeid').length > 0 && Number($('#storeid').val()) > 0) || $('#prstorid' + i).length > 0 && Number($('#prstorid' + i).val()) > 0)) {
            var product_id = Number($('#product' + i).val());
            if ($('#product' + i).val().indexOf("hasSizeColor") == 0) {
                product_id = $('#product' + i).val();
            }

            if ($('#prstorid' + i).length > 0 && Number($('#prstorid' + i).val()) > 0) {
                var store_id = Number($('#prstorid' + i).val());
            } else {
                var store_id = Number($('#storeid').val());
            }

            var unit_id = Number($('#productunit' + i).val());
            var quantity = Number($('#pronum' + 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);
    $.ajax({
        type: "POST",
        url: 'sellbillAjaxController.php?do=checkStoreDetail',
        data: { product_store_arr: product_store_arr },
        async: false,
        success: function (data) {
            if (data == 1) {
                flag = 1;
                $('#check_store_msg').html("برجاء الانتظار قليلاً والمحاولة مرة أخرى");
                $('#check_store_div').show();
                alert("برجاء الانتظار قليلاً والمحاولة مرة أخرى");
            } else {
                $('#check_store_div').hide();
            }
        }
    });
    return flag;
}

function markStoreDetailInUse() {
    var product_store_arr = {}; //object not array
    var itr = $('#hidden_itr').val();
    var flag = 0;
    for (var i = 0; i <= itr; i++) {
        if ($('#product' + i).length > 0 && (Number($('#product' + i).val()) > 0 || $('#product' + i).val().indexOf("hasSizeColor") == 0)
            && (($('#storeid').length > 0 && Number($('#storeid').val()) > 0) || $('#prstorid' + i).length > 0 && Number($('#prstorid' + i).val()) > 0)) {
            var product_id = Number($('#product' + i).val());
            if ($('#product' + i).val().indexOf("hasSizeColor") == 0) {
                product_id = $('#product' + i).val();
            }

            if ($('#prstorid' + i).length > 0 && Number($('#prstorid' + i).val()) > 0) {
                var store_id = Number($('#prstorid' + i).val());
            } else {
                var store_id = Number($('#storeid').val());
            }

            var unit_id = Number($('#productunit' + i).val());
            var quantity = Number($('#pronum' + 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);
    $.ajax({
        type: "POST",
        url: 'sellbillAjaxController.php?do=markStoreDetailInUse',
        data: { product_store_arr: product_store_arr },
        async: false,
        success: function (data) {
        }
    });
}