var formatResult;

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

    //alert($('#oldfinalproduct').val());
    //alert($('#oldfinalproductname').val());
    $("#finalProductId").select2("data", {id: $('#oldfinalproduct').val(), text: $('#oldfinalproductname').val()});

    if ($('#outItr').val() >= 1)
    {
        var i = 1;
        $('.outputSelect').each(function () {
            $('#product' + i).select2("data", {id: $('#productOut' + i).val(), text: $('#productnameOut' + i).val()});
            i++;
        });
    }

    if ($('#wasteItr').val() >= 1)
    {
        var j = 1;
        $('.wasteproduct').each(function () {
            $('#wasteproduct' + j).select2("data", {id: $('#productWaste' + j).val(), text: $('#productnametWaste' + j).val()});
            j++;
        });
    }

    if ($('#rowitr').val() >= 1)
    {
        for (i = 0; i <= $('#rowitr').val(); i++) {
            initializeSelectt2Raw(i);
        }
        calcSumOfRawMaterials();
    }


});

//stop default action of form if {no equation name} or (total percentage !=100) or {one of products list with choice = -1}
$("#executeEdit").click(function (event) {

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

    $proOrderId = document.getElementById('proOrderId').value;
    if ($proOrderId.length > 0)
    {
//true contine
        document.getElementById('proOrderId').style.backgroundColor = "white";
    } else
    {
        document.getElementById('proOrderId').style.backgroundColor = "yellow";
        event.preventDefault();
        return false;
    }

    $num = document.getElementById('proNum').value;
    if ($num.length > 0)
    {
//true contine
        document.getElementById('proNum').style.backgroundColor = "white";
    } else
    {
        document.getElementById('proNum').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;
    }

    addDataAndReturn();
});

$("#editBtn").click(function (event) {

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

    $proOrderId = document.getElementById('proOrderId').value;
    if ($proOrderId.length > 0)
    {
//true contine
        document.getElementById('proOrderId').style.backgroundColor = "white";
    } else
    {
        document.getElementById('proOrderId').style.backgroundColor = "yellow";
        event.preventDefault();
        return false;
    }

    $num = document.getElementById('proNum').value;
    if ($num.length > 0)
    {
//true contine
        document.getElementById('proNum').style.backgroundColor = "white";
    } else
    {
        document.getElementById('proNum').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;
    }
});


function initializeSelectt2Raw(q) {



    $("#pro" + q).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};
            }
        },
        formatResult: formatResult,
        initSelection: function (element, callback) {
            var item = element.val().split(':');
            var data = {id: item[0], text: item[1]};
            callback(data);
        }
    });

    var theselectedvalue = $('#oldproId' + q).val();
    $("#pro" + q).select2("data", {id: $('#oldproId' + q).val(), text: $('#oldproName' + q).val()});
    $('#unitDiv' + q).load('damagedProductAjaxController.php?do=unitsWithItration&productid=' + theselectedvalue + '&itr=' + q + '', function () {
        //change comming name,id attributes
        $('#unitId' + q).attr('id', 'unit' + q);
        $('#unit' + q).attr('name', 'unit' + q);

        $('select').select2();
        $("#unit" + q).select2();
        $("#unit" + q).select2("data", {id: $('#oldunitId' + q).val(), text: $('#oldunitName' + q).val()});
    });


    ///////////  دى بسمعانا/////
    $("#pro" + q).change(function () {


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

        $('#cost' + q).val($("#pro" + q).select2('data').productBuyPrice).change();
        $('#actualCost' + q).val($('#cost' + q).val() * $('#actual' + q).val()).change();
        $('#unitDiv' + q).load('damagedProductAjaxController.php?do=unitsWithItration&productid=' + theselectedvalue + '&itr=' + q + '', function () {
            //change comming name,id attributes
            $('#unitId' + q).attr('id', 'unit' + q);
            $('#unit' + q).attr('name', 'unit' + q);


            $('select').select2();
            $("#unit" + q).select2("data", {id: $('#oldunitId' + q).val(), text: $('#oldunitName' + q).val()});
        });

    });





}
function calcSumOfRawMaterials() {
    $('.quantity').on('keyup change', function () {
        var sum = 0;
        $('.quantity').each(function () {
            sum += Number($(this).val());
        });
        $('#totalQuantitySpan').html(sum);
    });
    $('.actual').on('keyup change', function () {
        var sum = 0;
        $('.actual').each(function () {
            sum += Number($(this).val());
        });
        $('#totalActualQuantity').html(sum);
    });
    $('.cost').on('keyup change', function () {
        var sum = 0;
        $('.cost').each(function () {
            sum += Number($(this).val());
        });
        $('#totCost').html(sum);
    });
    $('.actualCost').on('keyup change', function () {
        var sum = 0;
        $('.actualCost').each(function () {
            sum += Number($(this).val());
        });
        $('#actualTotalCost').html(sum);
        $('#actlTotalCost').val(sum);
    });
}
function addDataAndReturn()
{
//    $('#bn').removeAttr('disabled');
    $("#form1").attr("action", "productionExecutionController.php?do=executeUpdate");
}


