jQuery.fn.forcepositiveNum = function () {

    return this.each(function () {
        $(this).keydown(function (e) {
            var key = e.which || e.keyCode;
            //alert(key);
            if (!e.shiftKey && !e.altKey && !e.ctrlKey &&
                    // numbers
                    key >= 48 && key <= 57 ||
                    // Numeric keypad
                    key >= 96 && key <= 105 ||
                    // comma, period and minus, . on keypad
                    //key == 190 || key == 188 || key == 109 || key == 110 ||
                    // Backspace and Tab and Enter
                    key == 8 || key == 9 || key == 13 ||
                    // Home and End
                    key == 35 || key == 36 ||
                    // left and right arrows
                    key == 37 || key == 39 ||
                    // Del and Ins
                    key == 46 || key == 45)
                return true;

            return false;
        });
    });
}

$(document).ready(function () {

    $(".positiveNo").forcepositiveNum();
    var formatResult;


    formatResult = function (data) {

        return  data.text;
    }


    $('input[name="clienttype"]').live('click', function () {

        var thisvalue = $(this).val();

        if (thisvalue == 0) {

            $("#newn_client_div").hide();
            $("#oldn_client_div").show();
        } else {
            $("#oldn_client_div").hide();
            $("#newn_client_div").show();
            // $("#newn_client_div").css('display','block');
        }

    })


    /*===================================first product load============================================*/
    if ($("#offer_proudctid1").length > 0)
    {
        $("#offer_proudctid1").select2({
            placeholder: "إسم المنتج",
            width: '200px',
            minimumInputLength: document.getElementById("searchvalue").value,
            //minimumInputLength: 3,
            multiple: false,
            quietMillis: 100,
            ajax: {
                url: "sellbillAjaxController.php?do=getProducts2",
                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);
            }
        });
    }

    $('.showdeletemsg').click(function () {
        var itemid = $(this).attr('data-id');
        var urlgo = $(this).attr('data-go');
        var hosturl = $('#hosturl').val();
        $('#small').modal('show');
        $('.deleteit').on('click', function () {
            window.location.href = urlgo + "?do=delete&id=" + itemid;
            //alert(hosturl + "/" + urlgo + "/delete/" + itemid);
            $('#small').modal('hide');
        });

    });
    $("#addpro_priceoffer").click(function () {

        $aw_i = Number(document.getElementById("offerhidden_itr").value) + 1;
        $tabindexnum = 8;
        addrow($aw_i, $tabindexnum, 1);
        // fill the iltration filed with common iltration
        document.getElementById("offerhidden_itr").value = $aw_i;

        // incrementaion of row number and tab index
        $aw_i++
        $tabindexnum++;

        //reload the dropdownlist and jquery files
        //$('select2').select2();
        return false;
    });


    $("#addwrite_priceoffer").click(function () {

        $aw_i = Number(document.getElementById("offerhidden_itr").value) + 1;
        $tabindexnum = 8;
        addrow($aw_i, $tabindexnum, 0);
        // fill the iltration filed with common iltration
        document.getElementById("offerhidden_itr").value = $aw_i;

        // incrementaion of row number and tab index
        $aw_i++
        $tabindexnum++;

        //reload the dropdownlist and jquery files
        //$('select2').select2();
        return false;
    });


    //add new row in bill
    /**************************/
    var addrow = function ($aw_i, $tabindexnum, $chk)
    {
        $addedRow = '<tr id="newProduct' + $aw_i + '">';

        if ($chk == 1)
        {
            $addedRow += '<td> <input type="text" name="parcode' + $aw_i + '" id="parcode' + $aw_i + '"  class="form-control txt-nonraduis" onkeypress="getproductbyParcode(event, this.value, ' + $aw_i + ');" size="3"  placeholder="الباركود" /> </td>';
            $addedRow += '<td><input type="text" name="offerproudctid' + $aw_i + '" id="offer_proudctid' + $aw_i + '" required  class="select2product wdt100 clas_offerproduct" data-itr=' + $aw_i + ' data-placeholder="اختر منتج" tabindex="301"/></td>';
        } else {
            $addedRow += '<td></td>';
            $addedRow += '<td> <input type="text" name="offerproudctname' + $aw_i + '" id="offerproudctname' + $aw_i + '" required data-itr=' + $aw_i + ' class="form-control" data-placeholder="  اسم المنتج" value="" /> </td>';

        }
        $addedRow += '<td> <input type="text" name="offerproprice' + $aw_i + '" id="offerproprice' + $aw_i + '" required data-itr=' + $aw_i + ' class="form-control txt-nonraduis positiveNo calcprice" value="0" /> </td>';

        $addedRow += '<td> <textarea name="prodescrp' + $aw_i + '" id="prodescrp' + $aw_i + '" class="form-control" ></textarea> </td>';

        $addedRow += '<td> <input type="text" name="offerpronumber' + $aw_i + '" id="offerpronumber' + $aw_i + '" required data-itr=' + $aw_i + ' class="form-control txt-nonraduis positiveNo calcprice" value="1" /> </td>';

        $addedRow += '<td class="aw_totalprice_offer"><input type="text" id="div_pr_offertotal' + $aw_i + '" required name="div_pr_offertotal' + $aw_i + '" data-itr=' + $aw_i + ' class="form-control txt-nonraduis positiveNo finalprice" value="0"></td>'

                + '<td>	<button type="button" id="offerprice_remove' + $aw_i + '" class="offerprice_remove close flt-none" aria-hidden="true"   onclick="removeproduct(' + $aw_i + ');" >&times;</button>'
                + '				</td>'
                + '</tr>';

        //add the new row with itration and with all propperties
        $("#priceoffer_tb").append($addedRow);
        $(".positiveNo").forcepositiveNum();
        $('select').select2();


        $("#offer_proudctid" + $aw_i).select2({
            placeholder: "إسم المنتج",
            width: '200px',
            minimumInputLength: document.getElementById("searchvalue").value,
            //minimumInputLength: 3,
            multiple: false,
            quietMillis: 100,
            ajax: {
                url: "sellbillAjaxController.php?do=getProducts2",
                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);
            }
        });

    }

    $(".offerprice_remove").live('click', function () {

        $(this).parent().parent().remove();
        total_sellprice();
    })
    /*===============get price of product=====================*/
    $('.clas_offerproduct').live('change', function () {
        var theselectedvalue = $(this).val();
        var itr = $(this).attr('data-itr');
        $.ajax({
            url: 'priceoffersControllerAjax.php?do=getproductsellprice&productid=' + theselectedvalue + '',
            type: "get",
            success: function (data) {
                var response = $.parseJSON(data);

                $("#offerproprice" + itr).val(response.productSellHalfPrice);
                $("#prodescrp" + itr).val(response.productDescription);
                $("#parcode" + itr).val(response.parcode);

                prouct_totalpricesell(itr);
                total_sellprice();

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


    })


    $(".calcprice").live('keyup', function () {

        var i = $(this).attr('data-itr');
        prouct_totalpricesell(i);
    })




    /*===========================client ===========================*/
    if ($("#offer_oldclient").length > 0)
    {
        $("#offer_oldclient").select2({
            placeholder: "إسم العميل",
            minimumInputLength: document.getElementById("searchvalue").value,
            //minimumInputLength: 3,
            multiple: false,
            quietMillis: 100,
            ajax: {
                url: "priceoffersControllerAjax.php?do=getclients",
                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);
            }
        });

        $("#offer_oldclient").select2("data", {id: $('#edit_hiddenclientId').val(), text: $('#edit_hiddenclientName').val()});
    }






    /*=============================edit product ===============================================*/

    if ($("#edit_offersellbill").length > 0) {

        var edit_itr = $("#offerhidden_itr").val();
        for (var qq = 1; qq <= edit_itr; qq++)
        {
            if ($("#offer_proudctid" + qq).length > 0) {
                $("#offer_proudctid" + qq).select2({
                    placeholder: "إسم المنتج",
                    width: '100%',
                    minimumInputLength: document.getElementById("searchvalue").value,
                    //minimumInputLength: 3,
                    multiple: false,
                    quietMillis: 100,
                    ajax: {
                        url: "sellbillAjaxController.php?do=getProducts2",
                        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);
                    }
                });

                $("#offer_proudctid" + qq).select2("data", {id: $('#edit_hiddenproductId' + qq).val(), text: $('#edit_hiddenproductName' + qq).val()});

            }


        }
    }






    $(".finalprice").live('keyup', function () {

        var i = $(this).attr('data-itr');

        var pro_finalprice = $(this).val();
        ///////price pro
        var pro_pricenumber = $('#offerpronumber' + i).val();

        if (Number(pro_finalprice) >= Number(pro_pricenumber)) {
            var pro_price = Math.round(Number(pro_finalprice) / Number(pro_pricenumber));
            $("#offerproprice" + i).val(pro_price);
            prouct_totalpricesell(i);
        }


    })
    /*=====================totalprice ===================================*/

    var prouct_totalpricesell = function (i) {

        var sellprice = Number($('#offerproprice' + i).val());
        var number = Number($('#offerpronumber' + i).val());

        //var totalprice = Math.round((sellprice * number));
        var totalprice = (sellprice * number);

        $("#div_pr_offertotal" + i).val(totalprice);

        total_sellprice();
    }







    var total_sellprice = function () {


        var sellprice = 0;

        $offerhidden_itr = document.getElementById("offerhidden_itr").value;

        //loop to sum the all prices
        for ($x = 1; $x <= $offerhidden_itr; $x++)
        {
            var numco = $x;
            var inputname = "#div_pr_offertotal" + numco;


            //to make sure that all input is created
            if ($("#div_pr_offertotal" + numco).length > 0)
            {
                sellprice += Number($("#div_pr_offertotal" + numco).val());

            }
        }
        $("#offer_sellbillpricenew").val(sellprice);
        $("#offer_sellbillprice").html(sellprice);
        $.post('priceoffersControllerAjax.php?do=writtenmoney', {price: sellprice}, function (data) {
            //alert(data);
            $('#offer_sellbillprice_written').html(data);

        });

    }

    /*================================save ===========================================*/
    $("#offerprice_form").validate();

    $('#offerprice_save').click(function () {

        if ($("#offerprice_form").validate().form())
        {
            $("#offerprice_form").attr("action", "priceoffersController.php?do=add");
            $("#offerprice_form").submit();
            $(this).attr('disabled', true);
        }
    })
    $("#print_offerprice").live('click', function () {

        if ($("#offerprice_form").validate().form())
        {
            $("#offerprice_form").attr("action", "priceoffersControllerAjax.php?do=saveandprint", "_new");
            $("#offerprice_form").submit();
            $(this).attr('disabled', true);
        }
    })


    $('#offerprice_editsave').click(function () {

        if ($("#offerprice_form").validate().form())
        {
            $("#offerprice_form").attr("action", "priceoffersController.php?do=update");
            $("#offerprice_form").submit();
            $(this).attr('disabled', true);
        }
    })
    $("#printedit_offerprice").live('click', function () {

        if ($("#offerprice_form").validate().form())
        {
            $("#offerprice_form").attr("action", "priceoffersControllerAjax.php?do=updateandprint");
            $("#offerprice_form").submit();
            $(this).attr('disabled', true);
        }
    })


    /*==========================ckeditor =====================================*/

    var path = $('#path').val();
    if ($("#ckeditor").length > 0) {
        CKEDITOR.replace('ckeditor',
                {
                    language: 'ar',
                    filebrowserBrowseUrl: path + '/assets/plugins/ckeditor/plugins/filemanager/browser/default/browser.html?Connector=' + path + '/assets/plugins/ckeditor/plugins/filemanager/connectors/php/connector.php',
                    filebrowserImageBrowseUrl: path + '/assets/plugins/ckeditor/plugins/filemanager/browser/default/browser.html?Type=' + path + '/assets/plugins/ckeditor/plugins/filemanager/connectors/php/connector.php',
                    filebrowserFlashBrowseUrl: path + '/assets/plugins/ckeditor/plugins/filemanager/browser/default/browser.html?Type=' + path + '/assets/plugins/ckeditor/plugins/filemanager/connectors/php/connector.php',
                    filebrowserUploadUrl: path + '/assets/plugins/ckeditor/plugins/filemanager/connectors/php/upload.php?Type=File',
                    filebrowserImageUploadUrl: path + '/assets/plugins/ckeditor/plugins/filemanager/connectors/php/upload.php?Type=Image',
                    filebrowserFlashUploadUrl: path + '/assets/plugins/ckeditor/plugins/filemanager/connectors/php/upload.php?Type=Flash'
                });
    }


})

function getproductbyParcode(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());
        var billnameid = $('#billnameid').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: 'priceoffersControllerAjax.php?do=loadProductByParcode&parcode=' + value,
            success: function (data) {

                var response = $.parseJSON(data);
                $("#offer_proudctid" + n).select2("data", {id: response.id, text: response.text});
                $("#offer_proudctid" + n).change();
                $("#offer_proudctid" + n).select2("data", {id: response.id, text: response.text});
            }
        });



















    }















}


