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



    // here the frist action on frist dropdownlist
    /************************/


    /**********************/
    //action of store dropdownlist
    /**********************/

    $("#searchnow, .showMore").live("click", function (e) {
        if (!$("#searchnow").hasClass('processing....')) {
            $("#searchnow").addClass('processing....');
            // console.log(theSelection);
            //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 zeros = $("#zeros").attr("checked") ? 1 : 2;
            //##show More
            var showMoreSetting = $(".showMoreSetting:checked").val();
            var showMore = 0;
            var lastItr = 0;
            var pageNo = 0;
            if ($(this).hasClass('showMore')) {
                showMore = 1;
                lastItr = $(this).attr('data-lid');
                pageNo = $(this).attr('data-page');
            }
            //
            var storeId = $("#storeId").val();
            if (storeId > 0) {
                $.ajax({
                    url: 'inventoryControllerAjax.php?storeid=' + $("#storeId").val() + '&zeros=' + zeros + '&catid=' + productCatId + '&productid=' + $("#product").val() + '&lastInventoryDate=' + $("#lastInventoryDate").val() + '&beforeAfter=' + $('input.beforeAfter:checked').val() + '&showMore=' + showMore + '&lastItr=' + lastItr + '&pageNo=' + pageNo + '&showMoreSetting=' + showMoreSetting, //'&catid=' + $("#catId").val()
                    type: "get",
                    success: function (data) {
                        $("#searchnow").removeClass('processing....');

                        if (showMore == 0) {//it is #searchnow
                            $('#productsDiv').html(data);
                        } else {//it is .showMore,we will append
                            //destroy datatable first
                            $('#productsTable').DataTable().destroy();
                            $('#productsTBody').append(data);

                            var newPage = Number($('.showMore').attr('data-page')) + 1;
                            $('.showMore').attr('data-page', newPage);

                            var lId = $('.showMore').attr('data-lid');
                            var newLID = $('#lid_temp').val();
                            $('#lid_temp').remove();
                            $('.showMore').attr('data-lid', newLID);
                            if (lId == newLID) {//no more data
                                $('.showMore').hide();
                            }

                        }
                        //recreate datatable
                        dataTableClass();
                    },
                    error: function () {
                        alert("لقد حدث خطأ أثناء إجراء العملية");
                        $("#searchnow").removeClass('processing....');
                    }
                });

            } else {
                //////////////////////////////////////////////////
                alert('يجب اختيار المخزن');
                //////////////////////////////////////////////////
                $("#searchnow").removeClass('processing....');
            }
        }

    });


    $("#searchStoreHousing").on("click", function (e) {

        // console.log(theSelection);
        //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());
        }

        //////////////////////////////////////////////////
        $.ajax({
            url: 'inventoryControllerAjax.php?do=storehousing&storeid=' + $("#storeId").val() + '&catid=' + productCatId + '&productid=' + $("#product").val() + '', //'&catid=' + $("#catId").val()
            type: "get",
            success: function (data) {
                $('#productsDiv').html(data);
                dataTableClass();
            },
            error: function () {
                alert("لقد حدث خطأ أثناء إجراء العملية");
            }
        });
        //////////////////////////////////////////////////
    });


    $(".autostorehousing").live("change", function (e) {
        var name = $(this).attr('data-name');// e.val;
        var values = $(this).val();
        var id = $(this).attr('data-id');// e.val;
        $.post('inventoryControllerAjax.php?do=autostorehousing', {id: id, values: values, name: name});
        var itr = $(this).attr('data-itr');
        var producttext1 = $("#producttext1" + itr).val();
        var producttext2 = $("#producttext2" + itr).val();
        var producttext3 = $("#producttext3" + itr).val();
        $("#alltext" + itr).text(producttext1 + ' - ' + producttext2 + ' - ' + producttext3);

    });


    $(".autosave").live("change", function (e) {
        var itr = $(this).attr('data-itr');
        var newQty = $(this).val();
        var productId = $("#productId" + itr).val();
        var storedetailid = $("#storedetailid" + itr).val();
        var oldQty = $("#oldQty" + itr).val();
        var storeid = $("#storeid" + itr).val();

        $.post('inventoryController.php?do=autosave', {
            newQty: newQty, productId: productId, storedetailid: storedetailid,
            oldQty: oldQty, storeid: storeid
        });
    });
});

$('.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);
                });
            }
        }
    });

});

$(document).on('click', "#doAddManyParcodes", function () {
    if ($('#manyParcodes').val() != '') {
        $('#manyParcodesstoreid').val($('#storeId').val());
        $('#manyParcodesproductCatId').val($("#productCatId0").val());
        var parcodes = $('#manyParcodes').val();
        var storeid = $('#manyParcodesstoreid').val();
        var catid = $('#manyParcodesproductCatId').val();
        var lastInventoryDate = $('#lastInventoryDate').val();
        var beforeAfter = $('input.beforeAfter:checked').val();
        // $('#manyParcodesForm').submit();
        $.post('inventoryControllerAjax.php?do=addManyParcodesTest',
                {manyParcodes: parcodes, storeid: storeid, manyParcodesproductCatId: catid, lastInventoryDate: lastInventoryDate, beforeAfter: beforeAfter},
                function (data) {
                    $('#productsDiv').html(data);
                    dataTableClass();
                    $('#myModalManyParcodes').modal('hide');
                });
    } else {
        alert('عفوا لم تدخل اى باركود');
    }

});
