
jQuery.fn.forcepositivefloat = function () {

    return this.each(function () {
        $(this).keydown(function (e) {
            var presedval = e.key;
            var key = e.which || e.keyCode;
            //alert(key);
            if (!e.shiftKey && !e.altKey && !e.ctrlKey &&
                    // numbers
                    key >= 48 && key <= 57 ||
                    // Numeric keypad
                    key >= 96 && key <= 105 ||
                    // comma, period and minus, . on keypad
                    //key == 190 || key == 188 || key == 109 || key == 110 ||
                    // Backspace and Tab and Enter
                    key == 8 || key == 9 || key == 13 ||
                    // Home and End
                    key == 35 || key == 36 ||
                    // left and right arrows
                    key == 37 || key == 39 ||
                    //dot or point  .  on keyboard  for one time
                            (key == 110 && $(this).val().indexOf(".") < 0) ||
                            (key == 190 && $(this).val().indexOf(".") < 0 && presedval == ".") ||
                            // Del and Ins
                            key == 46 || key == 45)
                return true;

            return false;
        });
    });
}

$(document).ready(function (e) {
    //alert("ffff");

    $('.stratdate').datepicker({
        format: 'yyyy-mm-dd'
    });
    $('.enddate').datepicker({
        format: 'yyyy-mm-dd'
    });

    $(".awdatepicker").datepicker({
        format: 'yyyy-mm-dd'
    });

    //$('.productCat').live('change', function () {
    $('body').on('change', '.productCat', function () {
        var id = $(this).val();
        console.log('id = ' + id);
        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);
            }
        });

        var last_level = $('#level').val();
        if (typeof last_level !== 'undefined') {

            last_level = last_level - 1;

            var last_productCatId = $('#productCatId' + last_level + '').val();
            $('#productCatId').val(last_productCatId);
            console.log('productCatId = ' + last_productCatId);

            //# fill buypricereal ,  buytotal , buyhalf , buypart
            var productCatId_level = $('#level').val();
            //console.log('level = '+productCatId_level);
            var i, last_level;
            for (i = 1; i <= productCatId_level; i++) {
                if (i == productCatId_level) {
                    last_level = productCatId_level - 1;
                }
            }
            var productCatId = $('#productCatId' + last_level + '').val();

        }
        $.post('productControllerAjax.php?do=get_prices', {productCatId: productCatId}, function (data) {
            data = JSON.parse(data);
            $('.buypricereal_precentage1').val(data.buypricereal);
            $('.buytotal_precentage1').val(data.buytotal);
            $('.buyhafe_precentage1').val(data.buyhalf);
            $('.buypart_precentage1').val(data.buypart);
        });

    });

    //# m7md products form
    $('body').on('keyup', '.buy_price', function () {
        var ths_val = $(this).val();
        var ths_id = $(this).attr('data-id');

        var buypricereal = $('.buypricereal_precentage' + ths_id + '').val();
        var buytotal = $('.buytotal_precentage' + ths_id + '').val();
        var buyhalf = $('.buyhafe_precentage' + ths_id + '').val();
        var buypart = $('.buypart_precentage' + ths_id + '').val();


        var b_pricereal = (((Number(buypricereal) * Number(ths_val)) / 100) - Number(ths_val)) * -1;
        var b_total = ((Number(buytotal) * Number(ths_val)) / 100) + Number(ths_val);
        var b_hafe = ((Number(buyhalf) * Number(ths_val)) / 100) + Number(ths_val);
        var b_part = ((Number(buypart) * Number(ths_val)) / 100) + Number(ths_val);

        $('.buy_pricereal' + ths_id + '').val(b_pricereal);
        $('.buy_total' + ths_id + '').val(b_total);
        $('.buy_hafe' + ths_id + '').val(b_hafe);
        $('.buy_part' + ths_id + '').val(b_part);

        /*    var productCatId_level = $('#level').val();
         console.log('level = '+productCatId_level);
         var i , last_level;
         for( i = 1 ;  i <= productCatId_level ;  i++){
         if( i == productCatId_level ){
         last_level =  productCatId_level - 1;
         }
         }
         var productCatId = $('#productCatId'+last_level+'').val();
         console.log('productCatId = '+productCatId);
         //# get buytotal , buyhalf , buypart
         $.post('productControllerAjax.php?do=get_prices',{ productCatId:productCatId },function(data){
         data = JSON.parse(data);

         var b_pricereal = ( ( Number(data.buypricereal) * Number(ths_val) ) /100) + Number(ths_val) ;
         var b_total = ( ( Number(data.buytotal) * Number(ths_val) ) /100) + Number(ths_val) ;
         var b_hafe  = ( ( Number(data.buyhalf)* Number(ths_val) )  /100) + Number(ths_val) ;
         var b_part  = ( ( Number(data.buypart) * Number(ths_val) ) /100) + Number(ths_val) ;
         // console.log('b_total = '+b_total);
         $('.buy_pricereal'+ths_id+'').val(b_pricereal);
         $('.buy_total'+ths_id+'').val(b_total);
         $('.buy_hafe'+ths_id+'').val(b_hafe);
         $('.buy_part'+ths_id+'').val(b_part);
         });*/



    });

    //# m7md products form //and fatma
    $('body').on('keyup', '.buy_total1', function () {
        var ths_val = $(this).val();
        var ths_id = $(this).attr('data-id');


        var buyhalf = $('.buyhafe_precentage' + ths_id + '').val();
        var buypart = $('.buypart_precentage' + ths_id + '').val();



        var b_hafe = ((Number(buyhalf) * Number(ths_val)) / 100) + Number(ths_val);
        var b_part = ((Number(buypart) * Number(ths_val)) / 100) + Number(ths_val);


        $('.buy_hafe' + ths_id + '').val(b_hafe);
        $('.buy_part' + ths_id + '').val(b_part);

        /*    var productCatId_level = $('#level').val();
         console.log('level = '+productCatId_level);
         var i , last_level;
         for( i = 1 ;  i <= productCatId_level ;  i++){
         if( i == productCatId_level ){
         last_level =  productCatId_level - 1;
         }
         }
         var productCatId = $('#productCatId'+last_level+'').val();
         console.log('productCatId = '+productCatId);
         //# get buytotal , buyhalf , buypart
         $.post('productControllerAjax.php?do=get_prices',{ productCatId:productCatId },function(data){
         data = JSON.parse(data);

         var b_pricereal = ( ( Number(data.buypricereal) * Number(ths_val) ) /100) + Number(ths_val) ;
         var b_total = ( ( Number(data.buytotal) * Number(ths_val) ) /100) + Number(ths_val) ;
         var b_hafe  = ( ( Number(data.buyhalf)* Number(ths_val) )  /100) + Number(ths_val) ;
         var b_part  = ( ( Number(data.buypart) * Number(ths_val) ) /100) + Number(ths_val) ;
         // console.log('b_total = '+b_total);
         $('.buy_pricereal'+ths_id+'').val(b_pricereal);
         $('.buy_total'+ths_id+'').val(b_total);
         $('.buy_hafe'+ths_id+'').val(b_hafe);
         $('.buy_part'+ths_id+'').val(b_part);
         });*/



    });

});


