jQuery(document).ready(function () {

    var formatResult = function (data) {
//alert(data);
        return  data.text;
    }


    $('.select2product').select2({
        placeholder: "إسم المنتج",
        minimumInputLength: $('#searchvalue').val(),
        multiple: false,
        quietMillis: 100,
        ajax: {
            url: "buyBillControllerAjax.php?do=getProductsnoservice",
            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);
        }
    });
    $("#searchnow").on("click", function (e) {
//the selected value of drop downlsit
        var theselectedvalue = $("#product").val()// e.val;
        var level = Number($("#level").val());
        var productCatId = Number($("#productCatId" + level).val());
        if (isNaN(productCatId) || productCatId < 1) {
            var productCatId = Number($("#productCatId" + (level - 1)).val());
        }
        var Store = Number($("#storeId").val());
//        if (Store > 0) {
        //////////////////////////////////////////////////
        $.ajax({
            url: 'inventoryControllerAjax.php?do=expirationInv&storeid=' + $("#storeId").val() + '&catid=' + productCatId + '&productid=' + $("#product").val() + '', //'&catid=' + $("#catId").val()
            type: "get",
            success: function (data) {
                $('#productsDiv').html(data);
            },
            error: function () {
                alert("لقد حدث خطأ أثناء إجراء العملية");
            }
        });
        //////////////////////////////////////////////////
//        } else {
//            alert('اختر مخزن على الاقل')
//        }
    });
});

$('.productCat').live('change', function () {
    var id = $(this).val();
    var level = Number($(this).attr('data-level'));
    level = level + 1;
    $('#level').val(level);
    $.post('salesreportajax.php?do=getsubcat', {id: id, level: level}, function (data) {
        $('.productCat').each(function () {
            var thisLevel = Number($(this).attr('data-level'));
            if (thisLevel >= level) {
                $(this).parent('div').remove();
            }
        });
        $('#productIdDiv').remove();
        if (data != "-1") {
            $('#manyParents').append(data);
        }
    });

});

$('.productCatt').live('change', function () {
    var id = $(this).val();
    var level = Number($(this).attr('data-level'));
    level = level + 1;
    $('#level').val(level);
    $.post('salesreportajax.php?do=getsubcat2', {id: id, level: level}, function (data) {
        $('.productCatt').each(function () {
            var thisLevel = Number($(this).attr('data-level'));
            if (thisLevel >= level) {
                $(this).parent('div').remove();
            }
        });
        $('#productIdDiv_').remove();
        if (data != "-1") {
            $('#manyParents').append(data);
        } else
        {
            if ($('#dontLoadProducts').length > 0 && $('#dontLoadProducts').val() == 1) {
            } else {
                $.post('salesreportajax.php?do=getproductsbills', {id: id}, function (data) {
                    $('#manyParents').append(data);
                });
            }
        }
    });

});
function gettotal(i)
{
    var totalSerializedQuantity = 0;
    var itr = Number(document.getElementById('itr' + i + '').value);
    for (var z = 1; z <= itr; z++) {
        if ($('#quantity' + z + '_' + i).length > 0)
            totalSerializedQuantity += Number($('#quantity' + z + '_' + i).val());
    }


    var mytotal = Number(document.getElementById('totalproduct' + i + '').value);
    if (totalSerializedQuantity > mytotal) {
        $('#itr' + i).attr('data-e', 1);
        for (var z = 1; z <= itr; z++) {
            if ($('#quantity' + z + '_' + i).length > 0)
                $('#quantity' + z + '_' + i).css('background-color', 'yellow');
        }
        document.getElementById("subbtn" + i).style.display = "none";
        alert('من فضلك  عدل اعددا المنتجات لتصل الى ' + mytotal);
    } else {
        $('#itr' + i).attr('data-e', 0);
        for (var z = 1; z <= itr; z++) {
            if ($('#quantity' + z + '_' + i).length > 0)
                $('#quantity' + z + '_' + i).css('background-color', 'white');
        }
        document.getElementById("subbtn" + i).style.display = "block";
    }
//    var errorsOfQuantity = $('input[data-e=1]').length//no of products have error at total quantity
//    //
//    if (errorsOfQuantity > 0) {
//        document.getElementById("subbtn" + i).style.display = "none";
//    } else {
//        document.getElementById("subbtn" + i).style.display = "block";
//    }
}

