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
                };
            },
            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 () {
            //reload the dropdownlist and jquery files
            //$('select').chosen();
        });

        $('#addrow').trigger('click');

    });





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

//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
                    };
                },
                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 () {
                //reload the dropdownlist and jquery files
                //$('select').chosen();

            });
            $('#addrow').trigger('click');

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


        //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";
        }





    });




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




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



});

$('.checkExist').on('change', function () {
    var value = $(this).val();
    var editId = $(this).attr('data-editId');

    $.post('productionEquationAjaxController.php?do=chekExistTitle', {value: value, editId: editId}, function (data) {
        if (data != 1)
        {
            document.getElementById('name').style.backgroundColor = "yellow";
            $('#nameError').css('display', 'block');
        }
        else {
            document.getElementById('name').style.backgroundColor = "white";
            $('#nameError').css('display', 'none');
        }
    });
});



