var formatResult;

$(document).ready(function (e) {
    $("#finalProductId").select2("data", {id: $('#oldfinalproduct').val(), text: $('#oldfinalproductname').val()});
});





var rowitr = document.getElementById("rowitr").value;



//alert(myolditr);
//var x=1
for (var q = 1; q <= rowitr; q++)
{
    initializeSelectt2Raw(q);
}


function initializeSelectt2Raw(q) {



    $("#product" + 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 = $('#oldproduct' + q).val();
    $("#product" + q).select2("data", {id: $('#oldproduct' + q).val(), text: $('#oldproductname' + q).val()});
    $('#unitDiv' + q).load('damagedProductAjaxController.php?do=unitsWithItration&productid=' + theselectedvalue + '&itr=' + q + '', function () {
        $('select').select2();
        $("#unitId" + q).select2("data", {id: $('#oldUnit' + q).val(), text: $('#oldUnitName' + q).val()});
    });


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


        var currentId = $(this).attr('id');
        n = currentId.substr(7);
        var theselectedvalue = $(this).val();
        // alert('damagedProductAjaxController.php?do=unitsWithItration&productid='+theselectedvalue+'&itr='+n+'' );
        $('#unitDiv' + n).load('damagedProductAjaxController.php?do=unitsWithItration&productid=' + theselectedvalue + '&itr=' + n + '', function () {
            //reload the dropdownlist and jquery files
            $('select').chosen();
            $("#unitId" + n).select2("data", {id: $('#oldUnit' + n).val(), text: $('#oldUnitName' + n).val()});
        });

    });





}