var formatResult;


$(document).ready(function (e) {






//alert(document.getElementById("searchvalue").value);
    formatResult = function (data) {
        return  data.text;
    }





    //assign select2 properties
    $(".getFinalProductsWithOutProductionRate").select2({
        placeholder: "إسم المنتج",
        minimumInputLength: document.getElementById("searchvalue").value,
        multiple: false,
        quietMillis: 100,
        ajax: {
            url: "sellbillAjaxController.php?do=getFinalProductsWithOutProductionRate", //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);
        }
    });



    $(".select2RawMaterials").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
                    notRawMaterialsOnly: $('#notRawMaterialsOnly').val()
                };
            },
            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);
        }
    });



    $("#product1").change(function () {


        //alert(222);

        var theselectedvalue = $(this).val();
        //alert('damagedProductAjaxController.php?do=units&productid='+theselectedvalue);
        $('#unitDiv1').load('damagedProductAjaxController.php?do=unitsWithItration&productid=' + theselectedvalue + '&itr=1', function (response, status, xhr) {
            //reload the dropdownlist and jquery files
            //$('select').chosen();
            $('select').select2();
            if (status == "error") {
                var msg = "Sorry but there was an error: ";
                $("#error").html(msg + xhr.status + " " + xhr.statusText);
            }
            calcCollectiveProductCost();
        });

    });





////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

//add new row
    $("#addrow").click(function () {

        //the iltration of rows to increment the  name of rows
        $i = Number(document.getElementById('rowitr').value);
        $i++;

        $("#table").append(
                '<tr>'
                + '  <td>'

                + '<input type="hidden"  class="select2RawMaterials wdt300" name="product' + $i + '" id="product' + $i + '" data-placeholder=" اختر منتج خام"  />'

                + ' </td>'


                + '  <td><div id="unitDiv' + $i + '">'
                + '  <select class="select2 wdt300" name="unitId' + $i + '" id="unitId' + $i + '" >'
                + '  <option value="-1"> اختر المنتج اولا</option>'
                + $("#unitDiv" + $i).html()

                + '   </select></div>'
                + '  </td>'


                + '<td>'
                + '<input type="text" class="form-control check" value="" required  name="input' + $i + '" id="input' + $i + '" "/>'
                + '</td>'

                + '<td>'
                + '<input name="inputt' + $i + '" id="inputt' + $i + '" class="form-control positive"/>'
                + '</td>'
                + '<td id="' + $i + '">'
                + '<button id="remove' + $i + '" type="button" class="close flt-none removeicon removeproduct" aria-hidden="true">&times;</button>'
                + '</td>'
                + '</tr>');


        $("#product" + $i).select2({
            placeholder: "إسم المنتج",
            minimumInputLength: document.getElementById("searchvalue").value,
            //minimumInputLength: 3,
            multiple: false,
            quietMillis: 100,
            ajax: {
                url: "sellbillAjaxController.php?do=GetRawMaterials",
                dataType: 'json',
                data: function (term, page) {
                    return {
                        term: term, //search term
                        page_limit: 10, // page size
                        notRawMaterialsOnly: $('#notRawMaterialsOnly').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]};
                callback(data);
            }
        });


        $('select').select2();

        $("#product" + $i).change(function () {


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

            //alert(222);

            var theselectedvalue = $(this).val();
            //alert('damagedProductAjaxController.php?do=units&productid='+theselectedvalue+'&itr='+n+'' );
            $('#unitDiv' + n).load('damagedProductAjaxController.php?do=unitsWithItration&productid=' + theselectedvalue + '&itr=' + n + '', function (response, status, xhr) {
                //reload the dropdownlist and jquery files
                //$('select').chosen();
                $('select').select2();
                if (status == "error") {
                    var msg = "Sorry but there was an error: ";
                    $("#error").html(msg + xhr.status + " " + xhr.statusText);
                }
                calcCollectiveProductCost();
            });


            $('.select2').select2();




        });




        document.getElementById('rowitr').value = $i;
        // $("#product" + n).change(function() {

    });


