//the common itration and the start
$tabindexnumf = 3;
$rtabindexnum = 302;
$("#addpro").click(function () {
    $("#addunit").empty();
    var $aw_if = Number($('#hidden_itr').val()) + 1;








    //alert('userstoreid'+userstoreid);
    //alert('morestore'+morestore);
    $xx = '';
    $xx += '<tr id="productraw' + $aw_if + '">';


    $xx += '<td><span class="proDetails" data-pro="product' + $aw_if + '">' + $aw_if + '</span></td>';
    //        if (settingparcode == 0)
    //        {
    $xx += '<td class="">';


    $xx += '<div id="productparcode' + $aw_if + '">'
            + '  <input type="text" name="parcode' + $aw_if + '" id="parcode' + $aw_if + '" class="form-control  txt-nonraduis" tabindex="' + $tabindexnumf + '" onkeypress="getproductbyParcode(event,this.value, ' + $aw_if + ');" size="3"  placeholder="الباركود" />'

            + ' <input name="parcodeType' + $aw_if + '" id="parcodeType' + $aw_if + '" type="hidden"/> '
            + '<input name="productserailid' + $aw_if + '" id="productserailid' + $aw_if + '" type="hidden" /> '
            + ' <input name="productQty' + $aw_if + '" id="productQty' + $aw_if + '" type="hidden" />'
            + '</div></td>';



    $xx += '<td>'
            + '<div id="productdiv' + $aw_if + '">'
            + '<input type="hidden"id="product' + $aw_if + '" name="product' + $aw_if + '"  class="select2product' + $aw_if + ' wdt100"  data-placeholder="اختر منتج" tabindex="' + $tabindexnumf + '" />'

            + '</div>'
            + '</td>';

    //# check to hide
    var hidden_unit = '';
    $('#containerpros .check_tr_unit:first').each(function (e) {//first only is enough with is in table head
        var ths = $(this);
        if (ths.hasClass('hidden')) {
            hidden_unit = 'hidden';
            return false;
        }
    });

    $xx += '<td class="' + hidden_unit + '">';
    $xx += '<div id="productunitdiv' + $aw_if + '">'
            + '<input type="hidden" name="proNum' + $aw_if + '" id="proNum' + $aw_if + '" value=""/>'
            + '<select id="productunit' + $aw_if + '" name="productunit' + $aw_if + '" class="select2 wdt100" tabindex="' + $tabindexnumf + '">'

            + $("#addunit").html()
            + '</select>'
            + '</div>'
            + '</td> '



            + '<td class="">'
            + '<input type="text" name="pronum' + $aw_if + '" id="pronum' + $aw_if + '"  class="form-control txt-nonraduis getprototal enteraction numberinput positivefloat" onKeyUp="checkquantity(' + $aw_if + ', event);" value="1" tabindex="' + $tabindexnumf + '" />'
            + '</td>'



            //////////////////////////////value dicount by hazem///////////////////////////




            + '<td>'
            + '   <input type="hidden" name="tempSaveBillIdRow' + $aw_if + '" id="tempSaveBillIdRow' + $aw_if + '" value="0">'
            + '	<button id="remove' + $aw_if + '" type="button" class="close flt-none removeicon removeproduct" aria-hidden="true">&times;</button>'
            + '</td>'
            + '</tr>';
    $("#containerpros").append($xx);
    $(".positiveNo").forcepositiveNum();
    $(".numberinput").forceNumeric();
    $(".positivefloat").forcepositivefloat();

    // varaible to contains the common itration
    var n = $aw_if;
    var $tabindexnumf = $tabindexnumf;
    $(".select2product" + n).select2({
        placeholder: "إسم المنتج",
        minimumInputLength: document.getElementById("searchvalue").value,
        //minimumInputLength: 3,
        multiple: false,
        quietMillis: 100,
        ajax: {
            url: "sellbillAjaxController.php?do=getProducts",
            dataType: 'json',
            data: function (term, page) {
                return {
                    term: term, //search term
                    page_limit: 10, // page size
                    storeid: 1, //document.getElementById("storeid").value,
                    // hiddenpricetype: document.getElementById("pricetypepro" + n).value, //pricetype
                    //    searchWithCatAndProductNameOnly: document.getElementById("searchWithCatAndProductNameOnly").value,
                };
            },
            results: function (data) {
                return {results: data};
            }
        },
        formatResult: function (data) {
            return data.text;
        },
        initSelection: function (element, callback) {
            var item = element.val().split(':');
            //  var data = {id: item[0], text: item[1]};
            var data = {id: item[0], text: item[1], productquantity: item[2], price: item[3]};
            callback(data);
        }
    })
    //////////////////////////////////////////////////////////////////////////////////////
    //action in change of created dropdown list  to load the units
    $("#product" + n).change(function () {

        //the selected value in drop down list
        var theselectedvalue = $(this).val();
        if (theselectedvalue != "" && theselectedvalue != "null" && theselectedvalue != null && theselectedvalue != "-1")
        {

            $("#addunit").empty();
            //////////////////////////////////////////////////
            if (theselectedvalue.indexOf("hasSizeColor") == 0) {
                //when selecting sizecolor product make sure not to sent parcode
                //not stoping it in php to keep case of using sizecolor parcode working
                var productParcode = '';
            } else {
                var productParcode = $("#parcode" + n).val();
            }

            var OtherParameters = '';

            ///load unit , parcode, and price
            $.ajax({
                url: 'sellbillAjaxController.php?do=getunit&itrs=' + n + '&tabindex=' + $tabindexnumf + '&productid=' + theselectedvalue + '&parcode=' + productParcode,
                type: "get",
                success: function (data) {
                    var response = $.parseJSON(data);
                    //populate unit
                    $('#productunitdiv' + n).html(response.unitString);
                    //$("#addunit").empty();
                    $("#productunitdiv" + n + " option").clone().appendTo("#addunit");

                    $('#productparcode' + n).html(response.parcodeString);

                    $("#productunitdiv" + n + " option").clone().appendTo("#addunit");
                    //here all code that will happend with loading contants
                    $("#parcode" + $aw_if).focus();
                    $("#parcode" + $aw_if).select();

                    $('select').select2();
                },
                error: function () {
                    alert("لقد حدث خطأ أثناء إجراء العملية");
                }
            });
            //////////////////////////////////////////////////
        }
    });













    // fill the iltration filed with common iltration
    document.getElementById("hidden_itr").value = $aw_if;
    // incrementaion of row number and tab index
    $aw_if++
    $tabindexnumf++;
    //reload the dropdownlist and jquery files
    $('select').select2();
    return false;
});