function addRow(i) {
    var itr = Number($('#itr' + i).val());
    var carClass = 'hidden';
    if ($('.carClass').length > 0) {
        carClass = '';
    }

    $row = '<tr>' +
            '     <td><input name="serialnumber' + itr + '_' + i + '" id="serialnumber' + itr + '_' + i + '"  value="" class="myserial" data-allitr="{$allitr}" type="text">' +
            '           <input type="hidden" name="productserailid' + itr + '_' + i + '" id="productserailid' + itr + '_' + i + '" value="0"/> </td>' + //<!-- it is suggested serial for unserialized product  value="{$returnedSerial{$x}{$m}}"-->
            '     <td><input name="quantity' + itr + '_' + i + '" id="quantity' + itr + '_' + i + '"  type="text" onkeyup="gettotal(' + i + ');" value="1"></td>' +
            '     <td><textarea name="comment' + itr + '_' + i + '"></textarea></td>' +
            '     <td><input name="stratdate' + itr + '_' + i + '" class="awdatepicker" type="text" class="stratdate"></td>' +
            '     <td><input name="enddate' + itr + '_' + i + '" class="awdatepicker" type="text" class="enddate"></td>' +
            '     <td class="' + carClass + '"><input name="chassisNo' + itr + '_' + i + '"  type="text" class="chassisNo"></td>' +
            '     <td class="' + carClass + '"><input name="motorNo' + itr + '_' + i + '"  type="text" class="motorNo"></td>' +
            '     <td class="' + carClass + '"><input name="theColor' + itr + '_' + i + '"  type="text" class="theColor"></td>' +
            '     <td><input type="button" data-itr="' + itr + '_' + i + '" class="deleteitr" value="حذف" />' +
            '</tr>';
    $('#serialSTable' + i).append($row);
    $('.awdatepicker').datepicker({
        format: "yyyy-mm-dd",
        autoclose: true,
    });
    itr++;
    $('#itr' + i).val(itr);
}

$(document).on('click', '.deleteitr', function () {
    id = $(this).data('itr');
    $x = id.split('_')[1];
    var rowid = Number($('#productserailid' + id).val());
    if (rowid > 0) {
        var delIds = $('#delIds' + $x).val();
        delIds += rowid + ',';
        $('#delIds' + $x).val(delIds);
    }
    // delete by parents
    $("#serialnumber" + id).parent().parent().remove();

    return false;
});
$(document).on('click', '[id^="subbtn"]', function () {
    var thisBtn = $(this);
    if (!thisBtn.hasClass('processing...')) {
        thisBtn.addClass('processing...')
        thisBtn.addClass('btn-dark').removeClass('btn-primary');
        $x = thisBtn.data('proitr');
        //serialize all the form-elements within a div. only
        var rowData = $('tr[data-proitr="' + $x + '"]').find('select, textarea, input').serializeArray();
        rowData.push({name: "x", value: $x});

        $.ajax({
            type: 'POST',
            url: 'inventoryexpirationController.php?do=addAjax',
            data: rowData,
            async: true,
            success: function (data)
            {
                data = JSON.parse(data);
                if (data.status == 1) {
                    $.each(data.result, function (key, value) {
                        $('#productserailid' + value.itr).val(value.productserailid);
                    });
                    $('#delIds' + $x).val("");
                } else {
                    alert('عفوا لقد حدث خطأ من فضلك حاول مرة اخرى')
                }

                thisBtn.removeClass('processing...')
                thisBtn.addClass('btn-primary').removeClass('btn-dark');

            }
        });
    }
})