//remove row and calculate new percentage
    $(document).on('click', '.removeicon', function () {

        $itemRemove = Number($(this).parent().attr("id"));

        //var productid = document.getElementById("product"+$itemRemove).value;
        if ($('#percentage').length > 0 && $('#input' + $itemRemove).length > 0) {
            $x = Number(document.getElementById('percentage').innerHTML);
            $y = Number(document.getElementById('input' + $itemRemove + '').value);
            $newtotal = $x - $y;
            //alert($newtotal);
            document.getElementById('percentage').innerHTML = $newtotal;
        }

        //document.getElementById('input'+$itemRemove+'').value="deleted";

        //$value=document.getElementById('input'+$itemRemove+'').value;
        //alert($value);

        // delete by partents
        //this make it not sent by post
        $(this).parent().parent().remove();

        calcCollectiveProductCost();
        //delete row
        //this allow it to be sent in post

        //$("#trno+'$itemRemove'").style.display = 'none';


        //anotherProduct(productid,$itemRemove);



        return false;

    });


//check if iput value is number and calculate new percentage
    $(document).on('blur', '.check', function () {

        var numericExpression = /^(?:[1-9]\d*|0)?(?:\.\d+)?$/;

        if (this.value.match(numericExpression))
        {
            //here means +ve float number
            this.style.backgroundColor = "white";
            if (this.value > 100)
            {
                this.value = 100;
                //alert("لابد ان يكون الرقم من 0 الى 100");
                this.style.backgroundColor = "yellow";
            }

            $rows = Number(document.getElementById("rowitr").value);
            //alert($rows);
            $totalpercentage = 0;
            for ($i = 1; $i < $rows + 1; $i++)
            {
                //alert($("#input"+$i+"").length);
                if ($("#input" + $i + "").length != 0)
                {
                    $x = Number(document.getElementById("input" + $i + "").value);
                    //alert($x);
                    $totalpercentage += $x;
                }

            }

            document.getElementById('percentage').innerHTML = $totalpercentage;


        }
        else
        {
            //here it is not +ve float
            this.value = 0;
            this.style.backgroundColor = "yellow";
        }



        //var id=this.id.substr(5);
        //calculate sum

    });


//check if input is number(float)and +ve
    $(document).on('blur', '.positive', function () {


        //this check for +ve int
        /*var numericExpression = /^[0-9]+$/;

         if(this.value.match(numericExpression)) {
         */
        /*alert ("true");*/
        /* this.style.backgroundColor = "white";

         } else {
         this.value = 0;
         //alert("لابد  ان يكون رقم صحيح موجب");
         this.style.backgroundColor = "yellow";

         }*/


        //this check for +ve float
        var numericExpression = /^(?:[1-9]\d*|0)?(?:\.\d+)?$/;
        if (this.value.match(numericExpression))
        {
            this.style.backgroundColor = "white";
            if (this.value == 0)
            {
                this.value = 0;
                this.style.backgroundColor = "yellow";
            }

        }
        else
        {
            this.value = 0;
            //alert("لابد  ان يكون رقم صحيح موجب");
            this.style.backgroundColor = "yellow";
        }





    });


    $(document).on('keyup', "[id^='unitId']", function () {
        calcCollectiveProductCost();
    });
    $(document).on('change', "[id^='inputt']", function () {
        calcCollectiveProductCost();
    });
