jQuery(document).ready(function () {

    $('#addpro').live('click', function () {
        var priceClass = '';
        $('.priceClass').each(function () {
            if (!$(this).is(':visible'))
                priceClass = 'hidden';
        })
        if (Number($("#storeId_hidden").val()) > 0)
        {
            $("#storeId").attr('disabled', 'disabled');
            var itr = Number($('#itr').val()) + 1;
            var row = '<tr>' +
                    '                    <td>' +
                    '                        <input type="hidden" id="product' + itr + '" name="product' + itr + '" data-placeholder="اختر" class="select2product wdt100" />' +
                    '                    </td>' +
                    '                    <td><span id="oldQtySpan' + itr + '">0</span></td>' +
                    '                    <td>' +
                    '                        <input name="newQty' + itr + '" id="newQty' + itr + '" type="text"  class=" form-control positivefloat newQtyClass"  data-itr="' + itr + '"/>' +
                    '                        <input name="storedetailid' + itr + '" id="storedetailid' + itr + '" type="hidden" value="0" />' +
                    '                        <input name="oldQty' + itr + '" id="oldQty' + itr + '" type="hidden" value="0" />' +
                    '                    </td>' +
                    '                    <td><span id="qtyAfter' + itr + '">0</span></td>' +
                    '                    <td class="' + priceClass + '"><span id="price' + itr + '">0</span></td>' +
                    '                    <td class="' + priceClass + '"><span id="rowtotal' + itr + '">0</span></td>' +
                    '                    <td><span id="lastDestDate' + itr + '"></span></td>' +
                    '                    <td><textarea class="form-control" rows="2" name="note' + itr + '" id="note' + itr + '"></textarea></td>' +
                    '                    <td><button id="remove' + itr + '" type="button" class="close flt-none removeicon removeproduct">×</button></td>' +
                    '                </tr>';
            $('#productsTBody').append(row);
            $(".positivefloat").forcepositivefloat();
            $("#product" + itr).select2({
                placeholder: "إسم المنتج",
                minimumInputLength: $('#searchvalue').val(),
                multiple: false,
                quietMillis: 100,
                ajax: {
                    url: 'buyBillControllerAjax.php?do=getProductsQueryStringnoservice&storeid=' + $("#storeId_hidden").val() + '&catid=-1&productid=-1',
                    dataType: 'json',
                    data: function (term, page) {
                        return {
                            term: term, //search term
                            page_limit: 10 // page size
                        };
                    },
                    results: function (data) {
                        //alert("data: "+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);
                }
            });

            $('#itr').val(itr);
        } else
        {
            alert('اختر مخزن');
        }
    });
    $(document).on('click', '.removeproduct', function () {
        // delete by partents
        $(this).parent().parent().remove();
        if ($("[name^='newQty']").length == 0) {
            $("#storeId").removeAttr('disabled');
        }
    });
    $("#storeId").on("change", function (e) {
        $('#storeId_hidden').val($("#storeId").val());
    });
    var formatResult = function (data) {
        //alert(data);
        return  data.text;
    }
    /**********************/
    //action of store dropdownlist
    /**********************/
    $('.select2product').live('change', function () {
        var theselectedvalue = $(this).val();
        var itr = $(this).attr('id').slice(7);
        var lastRowProductVal = $('.select2product:last').val();
        $.ajax({
            type: 'GET',
            url: 'restaurantRawDestructionAjax.php?storeid=' + $("#storeId_hidden").val() + '&productid=' + theselectedvalue + '',
            async: false,
            success: function (data) {
                data = JSON.parse(data);
                data = data[0];
                if (data.storedetailid > 0) {
                    $('#oldQtySpan' + itr).html(data.productquantity);
                    $('#oldQty' + itr).val(data.productquantity);
                    $('#storedetailid' + itr).val(data.storedetailid);
                    $('#newQty' + itr).val(0);
                    $('#qtyAfter' + itr).html(data.productquantity);
                    $('#lastDestDate' + itr).html(data.lastDestructionDate);
                    $('#price' + itr).html(data.price);
                    $('#rowtotal' + itr).html(0);//data.price
                } else {
                    //not in store
                    $('#remove' + itr).click();
                    alert('عفوا المنتج غير متوفر بالمخزن')
                }

                if (Number(lastRowProductVal) > 0)
                {
                    $('#addpro').click();
                }
            },
            error: function () {
                alert("لقد حدث خطأ أثناء إجراء العملية");
            }
        });
    });
    $('.newQtyClass').live('keyup', function () {
        var itr = $(this).attr('data-itr');
        checkdata(itr);
        calcTotal();
    });
    function checkdata(i)
    {
        //	alert('i'+i);
        var storenegative = $("#storenegative").val();
        var currentquantity = Number($("#oldQty" + i).val());
        var productamount = Number($("#newQty" + i).val());
        // alert('productamount'+productamount);
        //alert('currentquantity'+currentquantity);

        if (storenegative == 0)
        {

            if (productamount > currentquantity)
            {
                if (currentquantity > 0)
                {
                    $("#newQty" + i).val(currentquantity);
                } else
                {
                    $("#newQty" + i).val(0);
                }
            }

        } else
        {

        }
        //
        $('#qtyAfter' + i).html(Number($("#oldQty" + i).val()) - Number($("#newQty" + i).val()));
    }
    function calcTotal() {
        var total = 0;
        $('.newQtyClass').each(function () {
            var itr = $(this).data('itr');
            var quantity = Number($("#newQty" + itr).val());
            var price = Number($("#price" + itr).html());
            var rowTot = quantity * price;
            $('#rowtotal' + itr).html(rowTot);
            total += rowTot;
        });
        $('#totalPrice').html(total);

    }
});
