// JavaScript Document
//here all method and function that control bill

var returncalcuproduct;
var returntotalprice;
var returnaddrow;
var hideBillPrices = document.getElementById("hideBillPrices").value;
var addServiceToBill = Number($('#addServiceToBill').val());


//the common itration and the start // 2
$raw_i = Number(document.getElementById("returnhidden_itr").value) + 1;
var scunitname = $('#scunitnamevalue').val();
var showPrevDiscount = Number($('#showPrevDiscount').val());

//alert($raw_i);
//the tabindex to increment in dynmaic load
$rtabindexnum = 302;



jQuery(document).ready(function () {

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

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



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

        $("#addunit").empty();

        returnaddrow($raw_i, $rtabindexnum);

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

        // incrementaion of row number and tab index
        $raw_i++
        $rtabindexnum++;

        //reload the dropdownlist and jquery files
        $('select').select2();


        return false;

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




    //add new row in bill
    /**************************/
    returnaddrow = function ($aw_i, $tabindexnum) {
        var settingparcode = document.getElementById("settingparcode").value;
        var settingdiscount = document.getElementById("settingdiscount").value;
        var settingcomment = document.getElementById("settingcomment").value;
        var settingUnit = document.getElementById("settingUnit").value;
        var morestore = document.getElementById("morestore").value;
        var userstoreid = document.getElementById("userstoreid").value;

        var discountrowtype = document.getElementById("discountrowtype").value;
        var shownumber = document.getElementById("shownumber").value;
        var hideBillPricesClass = '';
        if (hideBillPrices == 1) {
            hideBillPricesClass = 'hidden';
        }

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

        $xx += '<span class="proDetails" data-pro="returnproduct' + $aw_i + '">' + $aw_i + '</span></td>';

        //# check to hide
        var hidden_parcode = '';
        $('#containerReturn .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 += '<td class="' + proSellTrackingSerialClassVar + '">' +
                '      <input type="text" name="retproSellTrackingSerial' + $aw_i + '" id="retproSellTrackingSerial' + $aw_i + '"  class="form-control txt-nonraduis autoSaveBillRowRet" tabindex="7"  size="3"/>' +
                ' </td>';
        if (settingparcode == 0) {
            $xx += '<td class="' + hidden_parcode + '">';
        } else {
            $xx += '<td  class="' + hidden_parcode + '">';
        }


        $xx += '<div id="returnproductparcode' + $aw_i + '">'
                + '<input type="text" name="returnparcode' + $aw_i + '" id="returnparcode' + $aw_i + '" type="text" tabindex="' + $tabindexnum + '"   class="form-control txt-nonraduis autoSaveBillRowRet" placeholder="الباركود" onkeypress="getreturnproductbyParcode(event, this.value,' + $aw_i + ');" tabindex="301"/>'

                + ' <input name="returnparcodeType' + $aw_i + '" id="returnparcodeType' + $aw_i + '" type="hidden"/> '

                + ' <input name="returnproductserailid' + $aw_i + '" id="returnproductserailid' + $aw_i + '" type="hidden" /> '

                + '</div>'
                + '</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="reprstoridsiv' + $aw_i + '">'
                    + ' <select class="select2 wdt100 clientstore autoSaveBillRowRet" name="reprstorid' + $aw_i + '" id="reprstorid' + $aw_i + '" >'
                    + $("#addstore").html()
                    + '   </select>'
                    + '  </div></td>';
        } else if (userstoreid != 0) {
            //alert(11111);
            $xx += '<td class="' + $storeClass + '"> <div id="prstoridsiv' + $aw_i + '">'
                    + ' <input name="reprstorid' + $aw_i + '" id="reprstorid' + $aw_i + '" class="clientstore autoSaveBillRowRet" type="hidden" value="' + $('#userstoreidForClient').val() + '" />'
                    + $("#addstore2").html()

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

        $xx += '<td>'
                + '<div id="returnproductdiv' + $aw_i + '">'
                + '  <input type="hidden" id="returnproduct' + $aw_i + '" name="returnproduct' + $aw_i + '"  class="select2returnproduct' + $aw_i + ' wdt100 autoSaveBillRowRet"  data-placeholder="اختر منتج" tabindex="' + $tabindexnum + '" />'

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


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

        $xx += '<textarea class="form-control txt-nonraduis returnenteraction autoSaveBillRowRet"  name="returncomment' + $aw_i + '" id="returncomment' + $aw_i + '" rows="1" tabindex="' + $tabindexnum + '"></textarea>'
                + '</td>';

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

        var hidden_Height = '';
        $('#containerReturn .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 = '';
        $('#containerReturn .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 = '';
        $('#containerReturn .check_tr_quantity:first').each(function (e) {
            var ths = $(this);
            if (ths.hasClass('hidden')) {
                hidden_quantity = 'hidden';
                return false;
            }
        });

        if (settingUnit == 0) {
            $xx += '<td class="' + hidden_unit + '">';
        } else {
            $xx += '<td  class="' + hidden_unit + '">';
        }



        $xx += '<div id="returnproductunitdiv' + $aw_i + '">'
                + '<input type="hidden" name="retProNum' + $aw_i + '" id="retProNum' + $aw_i + '" value=""/>'
                + '<select id="returnproductunit' + $aw_i + '" name="returnproductunit' + $aw_i + '" class="select2 wdt100 autoSaveBillRowRet" tabindex="' + $tabindexnum + '">'
                + $("#addunit").html()
                + '</select>'
                + '</div>'
                + '</td> '


        $xx += '<td class="wdt100n check_tr_Height ' + hidden_Height + '">'
                + '                    <input type="text" name="returnproHeight' + $aw_i + '" id="returnproHeight' + $aw_i + '"  value="1" class="form-control txt-nonraduis enteraction numberinput positivefloat autoSaveBillRowRet" onKeyUp="calcQuantityReturn(' + $aw_i + ', event);" tabindex="301" />'
                + '                </td>'
                + '<td class="wdt100n check_tr_Width ' + hidden_Width + '">'
                + '                    <input type="text" name="returnproWidth' + $aw_i + '" id="returnproWidth' + $aw_i + '"  value="1" class="form-control txt-nonraduis enteraction numberinput positivefloat autoSaveBillRowRet" onKeyUp="calcQuantityReturn(' + $aw_i + ', event);" tabindex="301" />'
                + '                </td>';

        $xx += '<td class="' + hidden_quantity + '">'
                + '<input type="text" name="returnpronum' + $aw_i + '" id="returnpronum' + $aw_i + '"  class="form-control txt-nonraduis getreurnprototal returnenteraction numberinput ' + numClass + ' autoSaveBillRowRet" onKeyUp="returncheckquantity(' + $aw_i + ', event);" value="1" tabindex="' + $tabindexnum + '"/>'
                + '</td>';

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

        } else {
            $xx += '<td ><input name="returnscunitname' + $aw_i + '" id="returnscunitname' + $aw_i + '" value="0" class="form-control  txt-nonraduis  numberclic   positiveNo autoSaveBillRowRet" type="text" tabindex="' + $tabindexnum + '"  /></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>';

        $xx += '<td class="showrowPriceType ' + hidden_RowPriceType + '">' +
                '   <select class="select2 wdt100 autoSaveBillRowRet" name="retpricetypepro' + $aw_i + '" id="retpricetypepro' + $aw_i + '">' +
                priceOptions +
                '   </select>' +
                '</td>';

        $xx += '<td class="' + hideBillPricesClass + '">'
                + ' <div id="returnpropricechange' + $aw_i + '">'
                + '<input type="text" name="returnproprice' + $aw_i + '" id="returnproprice' + $aw_i + '"  class="form-control getreurnprototal txt-nonraduis returnenteraction numberinput positivefloat autoSaveBillRowRet" value="0" tabindex="' + $tabindexnum + '" />'
                + '</div>'
                + '</td>';



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


        $xx += '<td  class="' + hidden_discount + ' ' + hideBillPricesClass + '">';

        $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="returnprodis' + $aw_i + '" id="returnprodis' + $aw_i + '" class="form-control getreurnprototal  txt-nonraduis returnenteraction numberinput positiveNo autoSaveBillRowRet ' + $cashDiscountClass + '" value="0" tabindex="' + $tabindexnum + '" type="text"/>';
        $xx += '<input name="returndiscounttype' + $aw_i + '" id="returndiscounttype' + $aw_i + '" class="form-control getreurnprototal  txt-nonraduis returnenteraction numberinput positiveNo autoSaveBillRowRet ' + $PercentageDiscountClass + '" value="0" tabindex="' + $tabindexnum + '" type="text"/>';
        $xx += '<span class="input-group-addon small-addon retdiscountSpan" data-itr="' + $aw_i + '">' + $discountSpanHtml + '</span>';
        $xx += ' </div> </td>';


        $xx += '<td class="' + hideBillPricesClass + '">'
                + '<input  name="returnhidden_prototal' + $aw_i + '" id="returnhidden_prototal' + $aw_i + '" class="returnEditTotal 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="proSerialsRet' + $aw_i + '" id="proSerialsRet' + $aw_i + '" data-itr="' + $aw_i + '" class="autoSaveBillRowRet" value=""/> '
                + '</td>'
        $xx += '<td>'
                + '<input type="hidden" name="tempSaveBillIdRowRet' + $aw_i + '" id="tempSaveBillIdRowRet' + $aw_i + '" value="0">'
                + '<button type="button" id="returnremove' + $aw_i + '" class="close flt-none returnremoveproduct autoDelBillRowRet" aria-hidden="true">&times;</button>'
                + '</td>'


                + '</tr>';



        $("#containerReturn").append($xx);
        $(".positiveNo").forcepositiveNum();
        $(".numberinput").forceNumeric();
        $(".positivefloat").forcepositivefloat();
        $("#retpricetypepro" + $aw_i).val($("#pricetype").val());
        $("#proSerialsRet" + $aw_i).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: $('#returnproduct' + $aw_i).val(),
                        store: $('#reprstorid' + $aw_i).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($('#returnproductunit' + itr + ' :selected').data('pu-num'));
            var quantity = Number($('#returnpronum' + 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');
                }
            }
        });

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


        if (morestore == 0) {
            // alert('in if');
            $(".select2returnproduct" + 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("reprstorid" + n).value,
                            hiddenpricetype: document.getElementById("retpricetypepro" + 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');
            });
        } else {
            // alert('in else');
            //assign select2 properties
            $(".select2returnproduct" + 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("retpricetypepro" + n).value, //pricetype
                            suppplier: document.getElementById("supplier").value,
                            searchWithCatAndProductNameOnly: document.getElementById("searchWithCatAndProductNameOnly").value,
                        };
                    },
                    results: function (data) {
                        //alert("data: "+data);
                        return {results: data};
                    }
                },
                formatResult: rformatResult,
                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')
            //            $("#reprstorid" + $aw_i).select2('data', {id: storeidData.id, text: storeidData.text});
            $("#reprstorid" + $aw_i).val($("#storeid").val()).trigger('change.select2');
        }

        //action in change of created dropdown list  to load the price
        $("#returnproduct" + n).change(function () {

            var pricetype = document.getElementById("retpricetypepro" + 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, 1);
                //var storeid = document.getElementById("storeid").value;

                //using the load method to load the price
                // $("#returnproductunitdiv"+n).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 = $("#returnparcode" + n).val();
                }

                //alert(''+productpricepagename+'?do=getreturnunit&itrs='+n+'&tabindex='+tbindexn+'&productid='+theselectedvalue+ '&pricetype='+pricetype+'&clientid='+supplier+'&parcode='+productParcode);
                $.ajax({
                    url: '' + productpricepagename + '?do=getreturnunit&itrs=' + n + '&tabindex=' + tbindexn + '&productid=' + theselectedvalue + '&pricetype=' + pricetype + '&clientid=' + supplier + '&parcode=' + productParcode + '&billnameid=' + $('#billnameid').val(),
                    type: "get",
                    success: function (data) {
                        var response = $.parseJSON(data);
                        //	alert(response.unitString);
                        //alert(n+'sssssssss');
                        //alert(response.unitString);
                        //populate unit
                        $('#returnproductunitdiv' + n).html(response.unitString);
                        $("#addunit").empty();
                        //$("#returnproductunitdiv1 option").clone().appendTo("#addunit");

                        //populate buy price
                        //alert(response.priceString);
                        $('#returnpropricechange' + n).html(response.priceString);
                        //--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) {
                                $('#returnproprice' + n).val(WeightPricePart);
                                $('#returnpronum' + n).val(1);
                            }
                        }
                        //change price of product from main curr to slected curr val
                        $('#returnproprice' + n).val(getValueInTermsOfSelectedCurrency($('#returnproprice' + n).val()));
                        //----


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

                        var returnproductpricetype = document.getElementById("returnproductpricetype" + n).value;


                        if (returnproductpricetype == 1) {
                            $('#returnproprice' + n).css("background-color", "#B7DFA4");
                            $('#returnpropricechange' + n).css("background-color", "#B7DFA4");


                        } else {
                            $('#returnproprice' + n).css("background-color", "#FFF");
                            $('#returnpropricechange' + n).css("background-color", "#FFF");
                        }


                        var priceupdate = document.getElementById("priceupdate").value;
                        if (priceupdate == 0) {
                            //alert(0);
                            $('#returnproprice' + n).prop('readonly', true);
                            $('#returnhidden_prototal' + n).prop('readonly', true);
                        } else {
                            //alert(1);
                            $('#returnproprice' + n).prop('readonly', false);
                            $('#returnhidden_prototal' + n).prop('readonly', false);
                        }

                        if (showPrevDiscount == 1 && $('#retLastClientDisVal' + n).length > 0) {
                            $('#returnprodis' + n).val($('#retLastClientDisVal' + n).val());
                            $('#returndiscounttype' + n).val($('#retLastClientDisPer' + n).val());
                        }

                        $('#returnproductparcode' + n).html(response.parcodeString);
                        //alert(response.priceString)

                        var returnparcodeType = document.getElementById("returnparcodeType" + n).value;

                        if (returnparcodeType == "serialnumber") {
                            $('#returnpronum' + n).val(1);
                            //$('#returnpronum'+n).attr('readonly', true);
                        } else {
                            $('#returnpronum' + n).attr('readonly', false);
                        }

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

                        //document.getElementById("returnproprice"+n).value=0;
                        document.getElementById("returnpronum" + n).value = 1;
                        document.getElementById("returnprodis" + n).value = 0;

                        if ($('#retOnlySoldProducts').val() == 1 && $("#supplier").val() > 1 && returnproductpricetype != 1) {//sold befor//$('#returnproprice' + n).css('background-color') == 'rgb(183, 223, 164)') {
                            alert('لا يمكن رد هذا المنتج حيث ان هذا العميل لم يشتريه مسبقا');
                            $('#returnremove' + n).click();
                        }
                        //to calculate the price and amount with discount
                        returncalcuproduct(n);

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

                        totalprice();

                        //get the general discount
                        thegeneraldiscount();

                        checkthepayed();

                        //get the general payed
                        thegeneralpayed();

                        // calculate the rest of debt
                        therestofdebt();

                        //getreturnunitprice(n);

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


                        if ((Number($raw_i) - Number(n)) == 1) {

                            $("#addunit").empty();

                            returnaddrow($raw_i, $rtabindexnum);


                            if (settingQuantitiyFocus == 0 && returnparcodeType != "serialnumber") {
                                $("#returnpronum" + n).focus();
                                $("#returnpronum" + n).select();
                            } else {
                                $("#returnparcode" + $raw_i).focus();
                                $("#returnparcode" + $raw_i).select();
                            }


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


                            // incrementaion of row number and tab index
                            $raw_i++
                            $rtabindexnum++;

                        } else {
                            if (settingQuantitiyFocus == 0 && returnparcodeType != "serialnumber") {
                                $("#returnpronum" + n).focus();
                                $("#returnpronum" + n).select();
                            } else {
                                $("#returnparcode" + $raw_i).focus();
                                $("#returnparcode" + $raw_i).select();
                            }
                        }

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

            }


        });


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





    // the delete action that delete row of products
    /************************/
    $(document).on('click', '.returnremoveproduct', function () {
        autoDelBillRowRetFunc($(this));
        // delete by partents
        $(this).parent().parent().remove();

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

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

        totalprice();

        //get the general discount
        thegeneraldiscount();


        checkthepayed();

        //get the general payed
        thegeneralpayed();

        // calculate the rest of debt
        therestofdebt();


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

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

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

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

        //the number of ilteration
        var thecolnmu = 0;

        //see what chase
        switch (newword) {
            case "returnprop":
                thecolnmu = currentId.substr(14);
                break;
            case "returnpron":
                // if ($('#enablequantityfractions').val() != 1) {
                //     if ($(this).val() % 1 > 0)
                //         $(this).val(Math.round($(this).val())).keyup();
                // }
                thecolnmu = currentId.substr(12);
                break;
            case "returnprod":
                thecolnmu = currentId.substr(12);
                break;
            default:
                thecolnmu = 0;
        }


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

        // get the total price of product
        returntotalprice($raw_i);

        totalprice();

        //get the general discount
        thegeneraldiscount();

        checkthepayed();

        //get the general payed
        thegeneralpayed();

        // calculate the rest of debt
        therestofdebt();

    });
    /************************/
    $(document).on('keyup', ".returnEditTotal", function () {

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

        //get the num from this method
        var thecolnmu = currentId.substr(21);

        var totalVal = $(this).val();
        var pronum = $("#returnpronum" + thecolnmu).val();

        var prodis = $("#returnprodis" + thecolnmu).val();
        if (prodis == 0) {
            $("#returnproprice" + thecolnmu).val(totalVal / pronum);
        } else {
            $("#returnproprice" + thecolnmu).val((+totalVal + +prodis) / pronum);
        }
        //change price of product from main curr to slected curr val
        $('#returnproprice' + thecolnmu).val(getValueInTermsOfSelectedCurrency($('#returnproprice' + thecolnmu).val()));
        //get the total price of sell
        returntotalprice($aw_i);

        // get the total price of sell and return sell
        totalprice();
        //get the general discount
        thegeneraldiscount();


    });




    var rformatResult = function (data) {

        //return  data.text ;
        //return  data.text+'<span   style="margin-right:50px;" >'+data.productquantity+'</span ><span   style="margin-right:50px;" > '+data.price+'';
        //return  data.text + '<span  style="text-align: left;  float: left;  width: 30%;">' + data.price + '</span ><span  style="float: left;  margin-left: 5px;"  > ' + data.productquantity + '';
        //
        //        var cfactor = $('#currencyId').select2("data").element[0].attributes['data-cfactor'].value;
        var cfactor = $('#cFactor').val();
        data.price = Number((data.price * cfactor).toFixed(4));


        $choice = data.text;
        if (hideBillPrices != 1)
            $choice += '<span style="text-align: left;  float: left;  width: 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>';
        }
        return $choice;
    }

    //alert(22);
    var morestore = document.getElementById("morestore").value;
    //storeid: document.getElementById("prstorid"+n).value ,

    if (morestore == 0) {
        //alert('morestore');
        $(".select2returnproduct").select2({
            placeholder: "إسم المنتج",
            //  minimumInputLength: 3,
            minimumInputLength: document.getElementById("searchvalue").value,
            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("reprstorid1").value,
                        hiddenpricetype: document.getElementById("retpricetypepro1").value, //pricetype
                        suppplier: document.getElementById("supplier").value,
                        searchWithCatAndProductNameOnly: document.getElementById("searchWithCatAndProductNameOnly").value,
                    };
                },
                results: function (data) {
                    //alert("data: "+data);
                    return {results: data};
                }
            },
            formatResult: rformatResult,
            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('one '+document.getElementById("storeid").value);
        //assign select2 properties
        $(".select2returnproduct").select2({
            placeholder: "إسم المنتج",
            //  minimumInputLength: 3,
            minimumInputLength: document.getElementById("searchvalue").value,
            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("retpricetypepro1").value, //pricetype
                        suppplier: document.getElementById("supplier").value,
                        searchWithCatAndProductNameOnly: document.getElementById("searchWithCatAndProductNameOnly").value,
                    };
                },
                results: function (data) {
                    //alert("data: "+data);
                    return {results: data};
                }
            },
            formatResult: rformatResult,
            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');
        });
    }



    // here the frist action on frist dropdownlist
    /************************/
    $("#returnproduct1").change(function () {

        var pricetype = document.getElementById("retpricetypepro1").value;//pricetype
        var supplier = document.getElementById("supplier").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, 1);
            //using the load method to load the price
            // $("#returnproductunitdiv1").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 = $("#returnparcode1").val();
            }
            $.ajax({
                url: '' + productpricepagename + '?do=getreturnunit&itrs=1&tabindex=301&productid=' + theselectedvalue + '&pricetype=' + pricetype + '&clientid=' + supplier + '&parcode=' + productParcode + '&billnameid=' + $('#billnameid').val(),
                type: "get",
                success: function (data) {
                    var response = $.parseJSON(data);
                    //populate unit
                    $('#returnproductunitdiv1').html(response.unitString);
                    $("#addunit").empty();
                    $("#returnproductunitdiv1 option").clone().appendTo("#addunit");

                    //populate buy price
                    //alert(response.priceString);
                    $('#returnpropricechange1').html(response.priceString);
                    //--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) {
                            $('#returnproprice1').val(WeightPricePart);
                            $('#returnpronum1').val(1);
                        }
                    }
                    //change price of product from main curr to slected curr val
                    $('#returnproprice1').val(getValueInTermsOfSelectedCurrency($('#returnproprice1').val()));
                    //----
                    $(".positiveNo").forcepositiveNum();


                    var returnproductpricetype = document.getElementById("returnproductpricetype1").value;


                    if (returnproductpricetype == 1) {
                        $('#returnproprice1').css("background-color", "#B7DFA4");
                        $('#returnpropricechange1').css("background-color", "#B7DFA4");
                    } else {
                        $('#returnproprice1').css("background-color", "#FFF");
                        $('#returnpropricechange1').css("background-color", "#FFF");
                    }



                    var priceupdate = document.getElementById("priceupdate").value;
                    if (priceupdate == 0) {
                        //alert(0);
                        $('#returnproprice1').prop('readonly', true);
                        $('#returnhidden_prototal1').prop('readonly', true);
                    } else {
                        //alert(1);
                        $('#returnproprice1').prop('readonly', false);
                        $('#returnhidden_prototal1').prop('readonly', false);
                    }

                    if (showPrevDiscount == 1 && $('#retLastClientDisVal1').length > 0) {
                        $('#returnprodis1').val($('#retLastClientDisVal1').val());
                        $('#returndiscounttype1').val($('#retLastClientDisPer1').val());
                    }

                    $('#returnproductparcode1').html(response.parcodeString);
                    //alert(response.priceString)



                    var returnparcodeType = document.getElementById("returnparcodeType1").value;

                    if (returnparcodeType == "serialnumber") {
                        $('#returnpronum1').val(1);
                        //$('#returnpronum1').attr('readonly', true);
                    } else {
                        $('#returnpronum1').attr('readonly', false);
                    }

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

                    // document.getElementById("returnproprice1").value=0;
                    document.getElementById("returnpronum1").value = 1;
                    document.getElementById("returnprodis1").value = 0;

                    if ($('#retOnlySoldProducts').val() == 1 && $("#supplier").val() > 1 && returnproductpricetype != 1) {//sold befor//$('#returnproprice' + n).css('background-color') == 'rgb(183, 223, 164)') {
                        alert('لا يمكن رد هذا المنتج حيث ان هذا العميل لم يشتريه مسبقا');
                        $('#returnremove1').click();
                    }

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

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

                    totalprice();

                    //get the general discount
                    thegeneraldiscount();


                    checkthepayed();

                    //get the general payed
                    thegeneralpayed();

                    // calculate the rest of debt
                    therestofdebt();

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

                    //daiable price  type
                    //                    $('#pricetype').attr('readonly', true);
                    //                    $("#pricetype").trigger('liszt:updated');


                    document.getElementById("hiddenpricetype").value = document.getElementById("pricetype").value;

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


                    //getreturnunitprice(1);

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

                    if (Number($raw_i) - 1 == 1) {


                        $("#addunit").empty();

                        returnaddrow($raw_i, $rtabindexnum);




                        if (settingQuantitiyFocus == 0 && returnparcodeType != "serialnumber") {
                            $("#returnpronum1").focus();
                            $("#returnpronum1").select();
                        } else {
                            $("#returnparcode" + $raw_i).focus();
                            $("#returnparcode" + $raw_i).select();
                        }


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


                        // incrementaion of row number and tab index
                        $raw_i++
                        $rtabindexnum++;

                    } else {

                        if (settingQuantitiyFocus == 0 && returnparcodeType != "serialnumber") {
                            $("#returnpronum1").focus();
                            $("#returnpronum1").select();
                        } else {
                            $("#returnparcode" + $raw_i).focus();
                            $("#returnparcode" + $raw_i).select();
                        }
                    }


                    //load the jquery checker for number only
                    //$.getScript('../views/default/js/head_scripts.js');

                    $('select').select2();




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

            //using the load method to load the product Unit
            //   $('#returnproductunitdiv1').load(''+productpricepagename+'?do=getreturnunit&itrs=1&tabindex=301&productid='+theselectedvalue+'',function() {//
            //
            //			   $("#addunit").empty();
            //		 $("#returnproductunitdiv1 option").clone().appendTo("#addunit");
            //
            //
            //			   //using the load method to load the parcode
            //			    $('#returnproductparcode1').load(''+productpricepagename+'?do=getreturnparcode&itrs=1&tabindex=301&productid='+theselectedvalue+'',function() {
            //
            //
            //		var returnparcodeType = document.getElementById("returnparcodeType1").value;
            //
            //		if(returnparcodeType == "serialnumber")
            //		{
            //			$('#returnpronum1').val(1);
            //			$('#returnpronum1').attr('readonly', true);
            //		}
            //		else
            //		{
            //			$('#returnpronum1').attr('readonly', false);
            //		}
            //
            //
            //
            //
            //		  //here all code that will happend with loading contants
            //		  //the number of rows of products
            //		  var noitr = document.getElementById("returnhidden_itr").value
            //
            //		  document.getElementById("returnproprice1").value=0;
            //		  document.getElementById("returnpronum1").value=1;
            //		  document.getElementById("returnprodis1").value=0;
            //
            //
            //		  // get the total of product
            //		  returncalcuproduct(1);
            //
            //		  // get the total price of product
            //		  returntotalprice(noitr);
            //
            //		  totalprice();
            //
            //		  //get the general discount
            //		  thegeneraldiscount();
            //
            //
            //		  checkthepayed();
            //
            //		  //get the general payed
            //		  thegeneralpayed();
            //
            //		  // calculate the rest of debt
            //		  therestofdebt();
            //
            //		 //********************************************//
            //
            //			//daiable price  type
            //			$('#pricetype').attr('readonly', true);
            //			$("#pricetype").trigger('liszt:updated');
            //
            //
            //			document.getElementById("hiddenpricetype").value=document.getElementById("pricetype").value;
            //
            //	//********************************************//
            //
            //
            //		  getreturnunitprice(1);
            //
            //		  var settingQuantitiyFocus= document.getElementById("settingQuantitiyFocus").value;
            //
            //		 if(Number($raw_i) - 1  == 1)
            //		{
            //
            //
            //		   $("#addunit").empty();
            //
            //		  returnaddrow($raw_i,$rtabindexnum);
            //
            //
            //
            //
            //			if(settingQuantitiyFocus == 0  && returnparcodeType != "serialnumber")
            //			{
            //				$("#returnpronum1").focus();
            //				$("#returnpronum1").select();
            //			}
            //			else
            //			{
            //				$("#returnparcode"+$raw_i).focus();
            //				$("#returnparcode"+$raw_i).select();
            //			}
            //
            //
            //			// fill the iltration filed with common iltration
            //			document.getElementById("returnhidden_itr").value = $raw_i ;
            //
            //
            //			// incrementaion of row number and tab index
            //			$raw_i++
            //			$rtabindexnum++ ;
            //
            //		}
            //		else
            //		{
            //
            //			if(settingQuantitiyFocus == 0 && returnparcodeType != "serialnumber")
            //			{
            //				$("#returnpronum1").focus();
            //				$("#returnpronum1").select();
            //			}
            //			else
            //			{
            //				$("#returnparcode"+$raw_i).focus();
            //				$("#returnparcode"+$raw_i).select();
            //			}
            //		}
            //
            //
            //		  //load the jquery checker for number only
            //		  $.getScript('../views/default/js/head_scripts.js');
            //
            //		   $('select').select2();
            //				});
            //		   });

        }


    });
    $("#proSerialsRet1").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: $('#returnproduct1').val(),
                    store: $('#reprstorid1').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($('#returnproductunit' + itr + ' :selected').data('pu-num'));
        var quantity = Number($('#returnpronum' + 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
    /************************/
    returntotalprice = function ($ix) {


        // varaible that will carry total price
        var thealltotal = "";
        $round_numbers = $("#round_numbers").val();
        $returnTotalQty = 0;
        //loop to sum the all prices
        for ($x = 1; $x <= $ix; $x++) {
            var numco = $x;
            var inputname = "#returnhidden_prototal" + numco;

            //to make sure that all input is created
            if ($("#returnproduct" + numco).val() == "-1" || $("#returnproduct" + numco).val() == "" || $("#returnproduct" + numco).val() == null) {
                continue;
            } else {
                //Calculate it again to make sure that there are no errors in calculations
                returncalcuproduct(numco);

                if (addServiceToBill == 1 && $("#returnproduct" + numco).select2('data').isService == 1) {
                    //dont count no of servise only value
                } else {
                    $returnTotalQty = $returnTotalQty + Number(document.getElementById("returnpronum" + numco).value);
                }

                // sum method
                thealltotal = Number(thealltotal) + Number(document.getElementById("returnhidden_prototal" + numco).value)

                $round_numbers = $("#round_numbers").val();
                //                if ($round_numbers == 0) //التقريب لأقرب عدد صحيح
                //                {
                //                    thealltotal = Math.round(thealltotal * 100) / 100;
                //                } else //التقريب لأقرب رقم
                //                {
                //                    //alert(thealltotal.toFixed(2));
                //                    //عملت مشكله مش بتقبل .toFixed(2);
                //                    thealltotal = Math.round(thealltotal * 100) / 100;
                //                    //thealltotal =thealltotal.toFixed(2);
                //                }


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

                $("#returnsellbilltotal").html(thealltotal);

                /////////////////////add by sara ////
                document.getElementById("returnsellbillprice").value = thealltotal;


            }
        }

        $("#returnTotalQty").html($returnTotalQty);
        $("#returnsellQuantity").val($returnTotalQty);

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

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


        //insert the value in div
        $("#returnsellbilltotal").html(thealltotal);

        /////////////////////add by sara ////
        document.getElementById("returnsellbillprice").value = thealltotal;

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












    // the main method to calucalte products price
    /***************************/
    returncalcuproduct = function (thecolnmux) {
        //save product number of unit
        $('#retProNum' + thecolnmux).val($('#returnproductunit' + thecolnmux + ' option:selected').data('pu-num'));
        //

        var price = $("#returnproprice" + thecolnmux).val();
        var amount = $("#returnpronum" + thecolnmux).val();
        var pricebefore = price * amount;
        //القيمه المباشره
        var discountbefore = $("#returnprodis" + thecolnmux).val();
        //القيمه النسبيه
        var discounttype = $("#returndiscounttype" + thecolnmux).val();

        var showdiscountrow = $("#showdiscountrow").val();
        //## have to consider row discount type too
        var discountrowtype = $("#discountrowtype").val();
        if ($('#returnprodis' + thecolnmux).is(':visible')) {//means discount is cash , changing to percentage
            discountrowtype = 0;
        } else if ($('#returndiscounttype' + thecolnmux).is(':visible')) {//means discount is percentage , changing to cash
            discountrowtype = 1;
        }
        //##


        var totalpricex;
        /*
         alert('pricebefore'+pricebefore);
         alert('discountbefore'+discountbefore);
         alert('discountrowtype'+discountrowtype);
         */
        ////////////////add by sara////////////////////////////
        if (discountrowtype == 0) {
            if (discountbefore > pricebefore) {
                $("#returnprodis" + thecolnmux).val(pricebefore);
                var discountbefore = Number($("#returnprodis" + thecolnmux).val());


            }
            var totalpricex = pricebefore - discountbefore;

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

            //alert('totalpricex'+totalpricex);
        } else if (Number(discountrowtype) == 1 && Number(showdiscountrow) == 0) {


            if (discounttype > 100) {


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

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

        //var discountnum = discountbefore / 100 ;
        //var discount  = pricebefore * discountnum;




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

        $("#reurnprototal" + thecolnmux).html(totalpricex);

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



    //use enter action do new row
    /*****************************/
    //$(document+ ":not(#product1_chzn a.chzn-single)").keypress(function(e) {
    $(document).on('keypress', ".returnenteraction", function (e) {
        //$(".enteraction").keypress( function(e) {
        //$('input[type=text]').keypress(function(e) {

        if (e.which == 13) {



            //add the new row with itration and with all propperties
            returnaddrow($raw_i, $rtabindexnum);

            //here to make focus in dropdown list
            $('.chzn-single').focus(function (e) {
                e.preventDefault();
            });

            $('#returnproduct' + $raw_i + '_chzn a.chzn-single').focus();
            $('#returnproduct' + $raw_i + '_chzn a.chzn-single').select();

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

            // incrementaion of row number and tab index
            $raw_i++
            $rtabindexnum++;



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

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

            return false;
        }

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



    // using esc to delete row
    /*****************************/
    $(document).keypress(function (e) {
        var elementId = e.srcElement.id;
        //to stop the submit of the form
        if (elementId == "manyParcodes") {
            return true;
        }

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

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

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

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

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

                totalprice();

                //get the general discount
                thegeneraldiscount();

                checkthepayed();

                //get the general payed
                thegeneralpayed();

                // calculate the rest of debt
                therestofdebt();

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




});




function returncheckquantity(i, e) {
    //var currentQuantity= Number(document.getElementById("returnquantity"+i).value);
    //var quantity= Number(document.getElementById("returnpronum"+i).value);

    //if(quantity > currentQuantity)
    //{
    //document.getElementById("returnpronum"+i).value=currentQuantity;
    //}


    var noitr = document.getElementById("returnhidden_itr").value;


    // get the total of product
    returncalcuproduct(i);

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

    totalprice();

    //get the general discount
    thegeneraldiscount();

    checkthepayed();

    //get the general payed
    thegeneralpayed();

    // calculate the rest of debt
    therestofdebt();

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







function getreturnunitprice(n) {
    //alert('n'+n);
    //here  will get the price for every product
    //the selected value in drop down list
    var theselectedvalue = document.getElementById("returnproductunit" + n).value;
    // alert('returnproductunit'+n+theselectedvalue);

    if (theselectedvalue != "") {
        var pricetype = document.getElementById("retpricetypepro" + n).value;//pricetype
        var productid = document.getElementById("returnproduct" + n).value;
        // alert('returnproduct'+n+'='+$('#returnproduct'+n).val());
        //var storeid = document.getElementById("storeid").value;
        var supplier = document.getElementById("supplier").value;


        var x = $("#returnparcode" + n).attr("tabindex");


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


        //  alert(''+productpricepagename+'?do=getreturnpriceByOnlyProduct&itrs='+n+'&tabindex='+x+'&productunit='+theselectedvalue+'&productid='+productid+'&pricetype='+pricetype+'&clientid='+supplier+'');
        $('#returnpropricechange' + n).load('' + productpricepagename + '?do=getreturnpriceByOnlyProduct&itrs=' + n + '&tabindex=' + x + '&productunit=' + theselectedvalue + '&productid=' + productid + '&pricetype=' + pricetype + '&clientid=' + supplier + '', function () {



            var returnproductpricetype = document.getElementById("returnproductpricetype" + n).value;


            if (returnproductpricetype == 1) {
                $('#returnproprice' + n).css("background-color", "#B7DFA4");
                $('#returnpropricechange' + n).css("background-color", "#B7DFA4");


            } else {
                $('#returnproprice' + n).css("background-color", "#FFF");
                $('#returnpropricechange' + n).css("background-color", "#FFF");
            }



            var priceupdate = document.getElementById("priceupdate").value;
            if (priceupdate == 0) {
                //alert(0);
                $('#returnproprice' + n).prop('readonly', true);
                $('#returnhidden_prototal' + n).prop('readonly', true);
            } else {
                //alert(1);
                $('#returnproprice' + n).prop('readonly', false);
                $('#returnhidden_prototal' + n).prop('readonly', false);
            }

            if ($('#retOnlySoldProducts').val() == 1 && $("#supplier").val() > 1 && returnproductpricetype != 1) {//sold befor//$('#returnproprice' + n).css('background-color') == 'rgb(183, 223, 164)') {
                alert('لا يمكن رد هذا المنتج حيث ان هذا العميل لم يشتريه مسبقا');
                $('#returnremove' + n).click();
            }
            //here all code that will happend with loading contants
            //the number of rows of products
            var noitr = document.getElementById("returnhidden_itr").value;

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

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

            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 getreturnproductbyParcode(e, value, n) {
    var pricetype = document.getElementById("retpricetypepro" + n).value;//pricetype
    var supplier = document.getElementById("supplier").value;
    var storeid = document.getElementById("reprstorid" + n).value//pricetype

    $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 billnameid = $('#billnameid').val();
        var usedParcode = Number($('#usedParcode').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=getReturnproductNamebyOnlyParcode&parcode=' + value + '&billnameid=' + billnameid + '&storeid=' + storeid,
            success: function (data) {

                var response = $.parseJSON(data);

                //$("#returnproduct" + n).select2('val', ['' + response.id + ':' + response.text + ''], true);
                $("#returnproduct" + 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
                }, false);

                $("#returnparcodeType" + n).val(response.parcodeType);
                $("#returnproductserailid" + n).val(response.productserailid);
                if (response.chassisNo && response.motorNo) {
                    $("#returncomment" + n).val("رقم الشاسيه:" + response.chassisNo + " رقم الموتور:" + response.motorNo + " اللون:" + response.theColor);
                } else {
                    $("#returncomment" + 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 {
                    $('#returnpronum' + n).closest('td').append('<input type="hidden" name="parcodeBalance_data_hidden' + n + '" id="parcodeBalance_data_hidden' + n + '" value="' + parcodeBalance_data + '" />');
                }
                //---

                var productid = document.getElementById("returnproduct" + n).value;

                if (productid != "" && productid != "null" && productid != null && productid != "-1") {

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


                    $("#addunit").empty();
                    //////////////////////////////////////////////////
                    var productParcode = $("#returnparcode" + n).val();
                    $.ajax({
                        url: '' + productpricepagename + '?do=getreturnunit&itrs=' + n + '&tabindex=' + $rtabindexnum + '&productid=' + productid + '&pricetype=' + pricetype + '&clientid=' + supplier + '&comingproserial=1&parcode=' + productParcode + '&billnameid=' + $('#billnameid').val(),
                        type: "get",
                        success: function (data) {
                            var response = $.parseJSON(data);
                            //populate unit
                            $('#returnproductunitdiv' + n).html(response.unitString);
                            $("#addunit").empty();
                            //$("#returnproductunitdiv1 option").clone().appendTo("#addunit");

                            //populate buy price
                            //alert(response.priceString);
                            $('#returnpropricechange' + n).html(response.priceString);
                            //--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) {
                                    $('#returnproprice' + n).val(WeightPricePart);
                                    $('#returnpronum' + n).val(1);
                                }
                            }
                            //----


                            var returnproductpricetype = document.getElementById("returnproductpricetype" + n).value;


                            if (returnproductpricetype == 1) {
                                $('#returnproprice' + n).css("background-color", "#B7DFA4");
                                $('#returnpropricechange' + n).css("background-color", "#B7DFA4");


                            } else {
                                $('#returnproprice' + n).css("background-color", "#FFF");
                                $('#returnpropricechange' + n).css("background-color", "#FFF");
                            }


                            $('#returnproductparcode' + n).html(response.parcodeString);
                            //alert(response.priceString)

                            var returnparcodeType = document.getElementById("returnparcodeType" + n).value;

                            if (returnparcodeType == "serialnumber") {
                                $('#returnpronum' + n).val(1);
                                //$('#returnpronum'+n).attr('readonly', true);
                            } else {
                                $('#returnpronum' + n).attr('readonly', false);
                            }

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

                            //document.getElementById("returnproprice"+n).value=0;
                            document.getElementById("returnpronum" + n).value = 1;
                            document.getElementById("returnprodis" + n).value = 0;
                            if (useParcodeBalance == 1 && posType == 0) {
                                $('#returnpronum' + n).val(WeightPricePart);
                            } else {
                                $('#returnpronum' + n).val(1);
                            }

                            if (showPrevDiscount == 1 && $('#retLastClientDisVal' + n).length > 0) {
                                $('#returnprodis' + n).val($('#retLastClientDisVal' + n).val());
                                $('#returndiscounttype' + n).val($('#retLastClientDisPer' + n).val());
                            }

                            var productData = $("#returnproduct" + n).select2('data');
                            if (productData.isProUnitParcode == 1) {
                                $('#returnproductunit' + n).val(productData.productunitid);
                                switch (Number($('#retpricetypepro' + n).val())) {
                                    case 0:
                                        $('#returnproprice' + n).val(productData.proUnitSellAllPrice);
                                        break;
                                    case 1:
                                        $('#returnproprice' + n).val(productData.proUnitSellUnitPrice);
                                        break;
                                    case 2:
                                        $('#returnproprice' + n).val(productData.proUnitSellHalfPrice);
                                        break;

                                    default:
                                        $('#returnproprice' + n).val(productData.proUnitSellAllPrice);
                                        break;

                                }
                            }
                            //change price of product from main curr to slected curr val
                            $('#returnproprice' + n).val(getValueInTermsOfSelectedCurrency($('#returnproprice' + n).val()));

                            if ($('#retOnlySoldProducts').val() == 1 && $("#supplier").val() > 1 && returnproductpricetype != 1) {//sold befor//$('#returnproprice' + n).css('background-color') == 'rgb(183, 223, 164)') {
                                alert('لا يمكن رد هذا المنتج حيث ان هذا العميل لم يشتريه مسبقا');
                                $('#returnremove' + n).click();
                            }
                            //to calculate the price and amount with discount
                            returncalcuproduct(n);

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

                            totalprice();

                            //get the general discount
                            thegeneraldiscount();

                            checkthepayed();

                            //get the general payed
                            thegeneralpayed();

                            // calculate the rest of debt
                            therestofdebt();


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


                            if ((Number($raw_i) - Number(n)) == 1) {

                                $("#addunit").empty();

                                returnaddrow($raw_i, $rtabindexnum);


                                if (settingQuantitiyFocus == 0 && returnparcodeType != "serialnumber") {
                                    $("#returnpronum" + n).focus();
                                    $("#returnpronum" + n).select();
                                } else {
                                    $("#returnparcode" + $raw_i).focus();
                                    $("#returnparcode" + $raw_i).select();
                                }


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


                                // incrementaion of row number and tab index
                                $raw_i++
                                $rtabindexnum++;

                            } else {
                                if (settingQuantitiyFocus == 0 && returnparcodeType != "serialnumber") {
                                    $("#returnpronum" + n).focus();
                                    $("#returnpronum" + n).select();
                                } else {
                                    $("#returnparcode" + $raw_i).focus();
                                    $("#returnparcode" + $raw_i).select();
                                }
                            }

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

                }

            }
        });

        // }

    }

}


$("[id^='retpricetypepro']").live('change', function () {
    var pricetype = $(this).val();
    var id = $(this).attr('id');
    $n = id.substring(15);

    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") {
        $.ajax({
            url: 'sellbillAjaxController.php?do=getpriceall&productid=' + theselectedvalue + '&productunit=' + productunit + '&pricetype=' + pricetype + '&itrs=' + $n,
            type: "get",
            async: false,
            success: function (data) {
                data = data.split("/");
                $('#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');
            },
            error: function () {
                alert("لقد حدث خطأ أثناء إجراء العملية");
            }
        });
    }

});