//stop default action of form if {no equation name} or (total percentage !=100) or {one of products list with choice = -1}
    $("#save").click(function (event) {

        //check if there is an equation name
        $name1 = document.getElementById('name').value;
        if ($name1.length > 0)
        {
            //true contine
            document.getElementById('name').style.backgroundColor = "white";
        }
        else
        {
            document.getElementById('name').style.backgroundColor = "yellow";
            event.preventDefault();
            return false;
        }

        //remove last row if empty
        var lastItr = $('[id^="product"]:last').attr('id').substr(7);
        if ($('#product' + lastItr).val() == "" && $('#unitId' + lastItr).val() == -1 && $('#input' + lastItr).val() == "" && $('#inputt' + lastItr).val() == "") {
            $('#remove' + lastItr).click();
        }


        //check if final product name is choosen
        $finalProduct = document.getElementById('finalProductId').value;
        if ($finalProduct.length > 0)
        {
            //true contine
        }
        else
        {
            event.preventDefault();
            alert(" من فضلك اختر اسم المنتج النهائى");
            return false;
        }


        $rows = Number(document.getElementById("rowitr").value);
        //check if raw materials are choosen
        for ($i = 1; $i < $rows + 1; $i++)
        {
            $product = document.getElementById("product" + $i + "").value;

            if ($product.length > 0)
            {
                //true contine
            }
            else
            {
                event.preventDefault();
                alert("من فضلك اختر المواد الخام اولا");//will prevent default form submission
                return false;
            }

        }

        //check if units are choosen
        for ($i = 1; $i < $rows + 1; $i++)
        {
            $unit = document.getElementById("#unitId" + $i + "").value;

            if ($unit.length > 0)
            {
                //true contine
            }
            else
            {
                event.preventDefault();
                alert(" من فضلك اختر وحدات القياس اولا");//will prevent default form submission
                return false;
            }
        }


        /*//check if percentage in any row =0
         for($i=1;$i<$rows+1;$i++)
         {
         alert(Number(document.getElementById("input"+$i+"").value));
         if($("#input"+$i+"").length != 0)
         {
         $x=Number(document.getElementById("input"+$i+"").value);
         if($x==0)
         {
         document.getElementById("input"+$i+"").style.backgroundColor="yellow";
         event.preventDefault();
         return false;
         }
         }
         else
         {
         alert(1111);
         document.getElementById("input"+$i+"").style.backgroundColor="yellow";
         event.preventDefault();
         return false;
         }
         }*/





    });

    function calcCollectiveProductCost() {
        //set variables to sum
        var productBuyPrice = 0;
        var lastbuyprice = 0;
        var lastbuyprice_withDiscount = 0;
        var meanbuyprice = 0;
        var meanbuyprice_withDiscount = 0;
        var overAllAveragePrice = 0;
        $("[id^='inputt']").each(function () {
            var itr = $(this).attr('id').substr('6');
            if ($('#productBuyPrice' + itr).length > 0) {
                var val = Number($(this).val());
                var pronum = Number($('table[id="table"] #unitId' + itr + ' option:selected').attr('data-pronum'));

                productBuyPrice += Number($('table[id="table"] #productBuyPrice' + itr).val()) * val * pronum;
                lastbuyprice += Number($('table[id="table"] #lastbuyprice' + itr).val()) * val * pronum;
                lastbuyprice_withDiscount += Number($('table[id="table"] #lastbuyprice_withDiscount' + itr).val()) * val * pronum;
                meanbuyprice += Number($('table[id="table"] #meanbuyprice' + itr).val()) * val * pronum;
                meanbuyprice_withDiscount += Number($('table[id="table"] #meanbuyprice_withDiscount' + itr).val()) * val * pronum;
                overAllAveragePrice += Number($('table[id="table"] #overAllAveragePrice' + itr).val()) * val * pronum;
            }
        });
        $('#productBuyPrice').html(productBuyPrice.toFixed(1));
        $('#lastbuyprice').html(lastbuyprice.toFixed(1));
        $('#lastbuyprice_withDiscount').html(lastbuyprice_withDiscount.toFixed(1));
        $('#meanbuyprice').html(meanbuyprice.toFixed(1));
        $('#meanbuyprice_withDiscount').html(meanbuyprice_withDiscount.toFixed(1));
        $('#overAllAveragePrice').html(overAllAveragePrice.toFixed(1));

        $('#productBuyPrice_h').val(productBuyPrice.toFixed(1));
        $('#lastbuyprice_h').val(lastbuyprice.toFixed(1));
        $('#lastbuyprice_withDiscount_h').val(lastbuyprice_withDiscount.toFixed(1));
        $('#meanbuyprice_h').val(meanbuyprice.toFixed(1));
        $('#meanbuyprice_withDiscount_h').val(meanbuyprice_withDiscount.toFixed(1));
        $('#overAllAveragePrice_h').val(overAllAveragePrice.toFixed(1));
    }

    if ($("[id^='inputt']").length > 0) {
        //it is edit
        //calcCollectiveProductCost();

    }
});



