var formatResult = function (data) {
    return  data.text;
};
function initializeInSelect2(itr) {
    $("#product" + itr).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("inStore").value,
                    //hiddenpricetype: document.getElementById("pricetypepro" + n).value, //pricetype
                    //suppplier: document.getElementById("supplier").value,
                    searchWithCatAndProductNameOnly: 0, //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);
        }
    }).on('change', function () {
        //var theselectedvalue = $(this).val();
        var n = $(this).data('itr');
        $('#unitIdIn' + itr).val('').change();
        $('#price' + n).val('').change();
    })
    $("#unitIdIn" + itr).select2({
        placeholder: "وحدة القياس",
        minimumInputLength: 0, //document.getElementById("searchvalue").value,
        //minimumInputLength: 3,
        multiple: false,
        quietMillis: 100,
        ajax: {
            url: "damagedProductAjaxController.php?do=unitsAjax",
            dataType: 'json',
            data: function (term, page) {
                return {
                    term: term, //search term
                    page_limit: 10, // page size
                    product: $('#product' + itr).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]};
            var data = {id: item[0], text: item[1], productquantity: item[2], price: item[3]};
            callback(data);
        }
    }).on('change', function () {
        var n = $(this).data('itr');
        calcInPricesFunc(n);
    });


    //
    if ($('#oldproductid' + itr).length > 0 && $('#oldproductname' + itr).length > 0)
        $('#product' + itr).select2('data', {id: $('#oldproductid' + itr).val(), text: $('#oldproductname' + itr).val()});
    //
    if ($('#oldunitid' + itr).length > 0 && $('#oldunitname' + itr).length > 0)
        $('#unitIdIn' + itr).select2('data', {id: $('#oldunitid' + itr).val(), text: $('#oldunitname' + itr).val()});
}
function initializeOutSelect2(itr) {
    $("#pro" + itr).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("inStore").value,
                    //hiddenpricetype: document.getElementById("pricetypepro" + n).value, //pricetype
                    //suppplier: document.getElementById("supplier").value,
                    searchWithCatAndProductNameOnly: 0, //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);
        }
    }).on('change', function () {
        //var theselectedvalue = $(this).val();
        var n = $(this).data('itr');
        $('#unit' + itr).val('').change();
        $('#cost' + n).val('').change();
        $('#actualCost' + n).val('').change();
    })
    $("#unit" + itr).select2({
        placeholder: "وحدة القياس",
        minimumInputLength: 0, //document.getElementById("searchvalue").value,
        //minimumInputLength: 3,
        multiple: false,
        quietMillis: 100,
        ajax: {
            url: "damagedProductAjaxController.php?do=unitsAjax",
            dataType: 'json',
            data: function (term, page) {
                return {
                    term: term, //search term
                    page_limit: 10, // page size
                    product: $('#pro' + itr).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]};
            var data = {id: item[0], text: item[1], productquantity: item[2], price: item[3]};
            callback(data);
        }
    }).on('change', function () {
        var n = $(this).attr('id').slice(4);
        var p = $("#pro" + n).select2('data').price;
        var pnum = $("#unit" + n).select2('data').pnum;
        if (Number($("#unit" + n).val()) > 0) {
            $('#unitPrice' + n).html($("#pro" + n).select2('data').buyprice);
        } else {
            $('#unitPrice' + n).html('');
        }
        if ((Number($("#pro" + n).val()) > 0 || $("#pro" + n).val().includes("hasSizeColor")) && Number($("#unit" + n).val()) > 0) {
            var tp = Number((p * pnum).toFixed(2));
            $('#actualCost' + n).val(tp).keyup();
        } else {
            $('#actualCost' + n).val(.0).keyup();
        }
    });

    //
    if ($('#oldproId' + itr).length > 0 && $('#oldproId' + itr).length > 0)
        $('#pro' + itr).select2('data', {id: $('#oldproId' + itr).val(), text: $('#oldproName' + itr).val()});
    //
    if ($('#oldunitId' + itr).length > 0 && $('#oldunitName' + itr).length > 0)
        $('#unit' + itr).select2('data', {id: $('#oldunitId' + itr).val(), text: $('#oldunitName' + itr).val()});
}
var calcInPricesFunc = function (n, isInPrice = 0) {
    if (isInPrice != 1) {
  //        var p = $("#product" + n).select2('data').price;
  //        var pnum = $("#unitIdIn" + n).select2('data').pnum; 
  //        var tp = Number((p * pnum).toFixed(2));

        var actlTotalCost = Number($('#actlTotalCost').val());
        var totalNumIn = 0
        $('input.select2productin').each(function () {
            var j = $(this).attr('id').slice(7);
            if ((Number($("#product" + j).val()) > 0 || $("#product" + j).val().includes("hasSizeColor")) && Number($("#unitIdIn" + j).val()) > 0) {
                totalNumIn += Number($('#quantity' + j).val());
            }
        });
        //price
        $('input.select2productin').each(function () {
            var j = $(this).attr('id').slice(7);
            if ((Number($("#product" + j).val()) > 0 || $("#product" + j).val().includes("hasSizeColor")) && Number($("#unitIdIn" + j).val()) > 0) {
                var price = actlTotalCost / totalNumIn;//Number($('#quantity' + j).val())
                $('#price' + j).val(Number(price.toFixed(3)));
            } else {
                $('#price' + j).val(0);
            }
        });
    }


    var tot = 0;
    var totUnitManufPrice = 0;
    $('input.select2productin').each(function () {
        var j = $(this).attr('id').slice(7);
        if ((Number($("#product" + j).val()) > 0 || $("#product" + j).val().includes("hasSizeColor")) && Number($("#unitIdIn" + j).val()) > 0) {
            var q = Number($('#quantity' + j).val());
            var p = Number($('#price' + j).val());
            var UMP = Number($('#unitManufPrice' + j).val());
            var t = Number(((q * p) + (q * UMP)).toFixed(2));
            $('#inTotalCost' + j).html(t);
            $('#inTotalCostUnit' + j).html(p + UMP);
            $('#inTotalCostUnit_h' + j).val(p + UMP);
            tot += t;
            totUnitManufPrice += (q * UMP);
        } else {
            $('#inTotalCost' + j).html(0);
            $('#inTotalCostUnit' + j).html(0);
            $('#inTotalCostUnit_h' + j).val(0);
        }
    });
    $('#allCost').html(Number(tot.toFixed(3)));
    $('#allUnitManufPrice').html(Number(totUnitManufPrice.toFixed(3)));




}