function populateSellPrice()
{
    $("#new_productSellHalfPrice").val($("#new_productSellAllPrice").val());
    $("#new_productSellUnitPrice").val($("#new_productSellAllPrice").val());
}

//add product units
function addUnits()
{
    //var productItr = $("#productItr").val();
    var unitsItr = $("#unitsItr").val();
    unitsItr++;

    $("#unitsTable").append(
            '<tr id="unit_row' + unitsItr + '">'
            + '   <td>'
            + '       <div>'
            + '           <label>وحدة القياس</label>'
            + '           <select name="productunit' + unitsItr + '" id="productunit' + unitsItr + '" data-placeholder="اختر" class="select2_c' + unitsItr + ' aw_m1 chosenproduct"  tabindex="13">'
            + $("#productUnitsDiv_new").html()
            + '           </select>'
            + '       </div>'
            + '    </td>'
            + '   <td>'
            + '       <div>'
            + '           <label>عدد الوحدات</label>'
            + '           <input name="productnumber' + unitsItr + '" id="productnumber' + unitsItr + '" type="text" class="numberinput form-control" />'
            + '       </div>'
            + '    </td>'
            + '   <td>'
            + '       <div>'
            + '           <label>الباركود</label>'
            + '           <input name="proUnitParcode' + unitsItr + '" id="proUnitParcode' + unitsItr + '" type="text" class="numberinput form-control positiveNo" onblur="checkUnitbarcode(this.value, ' + unitsItr + ');"/>'
            + '       </div>'
            + '    </td>'
            + '   <td>'
            + '       <div>'
            + '           <label>سعر الشراء</label>'
            + '           <input name="proUnitBuyPrice' + unitsItr + '" id="proUnitBuyPrice' + unitsItr + '" type="text" class="numberinput form-control positivefloat" />'
            + '       </div>'
            + '    </td>'
            + '   <td>'
            + '       <div>'
            + '           <label>سعر الجملة</label>'
            + '           <input name="proUnitSellAllPrice' + unitsItr + '" id="proUnitSellAllPrice' + unitsItr + '" type="text" class="numberinput form-control positivefloat" />'
            + '       </div>'
            + '    </td>'
            + '   <td>'
            + '       <div>'
            + '           <label>سعر نص جملة</label>'
            + '           <input name="proUnitSellHalfPrice' + unitsItr + '" id="proUnitSellHalfPrice' + unitsItr + '" type="text" class="numberinput form-control positivefloat" />'
            + '       </div>'
            + '    </td>'
            + '   <td>'
            + '       <div>'
            + '           <label>سعر القطاعى</label>'
            + '           <input name="proUnitSellUnitPrice' + unitsItr + '" id="proUnitSellUnitPrice' + unitsItr + '" type="text" class="numberinput form-control positivefloat" />'
            + '       </div>'
            + '    </td>'
            + '    <td>'
            + '       <a id="remove' + unitsItr + '" onclick="removeUnits(' + unitsItr + ');"  class="removeUnits">X</a>'
            + '    </td>'
            + '</tr>'
            );
    $('.select2_c' + unitsItr).select2();

    $(".numberinput").forceNumeric();

    $("#unitsItr").val(unitsItr); //assign new iteration value
}