function getproductbyParcode(e, value, n)
{
    //\s means "one space", and \s+ means "one or more spaces".
    value = value.replace(/\s+/g, '');//\s is the regex for "whitespace", and g is the "global" flag, meaning match ALL \s (whitespaces).
    var code = (e.keyCode ? e.keyCode : e.which);
    //to stop the submit of the form
    if (e.which == 13 && value != "")
    {
        // var storeid = document.getElementById("storeid").value;
        // if(storeid != "-1")
        // {
        var usedParcode = Number($('#usedParcode').val());
        if (usedParcode == 1) {
            value = value.replace("ه", "i");//this replacement is for parcode reader
            value = value.replace("÷", "i");//this replacement is for parcode reader
            value = value.replace("/", "i");//this replacement is for parcode reader
            value = value.replace("I", "i");//this replacement is for parcode reader
        } else {
            value = value;
        }
        //alert(value.charAt(0));
        $.ajax({
            url: 'sellbillAjaxController.php?do=getproductNamebyOnlyParcode&parcode=' + value + '&billnameid=3',
            success: function (data) {

                var response = $.parseJSON(data);
                //$("#product" + n).select2('val', ['' + response.id + ':' + response.text + ''], true);
                $("#product" + n).select2('data', {id: response.id, text: response.text});
                //----
                var productid = document.getElementById("product" + n).value;
                if (productid != "" && productid != "null" && productid != null && productid != "-1")
                {
                    var productParcode = $("#parcode" + n).val();
                    ///load unit , parcode, and price
                    $.ajax({
                        url: 'sellbillAjaxController.php?do=getunit&itrs=' + n + '&tabindex=' + $tabindexnumf + '&productid=' + productid + '&comingproserial=1&parcode=' + productParcode,
                        type: "get",
                        success: function (data) {
                            var response = $.parseJSON(data);
                            //populate unit
                            $('#productunitdiv' + n).html(response.unitString);
                            //  $("#addunit").empty();

                            $("#productunitdiv" + n + " option").clone().appendTo("#addunit");
                            $('select').select2();
                            $("#pronum" + n).focus();
                            $("#pronum" + n).select();

                            $('select').select2();
                        },
                        error: function () {
                            alert("لقد حدث خطأ أثناء إجراء العملية");
                        }
                    });
                    //////////////////////////////////////////////////

                }
            }
        });
        // }
    }
}
/*--------------------------------------------------------------------------------------*/
$("#addreturn").click(function () {
    $("#addunit").empty();
    var $raw_i = Number($('#returnhidden_itr').val()) + 1;






    $xx = '';
    $xx += '<tr class="aw_td">';
    $xx += '<td><span class="proDetails" data-pro="returnproduct' + $raw_i + '">' + $raw_i + '</span></td>';

    //# check to hide
    var hidden_parcode = '';
    $('#containerReturn .check_tr_parcode:first').each(function (e) {
        var ths = $(this);
        if (ths.hasClass('hidden')) {
            hidden_parcode = 'hidden';
            return false;
        }
    });

    $xx += '<td class="' + hidden_parcode + '">';

    $xx += '<div id="returnproductparcode' + $raw_i + '">'
            + '<input type="text" name="returnparcode' + $raw_i + '" id="returnparcode' + $raw_i + '" type="text" tabindex="' + $rtabindexnum + '"   class="form-control txt-nonraduisRet" placeholder="الباركود" onkeypress="getreturnproductbyParcode(event, this.value,' + $raw_i + ');" tabindex="301"/>'

            + ' <input name="returnparcodeType' + $raw_i + '" id="returnparcodeType' + $raw_i + '" type="hidden"/> '

            + ' <input name="returnproductserailid' + $raw_i + '" id="returnproductserailid' + $raw_i + '" type="hidden" /> '

            + '</div>'
            + '</td>';


    $xx += '<td>'
            + '<div id="returnproductdiv' + $raw_i + '">'
            + '  <input type="hidden" id="returnproduct' + $raw_i + '" name="returnproduct' + $raw_i + '"  class="select2returnproduct' + $raw_i + ' wdt100Ret"  data-placeholder="اختر منتج" tabindex="' + $rtabindexnum + '" />'

            + '</div>'
            + '</td>';


//# check to hide
    var hidden_unit = '';
    $('#containerReturn .check_tr_unit:first').each(function (e) {
        var ths = $(this);
        if (ths.hasClass('hidden')) {
            hidden_unit = 'hidden';
            return false;
        }
    });

    $xx += '<td  class="' + hidden_unit + '">';
    $xx += '<div id="returnproductunitdiv' + $raw_i + '">'
            + '<input type="hidden" name="retProNum' + $raw_i + '" id="retProNum' + $raw_i + '" value=""/>'
            + '<select id="returnproductunit' + $raw_i + '" name="returnproductunit' + $raw_i + '" class="select2 wdt100Ret" tabindex="' + $rtabindexnum + '">'
            + $("#addunit").html()
            + '</select>'
            + '</div>'
            + '</td> ';


    $xx += '<td class="">'
            + '<input type="text" name="returnpronum' + $raw_i + '" id="returnpronum' + $raw_i + '"  class="form-control txt-nonraduis getreurnprototal returnenteraction numberinput positivefloat" onKeyUp="returncheckquantity(' + $raw_i + ', event);" value="1" tabindex="' + $rtabindexnum + '"/>'
            + '</td>';





    $xx += '<td>'
            + '<button type="button" id="returnremove' + $raw_i + '" class="close flt-none returnremoveproduct" aria-hidden="true">&times;</button>'
            + '</td>'


            + '</tr>';


    $("#containerReturn").append($xx);
    $(".positiveNo").forcepositiveNum();
    $(".numberinput").forceNumeric();
    $(".positivefloat").forcepositivefloat();

    // varaible to contains the common itration
    var n = $raw_i;
    var $tabindexnumf = $rtabindexnum;

    //assign select2 properties
    $(".select2returnproduct" + n).select2({
        placeholder: "إسم المنتج",
        minimumInputLength: document.getElementById("searchvalue").value,
        // minimumInputLength: 3,
        multiple: false,
        quietMillis: 100,
        ajax: {
            url: "sellbillAjaxController.php?do=getProducts",
            dataType: 'json',
            data: function (term, page) {
                return {
                    term: term, //search term
                    page_limit: 10, // page size
                    storeid: 1, //document.getElementById("storeid").value,
//                            hiddenpricetype: document.getElementById("retpricetypepro" + n).value, //pricetype
//                            suppplier: document.getElementById("supplier").value,
//                            searchWithCatAndProductNameOnly: document.getElementById("searchWithCatAndProductNameOnly").value,
                };
            },
            results: function (data) {
                //alert("data: "+data);
                return {results: data};
            }
        },
        formatResult: function (data) {
            return data.text;
        },
        initSelection: function (element, callback) {
            var item = element.val().split(':');
            //var data = {id: item[0], text: item[1]};
            var data = {id: item[0], text: item[1], productquantity: item[2], price: item[3]};
            callback(data);
        }
    });



    //action in change of created dropdown list  to load the price
    $("#returnproduct" + n).change(function () {
        //here  will get the price for every product
        //the selected value in drop down list
        var theselectedvalue = $(this).val();

        if (theselectedvalue != "" && theselectedvalue != "null" && theselectedvalue != null && theselectedvalue != "-1")
        {
            //////////////////////////////////////////////////
            if (theselectedvalue.indexOf("hasSizeColor") == 0) {
                //when selecting sizecolor product make sure not to sent parcode
                //not stoping it in php to keep case of using sizecolor parcode working
                var productParcode = '';
            } else {
                var productParcode = $("#returnparcode" + n).val();
            }

            $.ajax({
                url: 'sellbillAjaxController.php?do=getreturnunit&itrs=' + n + '&tabindex=' + $tabindexnumf + '&productid=' + theselectedvalue + '&parcode=' + productParcode,
                type: "get",
                success: function (data) {
                    var response = $.parseJSON(data);
                    //populate unit
                    $('#returnproductunitdiv' + n).html(response.unitString);
                    $("#addunit").empty();
                    //$("#returnproductunitdiv1 option").clone().appendTo("#addunit");

                    $('#returnproductparcode' + n).html(response.parcodeString);

                    $("#returnpronum" + n).focus();
                    $("#returnpronum" + n).select();

                    // incrementaion of row number and tab index
                    $raw_i++
                    $rtabindexnum++;


                    $('select').select2();
                },
                error: function () {
                    alert("لقد حدث خطأ أثناء إجراء العملية");
                }
            });
            //////////////////////////////////////////////////

        }


    });










    // fill the iltration filed with common iltration
    document.getElementById("returnhidden_itr").value = $raw_i;

    // incrementaion of row number and tab index
    $raw_i++
    $rtabindexnum++;

    //reload the dropdownlist and jquery files
    $('select').select2();
    return false;
});
function getreturnproductbyParcode(e, value, n)
{
    var code = (e.keyCode ? e.keyCode : e.which);
    //to stop the submit of the form
    if (e.which == 13 && value != "")
    {
        var usedParcode = Number($('#usedParcode').val());
        if (usedParcode == 1) {
            value = value.replace("ه", "i");//this replacement is for parcode reader
            value = value.replace("÷", "i");//this replacement is for parcode reader
            value = value.replace("/", "i");//this replacement is for parcode reader
            value = value.replace("I", "i");//this replacement is for parcode reader
        } else {
            value = value;
        }
        //alert(value.charAt(0));
        $.ajax({
            url: 'sellbillAjaxController.php?do=getReturnproductNamebyOnlyParcode&parcode=' + value + '&billnameid=3',
            success: function (data)
            {
                var response = $.parseJSON(data);
                $("#returnproduct" + n).select2('data', {id: response.id, text: response.text});
                //---
                var productid = document.getElementById("returnproduct" + n).value;
                if (productid != "" && productid != "null" && productid != null && productid != "-1")
                {
                    $("#addunit").empty();
                    //////////////////////////////////////////////////
                    var productParcode = $("#returnparcode" + n).val();
                    $.ajax({
                        url: 'sellbillAjaxController.php?do=getreturnunit&itrs=' + n + '&tabindex=' + $rtabindexnum + '&productid=' + productid + '&comingproserial=1&parcode=' + productParcode,
                        type: "get",
                        success: function (data) {
                            var response = $.parseJSON(data);
                            //populate unit
                            $('#returnproductunitdiv' + n).html(response.unitString);
                            $("#addunit").empty();
                            //document.getElementById("returnproprice"+n).value=0;
                            document.getElementById("returnpronum" + n).value = 1;


                            $("#returnpronum" + n).focus();
                            $("#returnpronum" + n).select();

                            $('select').select2();
                        },
                        error: function () {
                            alert("لقد حدث خطأ أثناء إجراء العملية");
                        }
                    });
                    //////////////////////////////////////////////////

                }

            }
        });

        // }

    }

}