$(document).ready(function (e) {
    calcSumOfRawMaterials();
    $(".select2Supp").select2({
        placeholder: "المورد",
        minimumInputLength: document.getElementById("searchvalue").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) {
            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]};
            callback(data);
        },
        //dropdownCssClass: "bigdrop", // apply css that makes the dropdown taller
    })
//    .on('select2-loaded', function (e) {// not "select2-open" nor "select2-opening" //http://mkurz.github.io/select2/index.html
//        $('.newoption').parent().addClass('newoption');
//    }).on('change', function () {
//        supplierDebt($(this).val());
//    })
    $('#supplier').select2('data', {id: $('#oldsupplierid').val(), text: $('#oldsuppliername').val()});
    $(".getFinalProductsWithOutProductionEquation").select2({
        placeholder: "إسم المنتج",
        minimumInputLength: document.getElementById("searchvalue").value,
        multiple: false,
        quietMillis: 100,
        ajax: {
            url: "taskOrderAjaxController.php?do=getProductionEquationProducts", //getFinalProducts
            dataType: 'json',
            data: function (term, page) {
                return {
                    term: term, //search term
                    page_limit: 10 // page size
                };
            },
            results: function (data) {
                return {results: data};
                alert(1);
            }
        },
        formatResult: formatResult,
        initSelection: function (element, callback) {
            var item = element.val().split(':');
            var data = {id: item[0], text: item[1]};
            callback(data);
        }
    });

    function calcSumOfRawMaterials() {
        $(document).on('keyup change', '.quantity', function () {
            //$('.quantity').on('keyup change', function () {
            var sum = 0;
            $('.quantity').each(function () {
                sum += Number($(this).val());
            });
            $('#totalQuantitySpan').html(sum);

            //change actualTotalCost or incalc class , calc prices of input
            calcInPricesFunc($('input.select2productin').first().attr('itr'))
        });
        $(document).on('keyup change', '.actual', function () {
            //$('.actual').on('keyup change', function () {
            var itr = $(this).attr('id').slice(6);
            var quantity = Number($(this).val());
            var uPrice = Number($('#unitPrice' + itr).html());
            var rowTot = Number((quantity * uPrice).toFixed(3));
            $('#actualCost' + itr).val(rowTot).keyup();

            var sum = 0;
            $('.actual').each(function () {
                sum += Number($(this).val());
            });
            $('#totalActualQuantity').html(sum.toFixed(3));


        });
        $(document).on('keyup change', '.cost', function () {
            //$('.cost').on('keyup change', function () {
            var sum = 0;
            $('.cost').each(function () {
                sum += Number($(this).val());
            });
            $('#totCost').html(sum);
        });
        $(document).on('keyup change', '.actualCost', function () {
            //$('.actualCost').on('keyup change', function () {
            var sum = 0;
            $('.actualCost').each(function () {
                sum += Number($(this).val());
            });
            //###################################
            $('#actualTotalCost').html(sum.toFixed(3));
            $('#actlTotalCost').val(sum.toFixed(3));
            //change actualTotalCost or incalc class , calc prices of input
            calcInPricesFunc($('input.select2productin').first().attr('itr'))
            //####################################

        });
    }
    //########################################################################//

    $('#finalProductId').on('change', function () {
        var proId = $(this).val();
        $('#outQuantity').val(1);
        $.post("productionExecutionAjaxController.php?do=getEqProducts", {proId: proId, allowAddDel: $('#allowAddDel').val(), showPriceCol: 1}, function (data) {
            $('#table tbody').html('');
            $('#SCProEqDiv').html('');

            $('body').append('<div id="tempDivv" style="display:none;"></div>');
            $('#tempDivv').html(data);
            var proHasSizeColor = $('#proHasSizeColor').val();
            $('#tempDivv').remove();

            if (proHasSizeColor == 1) {
                $('#SCProEqDiv').html(data);
            } else {
                $('#table tbody').html(data);
            }


//            $('.countCost').trigger('change');
//            $('.outAmount').trigger('change');
            useFinalProductAsOutput();
        });
    });
    function useFinalProductAsOutput() {

        $('.finalProInRow').parent().parent().remove();
        $('input[id^="product"]').each(function () {
            if (Number($(this).val()) == 0)
                $('#quantity' + $(this).attr('id').substr(7)).parent().parent().remove();
        })
        //############
        //output
        $('#addInPro').click();
        var itr = $('#inProItr').val();
        if (Number($('#proHasSizeColor').val() == 0)) {

            var finalProduct = $('#finalProductId').select2('data');
            $('#product' + itr).select2('data', {id: finalProduct.id, text: finalProduct.text});
            $('#quantity' + itr).addClass('finalProInRow');
            $('#quantity' + itr).val($('#outQuantity').val());
        } else {
            var pRateItr = $('#pRateItr').val();
            for (var i = 1; i < pRateItr; i++) {
                var userQuantity = $('#userQuantityOfEq' + i).val();
                if (userQuantity > 0) {
                    var finalId = $('#finalId' + i).val();
                    var finalName = $('#finalName' + i).val();
                    //var finalPrices = $('#finalPrices' + i).val().split(',');


                    $('#product' + itr).select2('data', {id: finalId, text: finalName});
                    $('#quantity' + itr).addClass('finalProInRow');
                    $('#quantity' + itr).val(userQuantity);

                    //calc cost
                    calcInPricesFunc(itr, 0)
                }
            }
        }

        if ($('#product' + itr).val() != "")
            $.post('sellbillAjaxController.php?do=getProFirstUnitData', {product: $('#product' + itr).val(), itr: itr}, function (data) {
                data = JSON.parse(data);
                $('#unitIdIn' + data.itr).select2('data', {id: data.productunitid, text: data.unitName});
                $('#quantity' + data.itr).keyup();
            })

    }
    function fixPlusRemoveBtn() {
        //####where is add , where is del buttons of the row
        $('input[id^="allPrice"]').each(function () {
            $n = $(this).attr('id').substr(8);
            if ($(this).hasClass('finalProOutRow'))
                $(this).parent().parent().children('td').last().html('<a href="javascript:;" type="button" class="btn add addOutPro" id="addOutPro' + $n + '"><i class="glyphicon glyphicon-plus-sign"></i></a>');
            else
                $(this).parent().parent().children('td').last().html('<button id="remove' + $n + '" type="button" data-del="out" class="close flt-none removeicon removeproduct" aria-hidden="true">&times;</button>');
        })
    }
    function sumProduct(proid, itr) {
        itr = Number(itr);
        var quantity = 0;
        var actual = 0;
        var cost = 0;
        var actualCost = 0;
        $("#table input[id^='pro']").not("#proHasSizeColor").each(function () {
            var loopProId = $(this).val();
            var loopItr = $(this).attr('id').slice(3);
            //sum products in same store  or  store == -10 means one store for all bill
            if (loopProId == proid) {
                quantity += Number($('#quantityVal' + loopItr).val());
                actual += Number($('#actual' + loopItr).val());
                cost += Number($('#cost' + loopItr).val());
                actualCost += Number($('#actualCost' + loopItr).val());
                //remove the row
                if (Number(loopItr) > Number(itr)) {
                    $('#pro' + loopItr).parent().parent().remove();
                }
            }
        });
        $('#quantityVal' + itr).val(Number(quantity.toFixed(3)));
        $('#quantity' + itr).html(Number(quantity.toFixed(3)));
        $('#actual' + itr).val(Number(actual.toFixed(3)));
        $('#cost' + itr).val(Number(cost.toFixed(3)));
        $('#costSpan' + itr).html(Number(cost.toFixed(3)));
        $('#actualCost' + itr).val(Number(actualCost.toFixed(3)));
    }
    $('.userQuantityOfEq').live('keyup', function () {
        //$(document).on('change', '.userQuantityOfEq', function () {
        var html = '';
        var itr = 1;
        var pRateItr = $('#pRateItr').val();
        var totalQuantity = 0;
        var totalCost = 0;

        var allowedit = $("#allowedit").val();
        for (var i = 1; i < pRateItr; i++) {
            var proItr = $('#proItr' + i).val();
            var userQuantity = Number($('#userQuantityOfEq' + i).val());
            if (userQuantity > 0) {
                for (var j = 1; j < proItr; j++) {
                    var proId = $("#pRateProId" + i + "_" + j).val();
                    var proName = $("#pRateProName" + i + "_" + j).val();
                    var unitId = Number($("#pRateUnitid" + i + "_" + j).val());
                    var unitName = $("#pRateUnitName" + i + "_" + j).val();
                    var rateQuantity = Number($("#pRateQty" + i + "_" + j).val());
                    var buyPrice = Number($("#pRateBuyPrice" + i + "_" + j).val());
                    var productNumber = Number($("#pRateProductNumber" + i + "_" + j).val());
                    //calc values
                    var rateQuantity = Number((rateQuantity * userQuantity).toFixed(3));
                    var cost = Number((buyPrice * rateQuantity).toFixed(3));
                    var dataVal = Number((rateQuantity / productNumber).toFixed(3));

                    totalQuantity += rateQuantity;
                    totalCost += cost;

                    if (allowedit == 0) {
                        html += '<tr>' +
                                '    <td>' +
                                '        <input type="hidden" readonly name="pro' + itr + '" id="pro' + itr + '" value="' + proId + '"/>' +
                                '        ' + proName +
                                '    </td>' +
                                '    <td>' +
                                '        <input type="hidden" readonly name="unit' + itr + '" id="unit' + itr + '" value="' + unitId + '"/>' +
                                '        ' + unitName +
                                '    </td>' +
                                '    <td class="quantityStyle">' +
                                '        <span id="quantity' + itr + '">' + rateQuantity + '</span>' +
                                '        <input type="hidden" class="quantity" name="quantity' + itr + '" id="quantityVal' + itr + '" data-val="' + dataVal + '" value="' + rateQuantity + '"/>' +
                                '    </td>' +
                                '    <td>' +
                                '        <input type="number" step="any" class="form-control actual" id="actual' + itr + '" name="actual' + itr + '" data-val="' + rateQuantity + '" value="' + rateQuantity + '"/>' +
                                '    </td>' +
                                '    <td><span id="unitPrice' + itr + '">' + buyPrice + '</span></td>' +
                                '    <td class="costStyle">' +
                                '        <span id="costSpan' + itr + '">' + cost + '</span>' +
                                '        <input type="hidden" class="cost" id="cost' + itr + '" name="cost' + itr + '" data-val="' + buyPrice + '" value="' + cost + '"/>' +
                                '    </td>' +
                                '    <td>' +
                                '        <input type="number" step="any" class="form-control actualCost" id="actualCost' + itr + '" name="actualCost' + itr + '" value="' + cost + '"/>' +
                                '    </td>';
                    } else if (allowedit == 1) {

                        html += '<tr>' +
                                '    <td>' +
                                '        <input type="hidden" name="pro' + itr + '" id="pro' + itr + '"/>' +
                                '        <input type="hidden" id="oldproId' + itr + '" value="' + proId + '"/>' +
                                '        <input type="hidden" id="oldproName' + itr + '" value="' + proName + '"/>' +
                                '    </td>' +
                                '    <td>' +
                                '        <div id="unitDiv' + itr + '">' +
                                '            <input type="hidden" readonly name="unit' + itr + '" id="unit' + itr + '"/>' +
                                '        </div>' +
                                '        <input type="hidden" id="oldunitId' + itr + '" value="' + unitId + '"/>' +
                                '        <input type="hidden" id="oldunitName' + itr + '" value="' + unitName + '"/>' +
                                '    </td>' +
                                '    <td class="quantityStyle">' +
                                '        <input type="number" step="any" class="quantity" name="quantity' + itr + '" id="quantityVal' + itr + '" data-val="' + dataVal + '" value="' + rateQuantity + '"/>' +
                                '    </td>' +
                                '    <td>' +
                                '        <input type="number" step="any" class="form-control actual" id="actual' + itr + '" name="actual' + itr + '" data-val="' + rateQuantity + '" value="' + rateQuantity + '"/>' +
                                '    </td>' +
                                '    <td><span id="unitPrice' + itr + '">' + buyPrice + '</span></td>' +
                                '    <td class="costStyle">' +
                                '        <input type="number" step="any" class="cost" id="cost' + itr + '" name="cost' + itr + '" data-val="' + buyPrice + '" value="' + cost + '"/>' +
                                '    </td>' +
                                '    <td>' +
                                '        <input type="number" step="any" class="form-control actualCost" id="actualCost' + itr + '" name="actualCost' + itr + '" value="' + cost + '"/>' +
                                '    </td>';


                    }
                    if (Number($('#allowAddDel').val() == 1)) {
                        html += '    <td>' +
                                '        <button id="remove' + itr + '" type="button" class="close flt-none rawProduct removethis" aria-hidden="true" data-itr="' + itr + '">×</button>' +
                                '    </td>';
                    }
                    html += '</tr>';
                    itr++;
                }
            }
        }

        //if sum row doesnot exist appent it ,its html code is below
        totalQuantity = Number(totalQuantity.toFixed(3));
        totalCost = Number(totalCost.toFixed(3));
        html += '<tr id="totalRowOut">' +
                '    <th colspan="2" style="color: #eeecda; background-color: #0081a8;"><span style="font: bold;">الإجمالي</span></th>' +
                '    <th class="quantityStyle"><span id="totalQuantitySpan">' + totalQuantity + '</span></th>' +
                '    <th><span id="totalActualQuantity">' + totalQuantity + '</span></th>' +
                '    <th></th>' +
                '    <th id="totCost" class="costStyle">' + totalCost + '</th>' +
                '    <th>' +
                '        <span id="actualTotalCost">' + totalCost + '</span>' +
                '        <input type="hidden" id="actlTotalCost" name="actlTotalCost" value="' + totalCost + '"/>' +
                '    </th>';
        if (Number($('#allowAddDel').val() == 1)) {
            html += '    <td></td>';
        }
        html += '</tr>' +
                '<input type="hidden" name="rowitr" id="rowitr" value="' + itr + '"/>' +
                '<input type="hidden" name="proHasSizeColor" id="proHasSizeColor" value="1">';

        $('#table tbody').html(html);

        if (allowedit == 1) {
            for (var j = 1; j < itr; j++) {
                initializeSelectt2Raw(j);
            }
            calcSumOfRawMaterials();
        }
        $("#table input[id^='pro']").each(function () {
            var itr = $(this).attr('id').slice(3);
            sumProduct($(this).val(), itr);
        });

//        $('.countCost').trigger('change');
//        $('.outAmount').trigger('change');
        useFinalProductAsOutput();


    });
    function initializeSelectt2Raw(q) {



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

        var theselectedvalue = $('#oldproId' + q).val();
        $("#pro" + q).select2("data", {id: $('#oldproId' + q).val(), text: $('#oldproName' + q).val()});
        $('#unitDiv' + q).load('damagedProductAjaxController.php?do=unitsWithItration&productid=' + theselectedvalue + '&itr=' + q + '', function () {
            //change comming name,id attributes
            $('#unitId' + q).attr('id', 'unit' + q);
            $('#unit' + q).attr('name', 'unit' + q);

            $('select').select2();
            $("#unit" + q).select2();
            $("#unit" + q).select2("data", {id: $('#oldunitId' + q).val(), text: $('#oldunitName' + q).val()});
        });


        ///////////  دى بسمعانا/////
        $("#pro" + q).change(function () {


            var currentId = $(this).attr('id');
            n = currentId.substr(7);
            var theselectedvalue = $(this).val();

            $('#cost' + q).val($("#pro" + q).select2('data').productBuyPrice).change();
            $('#actualCost' + q).val($('#cost' + q).val() * $('#actual' + q).val()).change();
            $('#unitDiv' + q).load('damagedProductAjaxController.php?do=unitsWithItration&productid=' + theselectedvalue + '&itr=' + q + '', function () {
                //change comming name,id attributes
                $('#unitId' + q).attr('id', 'unit' + q);
                $('#unit' + q).attr('name', 'unit' + q);


                $('select').select2();
                $("#unit" + q).select2("data", {id: $('#oldunitId' + q).val(), text: $('#oldunitName' + q).val()});
            });

        });





    }
    //########################################################################//

    $(".select2productout").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("outStore").value,
                    //hiddenpricetype: document.getElementById("pricetypepro" + n).value, //pricetype
                    //suppplier: document.getElementById("supplier").value,
                    searchWithCatAndProductNameOnly: 0, //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);
        }
    });
    if ($('#oldproductOutid').length > 0 && $('#oldproductOutname').length > 0)
        $('#productOut').select2('data', {id: $('#oldproductOutid').val(), text: $('#oldproductOutname').val()});

    $(document).on('click', '.addOutPro', function () {
        var itr = $('#rowitr').val();
        var allowedit = $("#allowedit").val();
        itr++;

        var html = '';
        if (allowedit == 0) {
            return;
        } else if (allowedit == 1) {
            html += '<tr>' +
                    '    <td>' +
                    '        <input type="hidden" name="pro' + itr + '" id="pro' + itr + '"/>' +
                    '        <input type="hidden" id="oldproId' + itr + '" value="0"/>' +
                    '        <input type="hidden" id="oldproName' + itr + '" value=""/>' +
                    '    </td>' +
                    '    <td>' +
                    '        <div id="unitDiv' + itr + '">' +
                    '            <input type="hidden" name="unit' + itr + '" id="unit' + itr + '"/>' +
                    '        </div>' +
                    '        <input type="hidden" id="oldunitId' + itr + '" value="0"/>' +
                    '        <input type="hidden" id="oldunitName' + itr + '" value=""/>' +
                    '    </td>' +
                    '    <td class="quantityStyle">' +
                    '        <input type="number" step="any" class="quantity" name="quantity' + itr + '" id="quantityVal' + itr + '" data-val="" value="1"/>' +
                    '    </td>' +
                    '    <td>' +
                    '        <input type="number" step="any" class="form-control actual" id="actual' + itr + '" name="actual' + itr + '" data-val="" value="1"/>' +
                    '    </td>' +
                    '    <td><span id="unitPrice' + itr + '">0</span></td>' +
                    '    <td class="costStyle">' +
                    '        <input type="number" step="any" class="cost" id="cost' + itr + '" name="cost' + itr + '" data-val="" value=""/>' +
                    '    </td>' +
                    '    <td>' +
                    '        <input type="number" step="any" class="form-control actualCost" id="actualCost' + itr + '" name="actualCost' + itr + '" value=""/>' +
                    '    </td>';
            if (Number($('#allowAddDel').val() == 1)) {
                html += '    <td>' +
                        '        <button id="remove' + itr + '" type="button" class="close flt-none rawProduct removethis" aria-hidden="true" data-itr="' + itr + '">×</button>' +
                        '    </td>';
            }
            html += '</tr>';


            var newRow = $(html);
            newRow.insertBefore($('#table #totalRowOut'));
            $('.positivefloat').forcepositivefloat();
            initializeOutSelect2(itr);
            $('#rowitr').val(itr);

        }

    });
    $(document).on('click', '.addInPro', function () {
        var itr = $('#inProItr').val();
        itr++;
        $('#inTabletb').append('<tr>'
                + '<td><input type="hidden" id="product' + itr + '" name="product' + itr + '" data-itr="' + itr + '" class="select2productin wdt100" tabindex="7" /></td>'
                + '<td><input type="hidden" name="unitIdIn' + itr + '"  id="unitIdIn' + itr + '" class="select2_unit" data-itr="' + itr + '"></td>'
                + '<td><input type="text" name="quantity' + itr + '" id="quantity' + itr + '" min="0" class="form-control inQuantity inCalc positivefloat" data-itr="' + itr + '" value="1" /></td>'
                + '<td><input type="text" name="price' + itr + '" id="price' + itr + '" min="0" class="form-control inPrice inCalc positivefloat" data-itr="' + itr + '" value=""/></td>'
                + '<td><input type="text" name="unitManufPrice' + itr + '" id="unitManufPrice' + itr + '" min="0" class="form-control inCalc positivefloat" data-itr="' + itr + '" value="0"/></td>'
                + '<td><span class="inTotalCostUnit" id="inTotalCostUnit' + itr + '"></span><input type="hidden" name="inTotalCostUnit_h' + itr + '" id="inTotalCostUnit_h' + itr + '"></td>'
                + '<td><span class="inTotalCost" id="inTotalCost' + itr + '"></span></td>'
                + '<td class="noprint"><button id="remove' + itr + '" type="button" class="close flt-none removeicon removeproduct" aria-hidden="true">&times;</button></td>');
        $('.positivefloat').forcepositivefloat();
        initializeInSelect2(itr);
        $('#inProItr').val(itr);
    });
    $(document).on('click', '.removeicon', function () {
        $(this).parent().parent().remove();
        if ($(this).hasClass('rawProduct') || $(this).hasClass('removeproduct')) {
            $('.quantity').first().keyup()
            $('.actual').first().keyup();
            $('.cost').first().keyup();
            $('.actualCost').first().keyup();
        }
        return false;
    });


    $('.outCalc').on('keyup', function () {
        var q = Number($('#outQuantity').val());
        var c = Number($('#outUnitCost').val());
        var t = Number((q * c).toFixed(2));
        $('#outAllCost').val(t);
        actual(q);
        calcOutAllCostTot();
    });



    function actual(q) {

        var sum = 0;
        $('.actual').each(function () {
            var itr = $(this).attr('id').slice(6);
            var quantity = q * Number($(this).attr('data-val'));
            // var quantity = q * Number($(this).val());
            
            $(this).val(quantity);
            var uPrice = Number($('#unitPrice' + itr).html());
            var rowTot = Number((quantity * uPrice).toFixed(3));
            $('#actualCost' + itr).val(rowTot);
            sum += Number($(this).val());
        });
        $('#totalActualQuantity').html(sum.toFixed(3));


        var sum2 = 0;
        $('.actualCost').each(function () {
            sum2 += Number($(this).val());
        });
        //###################################
        $('#actualTotalCost').html(sum2.toFixed(3));
        $('#actlTotalCost').val(sum2.toFixed(3));
        //change actualTotalCost or incalc class , calc prices of input
        calcInPricesFunc($('input.select2productin').first().attr('itr'))


    }
    $(document).on('keyup', '.inCalc', function () {
        var n = $(this).data('itr');
        var q = Number($('#quantity' + n).val());
        var p = Number($('#price' + n).val());
        var UMP = Number($('#unitManufPrice' + n).val());
        var t = Number(((q * p) + (q * UMP)).toFixed(2));
        $('#inTotalCost' + n).html(t);
        $('#inTotalCostUnit' + n).html(p + UMP);
        $('#inTotalCostUnit_h' + n).val(p + UMP);

        //
        calcOutAllCostTot();

        var isInPrice = 0;
        if ($(this).hasClass('inPrice')) {
            isInPrice = 1;
        }
        //change actualTotalCost or incalc class , calc prices of input
        calcInPricesFunc(n, isInPrice)

    })

    function calcOutAllCostTot() {
        var q = Number($('#outQuantity').val());
        if (q != 0) {
            var c = Number($('#outUnitCost').val());
            var ac = Number($('#allCost').html());
            var outAllCostTot = (ac / q) + c;
            outAllCostTot = Number(outAllCostTot.toFixed(3));
        } else {
            outAllCostTot = '';
        }
        $('#outAllCostTot').val(outAllCostTot);
        $('#outAllCostTot_h').val(outAllCostTot);
    }
    //stop default action of form if {no equation name} or (total percentage !=100) or {one of products list with choice = -1}
    $("#saveBtn").click(function (event) {
        if (!$('#form1').hasClass('processing...')) {
            $('#form1').addClass('processing...');

            if (Number($('#supplier').val()) > 0) {
            } else {
                alert('اختر مورد اولا');
                $('#form1').removeClass('processing...');
                return false;
            }
            if (Number($('#finalProductId').val()) > 0 || $("#finalProductId").val().includes("hasSizeColor") || ($('#id').length > 0 && $('#id').val() > 0)) {
            } else {
                alert('اختر المنتج النهائى اولا');
                $('#form1').removeClass('processing...');
                return false;
            }

            if (Number($('#allCost').html()) > 0) {
            } else {
                alert('اختر بيانات المدخلات اولا');
                $('#form1').removeClass('processing...');
                return false;
            }

            $('#form1').submit();
        }
    });



    //out rowitr
    if ($('#rowitr').length > 0) {
        //edit page
        var rowitr = Number($('#rowitr').val());
        if (rowitr > 0) {
            //edit page
            for (var i = 1; i <= rowitr; i++) {
                initializeOutSelect2(i);
            }
        } else {
            //add page//dont add row by default
        }
    }
    if ($('#inProItr').length > 0) {
        //edit page
        var inProItr = Number($('#inProItr').val());
        if (inProItr > 0) {
            //edit page
            for (var i = 1; i <= inProItr; i++) {
                initializeInSelect2(i);
            }
        } else {
            //add page
            $('.addInPro').click();
        }
    }
    $('.positivefloat').forcepositivefloat();

});