function removeUnits(unitItr)
{
    // delete by parents
    //$("#remove"+unitItr).parent().parent().remove();

    $("#unit_row" + unitItr).remove();
    return false;
}


////// Adding new product with modal box /////////////

function showModalBox(newLinkId)
{
    $(".awdatepicker").datepicker({
        format: 'yyyy-mm-dd'
    });



    $("select").select2();


    $("#newLinkCurrentId").val(newLinkId);
    emptyModalForm();


    var itr = newLinkId;
//alert(itr)
//	if($("#product"+itr).select2('val') != "-1" && $("#product"+itr).select2('val') != null && $("#product"+itr).select2('val') != '' )//user had choosed a product
//	{//edit product

//		$productId = $("#product"+itr).val();
//		$tabIndex = $("#product"+itr).attr("tabindex");

    //$.ajax({
//			type: 'GET',
//			url: 'buyBillControllerAjax.php?do=editProduct&id='+$productId+'&itr='+itr+'&tabIndex='+$tabIndex,
//			success: function(data) {
//				//alert(data);
//				if(data == '1')//Error
//				{
//					alert("البرنامج لم يستطع الوصول لبيانات المنتج ... الرجاء المحاولة مرة أخرى");
//				}
//				else
//				{
//				$('#productModal').modal('show');
//					$(".productForm").html(data);
//
//					$("select").select2();
//
//
//				}
//			}
//        });
//	}
    //else
    //{//insert new product
    //get new product parcode
    //	var parcode = $("#parcode"+itr).val();
    //check if this operation is editing or adding
    //if(parcode != null && parcode != "")
    //{
    //}
    //	else
    //	{
    $('#productModal2').modal('show');
    $("#productInfo").css("display", "block");
    $(".productForm").load('buyBillControllerAjax.php?do=productAddModal', function () {
        $(".select2_customj").select2();
        $("#newLinkCurrentId").val(itr);
    });
    //	}
    //}

    $("select").select2();
    $(".numberinput").forceNumeric();
}