/*--------------------------------------------------------------------------------*/
$(document).on('click', '.removeproduct, .returnremoveproduct', function () {
    // delete by partents
    $(this).parent().parent().remove();
});
$(document).on('click', '#saveBill', function () {
    $('#billTemplateForm').submit();
});
function initiateRet(qq) {
    $("#returnproduct" + qq).select2({
        placeholder: "إسم المنتج",
        minimumInputLength: document.getElementById("searchvalue").value,
        // minimumInputLength: 3,
        multiple: false,
        quietMillis: 100,
        ajax: {
            url: "sellbillAjaxController.php?do=getProducts",
            dataType: 'json',
            data: function (term, page) {
                return {
                    term: term, //search term
                    page_limit: 10, // page size
                    storeid: 1, //document.getElementById("storeid").value,
//                            hiddenpricetype: document.getElementById("retpricetypepro" + n).value, //pricetype
//                            suppplier: document.getElementById("supplier").value,
//                            searchWithCatAndProductNameOnly: document.getElementById("searchWithCatAndProductNameOnly").value,
                };
            },
            results: function (data) {
                //alert("data: "+data);
                return {results: data};
            }
        },
        formatResult: function (data) {
            return data.text;
        },
        initSelection: function (element, callback) {
            var item = element.val().split(':');
            //var data = {id: item[0], text: item[1]};
            var data = {id: item[0], text: item[1], productquantity: item[2], price: item[3]};
            callback(data);
        }
    });
    $("#returnproduct" + qq).select2("data", {id: $('#reoldproduct' + qq).val(), text: $('#reoldname' + qq).val()});
    $("#returnproduct" + qq).change(function () {
        //here  will get the price for every product
        //the selected value in drop down list
        var theselectedvalue = $(this).val();

        if (theselectedvalue != "" && theselectedvalue != "null" && theselectedvalue != null && theselectedvalue != "-1")
        {
            n = qq;
            //////////////////////////////////////////////////
            if (theselectedvalue.indexOf("hasSizeColor") == 0) {
                //when selecting sizecolor product make sure not to sent parcode
                //not stoping it in php to keep case of using sizecolor parcode working
                var productParcode = '';
            } else {
                var productParcode = $("#returnparcode" + n).val();
            }

            $.ajax({
                url: 'sellbillAjaxController.php?do=getreturnunit&itrs=' + n + '&tabindex=' + $tabindexnumf + '&productid=' + theselectedvalue + '&parcode=' + productParcode,
                type: "get",
                success: function (data) {
                    var response = $.parseJSON(data);
                    //populate unit
                    $('#returnproductunitdiv' + n).html(response.unitString);
                    $("#addunit").empty();
                    //$("#returnproductunitdiv1 option").clone().appendTo("#addunit");

                    $('#returnproductparcode' + n).html(response.parcodeString);

                    $("#returnpronum" + n).focus();
                    $("#returnpronum" + n).select();

                    // incrementaion of row number and tab index
                    $raw_i++
                    $rtabindexnum++;


                    $('select').select2();
                },
                error: function () {
                    alert("لقد حدث خطأ أثناء إجراء العملية");
                }
            });
            //////////////////////////////////////////////////

        }


    });
}
function initiateSell(q) {
    $("#product" + q).select2({
        placeholder: "إسم المنتج",
        minimumInputLength: document.getElementById("searchvalue").value,
        //minimumInputLength: 3,
        multiple: false,
        quietMillis: 100,
        ajax: {
            url: "sellbillAjaxController.php?do=getProducts",
            dataType: 'json',
            data: function (term, page) {
                return {
                    term: term, //search term
                    page_limit: 10, // page size
                    storeid: 1, //document.getElementById("storeid").value,
                    // hiddenpricetype: document.getElementById("pricetypepro" + n).value, //pricetype
                    //    searchWithCatAndProductNameOnly: document.getElementById("searchWithCatAndProductNameOnly").value,
                };
            },
            results: function (data) {
                return {results: data};
            }
        },
        formatResult: function (data) {
            return data.text;
        },
        initSelection: function (element, callback) {
            var item = element.val().split(':');
            //  var data = {id: item[0], text: item[1]};
            var data = {id: item[0], text: item[1], productquantity: item[2], price: item[3]};
            callback(data);
        }
    })
    $("#product" + q).select2("data", {id: $('#oldproduct' + q).val(), text: $('#oldname' + q).val()});
    $("#product" + q).change(function () {

        //the selected value in drop down list
        var theselectedvalue = $(this).val();
        if (theselectedvalue != "" && theselectedvalue != "null" && theselectedvalue != null && theselectedvalue != "-1")
        {
            n = q;
            $("#addunit").empty();
            //////////////////////////////////////////////////
            if (theselectedvalue.indexOf("hasSizeColor") == 0) {
                //when selecting sizecolor product make sure not to sent parcode
                //not stoping it in php to keep case of using sizecolor parcode working
                var productParcode = '';
            } else {
                var productParcode = $("#parcode" + n).val();
            }

            var OtherParameters = '';

            ///load unit , parcode, and price
            $.ajax({
                url: 'sellbillAjaxController.php?do=getunit&itrs=' + n + '&tabindex=' + $tabindexnumf + '&productid=' + theselectedvalue + '&parcode=' + productParcode,
                type: "get",
                success: function (data) {
                    var response = $.parseJSON(data);
                    //populate unit
                    $('#productunitdiv' + n).html(response.unitString);
                    //$("#addunit").empty();
                    $("#productunitdiv" + n + " option").clone().appendTo("#addunit");

                    $('#productparcode' + n).html(response.parcodeString);

                    $("#productunitdiv" + n + " option").clone().appendTo("#addunit");
                    //here all code that will happend with loading contants
                    $("#parcode" + $aw_if).focus();
                    $("#parcode" + $aw_if).select();

                    $('select').select2();
                },
                error: function () {
                    alert("لقد حدث خطأ أثناء إجراء العملية");
                }
            });
            //////////////////////////////////////////////////
        }
    });
}
$(function () {

    if ($("#returnhidden_itr").length > 0)
    {
        var myolditrreturn = document.getElementById("returnhidden_itr").value;
        if (myolditrreturn > 0)
        {
            for (var qq = 1; qq <= myolditrreturn; qq++)
            {
                initiateRet(qq);
            }
        }


    }
    // alert($("#hidden_itr").length);

    if ($("#hidden_itr").length > 0)
    {
        //alert(111);

        var myolditr = document.getElementById("hidden_itr").value;
        if (myolditr > 0)
        {
            for (var q = 1; q <= myolditr; q++)
            {
                initiateSell(q);
            }
        }
    }



    $("#addpro").click();
    $("#addreturn").click();
});