var formatResult;

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

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

    //alert($('#finalProductId').val());


    /*$("#product"+q).change(function() {


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

     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();

     });

     });*/
});





var rowitr = document.getElementById("rowitr").value;
for (var q = 1; q <= rowitr; q++) {
    initializeSelect2(q);
}

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

     });*/

    var theselectedvalue = $('#oldproduct' + q).val();
    $('#unitDiv' + q).load('damagedProductAjaxController.php?do=unitsWithItration&productid=' + theselectedvalue + '&itr=' + q + '', function () {
        $("#unitId" + q).select2();
        $("#unitId" + q).select2("data", {id: $('#oldUnit' + q).val(), text: $('#oldUnitName' + q).val()});
    });
}