function insertIntoTemp(e)
{


    //يشوف هل الإسم موجود في نفس التصنيف ولا لأ، لو مش موجود يضيفه
    var name = document.getElementById("new_productName").value;
    if ($("#productAddMultiCatLevel").length > 0)
    {
        var catid = $(".productCat:last").val();
    } else
    {
        var catid = document.getElementById("productCatId0").value;
    }
    if ($('#productInfo').validate().form())
    {
        if (name != '' && name != null)
        {
            //## size color part ###############################################
            if ($('.sizeColorQuantity').length > 0) {
                //its okay there is quantity
            } else {
                //draw it and keep it hidden
                getSizeColorArrays();
                if (sizes.length > 0 && colors.length > 0) {
                    drawSizeColor();
                }
            }
            //##################################################################
            $.ajax({
                url: 'checkRedundantNames.php?name=' + name + '&tablename=product&catid=' + catid,
                success: function (data) {
                    if (data == '0')
                    {
                        //alert("insertIntoTemp");
                        var newLinkCurrentId = $("#newLinkCurrentId").val();
                        var itr = newLinkCurrentId;
                        var totalQuantity = $("#totalQty").html();
                        var billnameid = $("#billnameid").val();
                        console.log('itr = ' + itr + ' billnameid = ' + billnameid);

                        $tabIndex = $("#product" + itr).attr("tabindex");

                        $.ajax({
                            type: 'POST',
                            url: 'buyBillControllerAjax.php?do=temp&itr=' + itr + '&tabIndex=' + $tabIndex + '&billnameid=' + billnameid,
                            data: $("#productInfo").serialize(),
                            success: function (data) {
                                if (data != "1") //not error
                                {
                                    //put data in row
                                    $("#newProduct" + itr).html(data);

                                    //$newItr = $("#newItr").val();

                                    $('select.select2_unit' + itr).select2();

                                    formatResult2 = function (data) {
                                        return  data.text;
                                    }

                                    $(".select2productx" + itr).select2({
                                        placeholder: "إسم المنتج",
                                        minimumInputLength: document.getElementById("searchvalue").value,
                                        //  minimumInputLength: 3,
                                        multiple: false,
                                        quietMillis: 100,
                                        ajax: {
                                            url: "buyBillControllerAjax.php?do=getProductsnotcollective",
                                            dataType: 'json',
                                            data: function (term, page) {
                                                return {
                                                    term: term, //search term
                                                    page_limit: 10, // page size
                                                    searchWithCatAndProductNameOnly: document.getElementById("searchWithCatAndProductNameOnly").value,
                                                };
                                            },
                                            results: function (data) {
                                                //alert("data: "+data);
                                                return {results: data};
                                            }
                                        },
                                        formatResult: formatResult2,
                                        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
                                    /************************/
                                    $("#product" + itr).on("change", function () {
                                        //alert("change product");
                                        //here get the price of product from ajax
                                        //the selected value of drop downlsit
                                        var theselectedvalue = $(this).val();
                                        var returnBillFlag = 0;

                                        //load the price
                                        //$("#propricechange"+itr).html('<img src="../views/default/images/loader/6.gif" alt="">');

                                        //////////////////////////////////////////////////
                                        var supplier = $('#supplier').val();
                                        $.ajax({
                                            url: 'buyBillControllerAjax.php?do=units&return=' + returnBillFlag + '&itrs=' + itr + '&tabindex=13&productid=' + theselectedvalue + '&supplier=' + supplier + '&billnameid=' + $('#billnameid').val(),
                                            type: "get",
                                            success: function (data) {
                                                //alert(data);
                                                var response = $.parseJSON(data);
                                                //populate unit
                                                $('#unitDiv' + itr).html(response.unitString);
                                                $("#productUnitsDiv").empty();
                                                $("#unitDiv" + itr + " option").clone().appendTo("#productUnitsDiv");
                                                $('.select2_unit' + itr).select2();

                                                //populate buy price
                                                $('#propricechange' + itr).html(response.priceString);

                                                //here all code that will happend with loaded content
                                                //the number of rows of products
                                                var noitr = document.getElementById("hidden_itr").value

                                                // get the total of product
                                                calcuproduct(itr);

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

                                                totalquantity(noitr);

                                                //get the general discount
                                                thegeneraldiscount();

                                                //get the general payed
                                                thegeneralpayed();

                                                // calculate the rest of debt
                                                therestofdebt();

                                                //add another row if there is no any new rows
                                                $proId = document.getElementById("product" + noitr).value;
                                                if ($proId != null && $proId != '-1' && $proId != '')
                                                {
                                                    $("#addpro").trigger('click');
                                                }
                                                //load the jquery checker for number only
                                                // $.getScript('../views/default/js/head_scripts.js');

                                                $('.select2_unit' + itr).select2();

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

                                        $('.select2_unit' + itr).select2();
                                    });

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

                                    //populate product select with value and label
                                    var productId = $("#productid_hidden" + itr).val();

                                    if (productId != null && productId != '' && productId != '-1')
                                    {
                                        //alert("draw select2");
                                        $.ajax({
                                            url: 'buyBillControllerAjax.php?do=productData&id=' + productId + '',
                                            type: "get",
                                            success: function (data) {
                                                //alert(data);
                                                if (data != null && data != "")
                                                {
                                                    var response = $.parseJSON(data);
                                                    //send value as a string of id and name to the initSelection function
                                                    $("#product" + itr).select2('val', ['' + response.id + ':' + response.text + ''], true);// true is a flag to allow triggering the change event which is false by default
                                                }
                                            },
                                            error: function () {
                                                alert("لقد حدث خطأ أثناء إجراء العملية");
                                            }
                                        });
                                    }
                                    /***********************************/
                                } else
                                {
                                    alert("يرجى إدخال البيانات بشكل صحيح");
                                }
                            }
                        });
                        $('select').select2();
                        //empty modal box's inputs' values
                        $('#productModal2').modal('hide');
                        emptyModalForm();
                    } else if (data == '1')
                    {
                        userClickedYes = false;
                        $("#new_productName").val("");
                        $("#new_productName").focus();
                        alert("هذا الإسم مستخدم في هذا التصنيف");
                        $("#new_nameError").css("display", "block");
                    }
                }
            });
        }
    }
}


function emptyModalForm()
{
    $('#productInfo').find(':input').each(function () {
        var type = this.type, tag = this.tagName.toLowerCase();
        if (type == 'text' || type == 'password' || tag == 'textarea')
            this.value = '';
        else if (type == 'checkbox' || type == 'radio')
            this.checked = false;
        else if (tag == 'select')
            this.value = '-1';
    })

    $('#SizeColorTB').html("");
    $('#sizeColorItr').val(0);
}


function closeProductForm()
{
    $('#productModal2').modal('hide');
    emptyModalForm();
}
////////////////// End adding new product /////////////////////////////////
$('[id^="proUnitParcode"]').live('keypress', function (e) {
    if (e.which == 13) { //Enter
        e.preventDefault();
        //get pro itr//unitsTable1
        var val = $(this).val();
        if (val != "") {
            addUnits();
        }
        return false
    }
})

//////// add serial page ///////////////////////////////////////////////////////
if ($('#addserialPage').length > 0) {
    $(document).ready(function () {
        if ($('.deserialize').length > 0) {
            $('#deserializeBtn').show();
        }
        //$('#serialnumber11').select();
        //$('#serialnumber11').focus();
        $('.myserial:not(:disabled)').first().select();
    });

    $('[id^="serialnumber"]').live('keydown', function (e) {
        if (e.keyCode == 13) {
            e.preventDefault();
            e.stopPropagation();
            var allitr = Number($('#allitr').val());
            var current = Number($(this).data('allitr'));
            current++;
            for (var i = current; i <= allitr; i++) {
                if ($('.myserial[data-allitr="' + i + '"]').length > 0) {
                    $('.myserial[data-allitr="' + i + '"]').first().select();
                    return true;
                }
            }

        }
    });
    $('[id^="serialnumber"]').live('blur', function (e) {
        var thisSerial = $(this).val();
        if (thisSerial != "") {
            $('.myserial').removeClass('repeated');
            $('#subbtn').removeClass('repeated2');
            $('#subbtn').prop('type', 'submit');


            var theFlag = 1;
            $('.myserial').each(function () {
                var thisid = $(this).attr('id');
                var thisSerial = $(this).val();
                var returnedFlag = checkRepeated(thisid, thisSerial);
                if (returnedFlag == 0) {
                    theFlag = 0;
                }
            });

            if (theFlag == 1) {
                $('#subbtn').removeAttr('disabled');
            } else {
                $('#subbtn').addClass('repeated2');
                $('#subbtn').prop('type', 'button');
                //alert('بعض السيريلات مكرره')
            }

        }

    });
    $('#subbtn').live('click', function (e) {
        if ($('#subbtn').prop('type') == 'submit') {
            e.preventDefault();
            e.stopPropagation();
            $('#subbtn').prop("disabled", true);
            $('#subbtn').css("background", "red");
            $("#billform").submit();
        }
    });
    function checkRepeated(thisid, thisSerial) {
        var flag = 1;
        $('.myserial').each(function () {
            var rowid = $(this).attr('id');
            var rowSerial = $(this).val();
            if (rowid != thisid && rowSerial != "" && thisSerial == rowSerial) {
                $('#' + thisid).addClass('repeated');
                $('#' + rowid).addClass('repeated');
                flag = 0;
            }
        });
        return flag;
    }

    $('.removethis').live('click', function (e) {
        var proitr = $(this).data('proitr');
        $('tr[data-proitr="' + proitr + '"]').remove();
    });
}
////////////////////////////////////////////////////////////////////////////////