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;
    }

    $("#project-form").validate();
    $('#project_save_btn').click(function () {

        if ($("#project-form").validate().form())
        {
            $("#project-form").submit();
            $(this).attr('disabled', true);
        }
    })

    /*=====================valid on name ===============================*/

    $("#projectName").live('change', function () {

        var projectname = $(this).val();
        var proid = $(this).attr('data-id');
        var hosturl = $("#hosturl").val();

        var input = $(this);
        if (input.val() === "") {
            input.closest('.form-group').removeClass('has-error').removeClass('has-success');
            $('.fa-check, fa-warning', input.closest('.form-group')).remove();
            return;
        }


        $.post('projectControllerAjax.php?do=checkprojectname', {projectname: projectname, proid: proid}, function (res) {
            input.attr("readonly", false).
                    attr("disabled", false);

            // change popover font color based on the result
            if (res.status == 'OK') {
                $('#chkno').remove();
                input.after('<div id="chkno">' + res.message + '</div>');
                $("#project_save_btn").attr("readonly", false).attr("disabled", false);
            } else {
                $('#chkno').remove();
                input.after('<div id="chkno">' + res.message + '</div>');
                $("#project_save_btn").attr("readonly", true).attr("disabled", true);
            }
        }, 'json');


    });

          $('.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');
                });

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

            });
            
            
    /*=====================valid on image ===============================*/
    $('input[type="file"]').on('change', function () {

        var myfile = $(this).val();
        var ext = myfile.split('.').pop();
        if (ext == "pdf" || ext == "docx" || ext == "doc" || ext == "PDF" || ext == "DOCX" || ext == "DOC" || ext == "jpg" || ext == "jpeg" || ext == "png" || ext == "gif" || ext == "JPG" || ext == "JPEG" || ext == "PNG" || ext == "GIF") {

            var filesize = (this.files[0].size / 1024 / 1024);//now in MB
            if (filesize > 5)
            {
                $(this).val("");
                alert('عفوا حجم الملف : اكبر من 5MB ');
            }
            if (filesize == 0)
            {
                $(this).val("");
                alert('عفوا حجم الملف اصغر من اللازم');
            }
        } else {

            alert("لايمكنك تحميل هذا الملف");
            $(this).val('');
        }
    });


/*===========================expensetype ===========================*/
if ($("#expensetype").length > 0){
    $("#expensetype").select2({
        placeholder: "إسم  ",
        multiple: false,
        quietMillis: 100,
        ajax: {
            url: "expensesControllerajex.php?do=expensetypesave",
            type: "post",
            dataType: 'json',
            data: function (term, page) {
                var saveid = Number($('#saveid').val());
                if (!saveid) {
                    alert('يجب اختيار الخزنه اولا');
                    return false;
                }
                return {
                    searchTerm: term,
                    saveid: saveid,
                };
            },
            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 expensetypeid = $('#expensetypeid').val();
    if (expensetypeid) {
        $('#expensetype').select2('data', {id: $('#expensetypeid').val(), text: $('#expensetypetext').val()});
    }
}


if ($("#expensetypeuserid1").length > 0){
    $("#expensetypeuserid1").select2({
        placeholder: "إسم  ",
        multiple: false,
        quietMillis: 100,
        ajax: {
            url: "expensesControllerajex.php?do=expensetypesaveuser",
            type: "post",
            dataType: 'json',
            data: function (term, page) {
                return {
                    searchTerm: term,
                };
            },
            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 expensetypeuserid1 = $('#expensetypeuserid1').val();
    if (expensetypeuserid1) {
        $('#expensetypeuserid1').select2('data', {id: $('#expensetypeuserid1').val(), text: $('#expensetypeusertext1').val()});
    }
}


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

        $("#project_id").select2("data", {id: $('#edit_hiddenprojectId').val(), text: $('#edit_hiddenprojectName').val()});
    }



if ($("#projectId").length > 0)
    { 
        $("#projectId").select2({
            placeholder: "إسم  المشروع",
            minimumInputLength: document.getElementById("searchvalue").value,
            // minimumInputLength: 3,
            multiple: false,
            quietMillis: 100,
            ajax: {
                url: "projectControllerAjax.php?do=getprojectforreport",
                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);
            }
        });
    }

    /*================================productitr ====================================*/
    $("#addpro_projectoperation").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;
    });

    var addrow = function ($aw_i, $tabindexnum, $chk)
    {
        $addedRow = '<tr id="newProduct' + $aw_i + '">';

        $addedRow += '<td><input type="text" name="projectproudctid' + $aw_i + '" id="project_proudctid' + $aw_i + '" required  class="select2product wdt100 clas_offerproduct" data-itr=' + $aw_i + ' data-placeholder="اختر منتج" tabindex="301"/></td>';
        
        $addedRow += '<td> <input type="text" name="productnumber' + $aw_i + '" id="productnumber' + $aw_i + '"  required data-itr=' + $aw_i + ' class="form-control txt-nonraduis positiveNo calcprice pro_num" value="1" /><input type="hidden" id="proquqntity' + $aw_i + '"/> </td>';
        
        $addedRow += '<td><input type="text" readonly="" class="txt-nonraduis" name="probuyprice' + $aw_i + '"  id="probuyprice' + $aw_i + '"/></td>';
        $addedRow += '<td><input type="text" readonly="" class="txt-nonraduis" id="totalbuyprice' + $aw_i + '"/></td>';
        if (document.getElementById("expensestypes").value == 'yes') {
          $addedRow += '<td><input type="text" name="expensestypeid' + $aw_i + '"  class="wdt100" id="expensetypeuserid' + $aw_i + '" placeholder="اختر" /></td>';  
        }else if (document.getElementById("expensestypes").value == 'no') {
           $addedRow += '<td><input type="file" name="image' + $aw_i + '"  class="form-control wdt100"></td>';  
        }
        $addedRow += '<td> <button type="button" id="offerprice_remove' + $aw_i + '" class="projectoperation_remove close flt-none" aria-hidden="true" >&times;</button>'
                + '				</td>'
                + '</tr>';

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


        $("#project_proudctid" + $aw_i).select2({
            placeholder: "إسم المنتج",
            width: '100%',
            minimumInputLength: document.getElementById("searchvalue").value,
            //minimumInputLength: 3,
            multiple: false,
            quietMillis: 100,
            ajax: {
                url: "sellbillAjaxController.php?do=getProductsbyandstor",
                dataType: 'json',
                data: function (term, page) {
                    //alert("sellbillAjaxController.php?do=getProductsbyandstor&term="+term+"&page_limit=10&storeid="+document.getElementById("storeidfrom").value);
                    return {
                        term: term, //search term
                        page_limit: 10,
                        storeid: document.getElementById("storeid").value // 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);
            }
        });


            $("#expensetypeuserid"+ $aw_i).select2({
                placeholder: "إسم  ",
                multiple: false,
                quietMillis: 100,
                ajax: {
                    url: "expensesControllerajex.php?do=expensetypesaveuser",
                    type: "post",
                    dataType: 'json',
                    data: function (term, page) {
                        return {
                            searchTerm: term,
                        };
                    },
                    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);
                }
            });
           
        


    }


    /*===================================first product load============================================*/
    if ($("#project_proudctid1").length > 0)
    {
        $("#project_proudctid1").select2({
            placeholder: "إسم المنتج",
            width: '100%',
            minimumInputLength: document.getElementById("searchvalue").value,
            //minimumInputLength: 3,
            multiple: false,
            quietMillis: 100,
            ajax: {
                url: "sellbillAjaxController.php?do=getProductsbyandstor",
                dataType: 'json',
                data: function (term, page) {
                    //alert("sellbillAjaxController.php?do=getProductsbyandstor&term="+term+"&page_limit=10&storeid="+document.getElementById("storeidfrom").value);
                    return {
                        term: term, //search term
                        page_limit: 10,
                        storeid: document.getElementById("storeid").value // 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);
            }
        });
    }

    $("#projectoperation_form").validate();
    $(".clas_offerproduct").live('change', function () {

        //get iteration from input id
        var itrx = $(this).attr("data-itr"); //inputId.substring(7,inputId.length);

        //the selected value of drop downlsit
        var theselectedvalue = $(this).val();

        //alert($i);
        getProductQuantity(theselectedvalue, itrx);
        getproductbuyprice(itrx, theselectedvalue);





    });


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

        var edit_itr = $("#offerhidden_itr").val();
        for (var qq = 1; qq <= edit_itr; qq++)
        {
            if ($("#project_proudctid" + qq).length > 0) {
                $("#project_proudctid" + qq).select2({
                    placeholder: "إسم المنتج",
                    width: '100%',
                    minimumInputLength: document.getElementById("searchvalue").value,
                    //minimumInputLength: 3,
                    multiple: false,
                    quietMillis: 100,
                    ajax: {
                        url: "sellbillAjaxController.php?do=getProductsbyandstor",
                        dataType: 'json',
                        data: function (term, page) {
                            //alert("sellbillAjaxController.php?do=getProductsbyandstor&term="+term+"&page_limit=10&storeid="+document.getElementById("storeidfrom").value);
                            return {
                                term: term, //search term
                                page_limit: 10,
                                storeid: document.getElementById("storeid").value // 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);
                    }
                });

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

            }


            if ($("#expensetypeuserid"+ qq).length > 0){
                $("#expensetypeuserid"+ qq).select2({
                    placeholder: "إسم  ",
                    multiple: false,
                    quietMillis: 100,
                    ajax: {
                        url: "expensesControllerajex.php?do=expensetypesaveuser",
                        type: "post",
                        dataType: 'json',
                        data: function (term, page) {
                            return {
                                searchTerm: term,
                            };
                        },
                        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);
                    }
                });
                if ($('#expensetypeuseridv'+ qq).val()) {
                    $('#expensetypeuserid'+ qq).select2('data', {id: $('#expensetypeuseridv'+ qq).val(), text: $('#expensetypeusertextv'+ qq).val()});
                }
            }


            getProductQuantity($("#project_proudctid" + qq).val(), qq);
            getproductbuyprice(qq, $("#project_proudctid" + qq).val());
        }


    }

    $(".pro_num").live('keyup', function () {
        var i = $(this).attr('data-itr');
        checkdata(i);
        prouct_buyprice(i);
    })



    /*==============================get product quantity in store================================*/
    function getProductQuantity(value, itr)
    {

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


        $.ajax({
            url: 'storemovementAjaxController.php?do=getquantity&productid=' + value + '&storeidfrom=' + storeid,
            success: function (x) {

                // document.getElementById("proquqntity").style.display="block";
                $("#proquqntity" + itr).val(Number(x));
                checkdata(itr);
                //anotherProduct(value,itr);

            }
        });

    }

    /*============================get buy price =======================================*/
    function getproductbuyprice(itr, productid)
    {
        $.ajax({
            url: 'priceoffersControllerAjax.php?do=getproductsellprice&productid=' + productid + '',
            type: "get",
            success: function (data) {
                var response = $.parseJSON(data);
                var productnumber = $("#productnumber" + itr).val();
                var totalbuyprice = Number(response.lastbuyprice_withDiscount) * Number(productnumber);
                $("#probuyprice" + itr).val(response.lastbuyprice_withDiscount);
                $("#totalbuyprice" + itr).val(totalbuyprice);
                total_sellprice();
            },
            error: function () {
                alert("لقد حدث خطأ أثناء إجراء العملية");
            }
        });
    }

    $(".projectoperation_remove").live('click', function () {
        $(this).parent().parent().remove();
        total_sellprice();

    })




    /*=====================check if < or > product in store ==================================*/
    function checkdata(i)
    {

        var currentquantity = Number($("#proquqntity" + i).val());
        var storenegative = Number($("#storenegative").val());
        var productamount = Number($("#productnumber" + i).val());

        if (storenegative == 0)
        {
            if (productamount > currentquantity)
            {

                if (currentquantity > 0)
                {

                    $("#productnumber" + i).val(currentquantity);
                }
                else
                {
                    $("#productnumber" + i).val(0);
                }
            }

        }
        else
        {
            if (productamount > currentquantity)
            {
                alert("هذه الكمية اكبر من الموجودة بالمخزن الموجود بالمخزن " + currentquantity);
            }

        }


    }

    /*====================================total price ==========================================*/
    function prouct_buyprice(i) {

        var probuyprice = Number($('#probuyprice' + i).val());
        var number = Number($('#productnumber' + i).val());

        var totalprice = Math.round((probuyprice * number));

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

        total_sellprice();
    }


    function total_sellprice() {


        var buyprice = 0;
        var pronumber = 0;
        var offerhidden_itr = document.getElementById("offerhidden_itr").value;

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

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


            }
        }
        $("#finaltotalprice").val(buyprice);
        $("#div_totalnumber").html(pronumber);
        $("#totalpronumber").val(pronumber);


    }

    /*---------------------------------------------------------------*/
    //fatma expenseexchange
    if ($("#expenseexchange").val() == "1") {

        $(".expensefrom").live('change', function () {
            var val = $(this).val();
            if (val == 0)
            {
                $("#saveDiv").show();
                $("#bankDiv").hide();
                $("#ohadDiv").hide();
                $("#bankaccountDiv").hide();
            }
            else if (val == 1)
            {
                $("#saveDiv").hide();
                $("#bankDiv").show();
                $("#ohadDiv").hide();
                $("#bankaccountDiv").show();
            }
            else if (val == 2)
            {
                $("#saveDiv").hide();
                $("#bankDiv").hide();
                $("#ohadDiv").show();
                $("#bankaccountDiv").hide();
            }
        });
        $("#bankid").live('change', function () {
            var id = $(this).val();
            $.post("projectControllerAjax.php?do=getbankaccount", {id: id}, function (data) {
                $("#bankaccountid").html(data);
            });
        });
        $("#project_id").live('change', function () {
            var data = $(this).select2('data')
            $("#costcenterid").val(data.text);
        });
    }

});
