// JavaScript Document
var formatResult;
$(document).ready(function (e) {
    
    
    
jQuery.fn.forcepositivefloat = function () {

    return this.each(function () {
        $(this).keydown(function (e) {
            var presedval = e.key;
            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 ||
                    // plus and minus
                    key == 109 || key == 107 || key == 173 || key == 43

                    //dot or point  .  on keyboard  for one time
                            (key == 110 && $(this).val().indexOf(".") < 0) ||
                            (key == 190 && $(this).val().indexOf(".") < 0 && presedval == ".") ||
                            // Del and Ins
                            key == 46 || key == 45)
                return true;

            return false;
        });
    });
}

   $(".realNo").forcepositivefloat();

    //# m7md
    $('#pay_clientdept').on('click', function () {
        var client_id = $('#client').val();
        if (client_id == '') {
            alert('يجب اختيار عميل اولا .');
        } else {
            $.post('clientControllerAjax.php?do=load_client', {client_id: client_id}, function (client_arr) {

                var client_data = JSON.parse(client_arr);
                console.log(client_data);
                $('#sp_client_name').html(client_data.clientname);
                $('#sp_client_dept').html(client_data.clientdebt);
                var total_dept = Number($('#waitValue').val()) + Number($('#lbl_dept').html())
                $('#total_dept').html(Number(total_dept));
            });

            $.post('billsajax.php?do=clientBills', {client_id: client_id}, function (client_bills) {
                $('#table_container').html(client_bills);
                $('#client_id').val(client_id);

            });

            $('#clientdept-modal').modal('show');
        }
    });


    $('body').on('click', '.update_confirm', function () {

        var client_id = $('#client').val();
        var discount_dept = Number($('#pay_client_dept').val());
        var dept_val = Number($('#sp_client_dept').html());
        if (discount_dept > dept_val) {
            alert('يجب ان تكون قيمة السداد اقل من المديونية');
        } else {

            var updated_dept = dept_val - discount_dept;
            //# update client .
            $.post('clientControllerAjax.php?do=update_client', {client_id: client_id, updated_dept: updated_dept}, function (data) {
                if (data == 1) {
                    $('#lbl_dept').html(updated_dept);
                    $('#clientdept-modal').modal('hide');
                    $('#pay_client_dept').val('0');
                    rechange_total_dept();
                } else {
                    alert('هناك خطأ .');
                }

            });
        }
    });

    $('#kashf_serial').on('focusout', function () {

        var customerId = $("#client").val();
        var kashf_serial = $(this).val();

        //# load kasfh details by customer and kashf serial .
        loadkasfdetails(customerId, kashf_serial)
    });

    function loadkasfdetails(customerId, kashf_serial) {


        $.post('billsajax.php?do=loadkasfdetailsByKashfSerial', {customerId: customerId, kashf_serial: kashf_serial}, function (rslt_2) {

            var obj_2 = JSON.parse(rslt_2);

            $('#usedkashf').val('0');

            if (obj_2.lastDoctorKashfCount == 1) {
                $('#kashfError').hide();


                if (obj_2.usedkashf == '1') {

                    $('#usedkashf').val('1');
                    $("#kashfError2").show();
                } else {
                    $("#kashfError2").hide();
                }
                $("#kashfError3").hide();
                $('#kashfError').hide();
                $('#kashfExist').val(1);
                fillExternalKashfFixed(obj_2.lastDoctorKashf);
                $('#externalKashfFixed').show();


                if (obj_2.kashfInBill == 1)
                {
                    // add kashf to bill
                    $('#kashfValue').val(obj_2.kashfValue);
                    $('#kashfValueP').html(obj_2.kashfValue);
                }
                else
                {

                    $('#kashfValue').val(obj_2.kashfValue);
                    $('#kashfValueP').html(obj_2.kashfValue);

                    $('#kashDiscValue').val(obj_2.kashfValue);
                    $('#kashDiscValueP').html(obj_2.kashfValue);
                }
                calcTotal();

            } else {
                $('#kashfError3').show();
            }

        });


    }
    if ($('#buyoptic').length < 1) {//not buy
        $("#client").select2({
            placeholder: "اختر عميل ",
            minimumInputLength: 0,
            //  minimumInputLength: 3,
            multiple: false,
            quietMillis: 100,
            ajax: {
                url: "billsajax.php?do=getclients",
                dataType: 'json',
                data: function (term, page) {
                    //  alert(term);
                    return {
                        term: term, //search term
                        page_limit: 10, // page size
                    };
                },
                results: function (data) {

                    // alert(term);
                    return {results: data};
                }
            },
            formatResult: formatResult,
            initSelection: function (element, callback) {
                var item = element.val().split(':');
                var data = {id: item[0], text: item[1]};
                callback(data);
            }
        }).on('change', function () {

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

            $.post('clientControllerAjax.php?do=load_client', {client_id: ths_client_id}, function (client_arr) {

                var client_data = JSON.parse(client_arr);
                $('#lbl_dept').html(client_data.clientdebt);
                rechange_total_dept();
            });

        });
    }

    //# to make client name نقدى
    //# as default for client selection .
    function rechange_total_dept() {
        var total_dept = Number($('#waitValue').val()) + Number($('#lbl_dept').html());
        $('#total_dept').html(Number(total_dept));
    }
    $(document).ready(function () {
        var nakdyOnly = $('#nakdyOnly').val();
        if (nakdyOnly == 1) {
            $("#client").select2("data", {id: "1", text: "نقدى"});

            $.post('clientControllerAjax.php?do=load_client', {client_id: 1}, function (client_arr) {

                var client_data = JSON.parse(client_arr);
                $('#lbl_dept').html(client_data.clientdebt);
                rechange_total_dept();
            });
        }

        if ($('#oldclientid').length > 0)
        {
            $("#client").select2("data", {id: $('#oldclientid').val(), text: $('#oldclientname').val()});
        }
    });


    var billType = 0;//sell
    if ($('#buyoptic').length > 0 && $('#buyoptic').val() == "1")
    {
        billType = 1;//buy
    }




//###########################################################################################################################################################
//######################################### Bills controller   ##############################################################################################
//###########################################################################################################################################################
    var searchvalue = $('#searchvalue').val();
    formatResult = function (data) {
        return  data.text + '<span  style="text-align: left;  float: left;  width: 30%;">'
                + data.price + '</span ><span  style="float: left;  margin-left: 5px;"  > ' + data.productquantity + '';
    };

    if ($('#edit').val() == 1 && $('#controllName').val() == 'bills')
    {
        function initialize_product(i) {
            $('#product' + i).select2({
                placeholder: "إسم المنتج",
                //minimumInputLength: 0,
                minimumInputLength: searchvalue,
                multiple: false,
                quietMillis: 100,
                ajax: {
                    url: "billsajax.php?do=getProducts",
                    dataType: 'json',
                    data: function (term, page) {
                        return {
                            term: term, //search term
                            page_limit: 10, // page size
                            storeid: document.getElementById("storeid").value,
                            pricetype: document.getElementById("pricetype").value,
                            serviceid: document.getElementById("service" + i).value
                        };
                    },
                    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 valueId = $('#productId' + i).val();
            var valueName = $('#billProductText' + i).val();

            $('#product' + i).select2('data', {id: valueId, text: valueName});
        }
        var itr = $('#hidden_itr').val();
        for (var i = 1; i <= itr; i++)
        {
            initialize_product(i);
        }
    }


    function isInteger(f) {
        return typeof (f) === "number" && Math.round(f) == f;
    }
    function isFloat(f)
    {
        return typeof (f) === "number" && !isInteger(f);
    }
    $(".opticService").live('change', function () {
        var itr = $(this).attr('data-itr');
        if ($("#productCatId0_" + itr).length > 0)
        {
            var service = $(this).val();

            $('#manyParents_' + itr).html("");
            $("#productCatId0_" + itr).empty();
            $.post('billsajax.php?do=getservicecats', {service: service}, function (data) {
                $("#productCatId0_" + itr).append(data);
                var newState = new Option('اختر تصنيف', '-1', true, true);
                // Append it to the select
                $("#productCatId0_" + itr).prepend(newState).trigger('change.select2');
                //$("#productCatId0_" + itr).val($("#productCatId0_" + itr + " option:first").val()).change();
            });

        }
    });
    //######################################### load kashf details on client change  #########################################
    $("#client").live('change', function (e) {

        // alert(111);
        val = $(this).val();
        if (val == '-2') {
            $('#myclientModal1').modal('show');

        }
        else {
            var customerId = $(this).val();
            //if (1 == 0)
            if ($('#buyoptic').length > 0 && $('#buyoptic').val() == "1")
            {
                calcTotal();
            }
            else {
                var kashfType = $('input[name=kashftype]:checked').val();
                if (kashfType == 1)
                {
                    $('#externalKashf').show();
                    $('#externalKashfFixed').hide();
                    $('#kashfExist').val(1);
                    $('#kashfError').hide();

                    $('#kashfValue').val(0);
                    $('#kashfValueP').html(0);

                    $('#kashDiscValue').val(0);
                    $('#kashDiscValueP').html(0);
                    $('#kashf_serial').css('display', 'none');
                    $('#kashf_serial').val('');
                    $('#kashfError2').hide();

                    calcTotal();
                }
                else
                {
                    $('#externalKashf').hide();
                    $('#externalKashfFixed').hide();

                    $.post('billsajax.php?do=loadkasfdetails', {customerId: customerId}, function (rslt) {
                        var obj = JSON.parse(rslt);

                        if (obj.lastDoctorKashfCount == 1 && kashfType == 0)
                        {
                            var kashf_serial = $('#kashf_serial').val();

                            if (kashf_serial != '') {

                                //# load kasfh details by customer and kashf serial .
                                loadkasfdetails(customerId, kashf_serial)

                            }

                        }
                        else if (obj.lastDoctorKashfCount == 0 && kashfType == 2)

                        {
                            kashf_error();
                        }
                        else if (obj.lastDoctorKashfCount == 0 && kashfType == 0)
                        {
                            $('#kashftype1').attr('checked', 'checked');
                            kashf_error();
                            $('#kashfError2').hide();


                        }
                        else if (obj.lastDoctorKashfCount == 1 && kashfType == 2)
                        {
                            $('#kashftype2').attr('checked', 'checked');
                            $('#kashfError').hide();
                            $('#kashf_serial').css('display', 'inline-block');
                            $('#kashf_serial').val('');
                            $('#kashfError2').hide();

                        }
                        calcTotal();
                    });
                }
            }
        }
    });
//######################################### load data in products select   #########################################


    $('.savemodel1').on('click', function (e) {
        //alert($('#clientInfomain').validate().form())
        if ($('#clientInfomain').validate().form())
        {

            var newclientName = $('#newclientName').val();
            var clientcode = $('#clientcode').val();
            var clientareaid = $('#clientareaid').val();
            var newclientdebt = $('#newclientdebt').val();
            var clientaddress = $('#clientaddress').val();
            var clientphone = $('#clientphone').val();
            var clientmobile = $('#clientmobile').val();
            var clientdetails = $('#clientdetails').val();
            var emp = '';

            if (newclientName == '') {
                e.preventDefault();
                if ($('#nameError').html() == "")
                {
                    $('#nameError').append("<p style='color: red;'>ادخل اسم العميل </p>");
                }
            }
            else if (clientareaid == 0) {
                e.preventDefault();
                $('#nameError').html("");
                if ($('#areaError').html() == "")
                {
                    $('#areaError').append("<p style='color: red;'>  اختر المنطقة </p>");
                }

            }
            else if (newclientdebt == '') {
                e.preventDefault();
                $('#nameError').html("");
                $('#areaError').html("");
                if ($('#areaError').html() == "")
                {
                    $('#nameError2').append("<p style='color: red;'>ادخل رقم المديونية </p>");
                }

            } else {
                $.post('clientControllerAjax.php?do=addclient3', {newclientName: newclientName, clientaddress: clientaddress, clientphone: clientphone, clientmobile: clientmobile, newclientdebt: newclientdebt, clientdetails: clientdetails, clientareaid: clientareaid, clientcode: clientcode, control: 1}, function (data) {

                    /// document.getElementById('').style.display = 'none';
                    $('#myclientModal1').modal('hide');
                    if (data == 2) {
                        alert('هذا العميل تمت اضافتة من قبل ');
                        location.reload();
                    } else if (data == 3) {
                        alert('رقم الكود تمت اضافتة من قبل ');
                        location.reload();
                    }
                    else {
                        data = data.split(',');
                        $("#client").val(data[0]).change();
                        $("#client").select2("data", {id: data[0], text: data[1]});

                        //$("#clientDiv").html(data);


                        $(':input', '#clientInfo').val('');
                        $('#clientareaid').select2();
                    }
                });
            }

        }


    });



    function closeClientForm()
    {
        document.getElementById('myModal1').style.display = 'none';

    }




    $(".checknumintfolat").live('blur', function (e) {

        var x = isInteger(Number($(this).val()));
        var y = isFloat(Number($(this).val()));

        var value = Number($(this).val());


        if (x)
        {
            if (value > 0)
            {

                $finalvalue = '+' + value + '.00';
                $(this).val($finalvalue);
            }
            else
            {

                $finalvalue = value + '.00';

                $(this).val($finalvalue);
            }


        }
        if (y)
        {
            // alert('yy');
            if (value > 0)
            {

                $newvalue = value.toFixed(2);
                //alert($newvalue);
                //decimalAdjust('round', value, -4);
                // alert('+newvalue'+$newvalue);
                $finalvalue = '+' + $newvalue;
                $(this).val($finalvalue);

            }
            else
            {

                // alert('-newvalue'+$newvalue);
                $newvalue = value.toFixed(2);//decimalAdjust('round', value, -4);
                //    alert($newvalue);
                $finalvalue = $newvalue;
                $(this).val($finalvalue);
            }

        }


    });

    function kashf_error() {

        $('#kashfError').show();
        $('#kashfExist').val(0);

        $('#kashfValue').val(0);
        $('#kashfValueP').html(0);

        $('#kashDiscValue').val(0);
        $('#kashDiscValueP').html(0);
        $('#kashf_serial').css('display', 'none');

    }

    $('#insuranceInst').live('click', function (e) {
        $("#myModal1").modal("show");
    });

    $("#insuranceCompanies").live('change', function (e) {
        var insuranceCompanyId = $(this).val();
        if (insuranceCompanyId == -1)
        {
            $('#insuranceInst').hide();
        }
        else
        {
            $.post('billsajax.php?do=getinsDetail', {insuranceCompanyId: insuranceCompanyId}, function (rslt) {
                var obj = JSON.parse(rslt);
                $('#companyName').html(obj.name);
                $('#instructionP').html(obj.instruction);
                $('#insuranceInst').show();
            });
        }

    });
    if ($('#edit').val() != 1)
    {
        var isProductRequest = $('#isProductRequest').val();
        if (isProductRequest == 1)
        {
            var itr = $('#hidden_itr').val();
            var n = 1;
            for (var i = 1; i <= itr; i++)
            {

                $('#product' + i).select2({
                    placeholder: "إسم المنتج",
                    //minimumInputLength: 0,
                    minimumInputLength: searchvalue,
                    multiple: false,
                    quietMillis: 100,
                    ajax: {
                        url: "billsajax.php?do=getProducts",
                        dataType: 'json',
                        data: function (term, page) {
                            return {
                                term: term, //search term
                                page_limit: 10, // page size
                                storeid: document.getElementById("storeid").value,
                                pricetype: document.getElementById("pricetype").value
                            };
                        },
                        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 valueId = $('#productId' + i).val();
                var valueName = $('#billProductText' + i).val();

                $('#product' + i).select2('data', {id: valueId, text: valueName});


                if (valueId == -1)
                {
                    $('#pronum' + i).val(1);
                    $('#proprice' + i).val(0);
                    $('#prototal' + i).html(0);
                    $('#totalProductPrice' + i).val(0);
                    calcTotal();
                }
                else
                {
                    var priceType = $('#pricetype').val();


                    $.post('billsajax.php?do=getproductdetails', {productId: valueId, priceType: priceType, billType: billType}, function (rslt) {
                        $('#proprice' + n).val(Number(rslt));
                        $('#prototal' + n).html((Number(rslt)) * (Number($('#pronum' + n).val())));
                        $('#totalProductPrice' + n).val(Number(rslt));
                        calcTotal();
                        n = n + 1;
                    });
                }



            }
        }
        else
        {
            $("#product1").select2({
                placeholder: "إسم المنتج",
                //minimumInputLength: 0,
                minimumInputLength: searchvalue,
                multiple: false,
                quietMillis: 100,
                ajax: {
                    url: "billsajax.php?do=getProducts",
                    dataType: 'json',
                    data: function (term, page) {
                        return {
                            term: term, //search term
                            page_limit: 10, // page size
                            storeid: document.getElementById("storeid").value,
                            pricetype: document.getElementById("pricetype").value,
                            serviceid: document.getElementById("service1").value
                        };
                    },
                    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);
                }
            });
        }
    }
//###################################################################################################################
    $(".kashftype").change(function (e) {
        var ths = $(this);

        var kashftype = ths.val();
        if (kashftype == 1)
        {
            $('#externalKashfFixed').hide();
            $('#externalKashf').show();

            $('#kashfExist').val(1);
            $('#kashfError').hide();

            $('#kashfValue').val(0);
            $('#kashfValueP').html(0);

            $('#kashDiscValue').val(0);
            $('#kashDiscValueP').html(0);
            $('#kashf_serial').css('display', 'none');
            $('#kashf_serial').val('');
            $('#kashfError2').hide();

            calcTotal();
        }
        else
        {

            $('#externalKashf').hide();
            $('#externalKashfFixed').hide();

            var customerId = $('#client').val();
            if (kashftype == -1)
            {
                $('#kashf_serial').css('display', 'none');
            } else {
                $.post('billsajax.php?do=loadkasfdetails', {customerId: customerId}, function (rslt) {
                    var obj = JSON.parse(rslt);

                    //# incase da5ely only and bill was inserted.
                    if (obj.lastDoctorKashfCount == 1 && kashftype == 0)
                    {
                        var kashf_serial = $('#kashf_serial').val();
                        $('#kashf_serial').css('display', 'inline-block');
                        $('#kashf_serial').val('');
                        if (kashf_serial != '') {

                            //# load kasfh details by customer and kashf serial .
                            loadkasfdetails(customerId, kashf_serial)

                        }

                    }
                    else if (obj.lastDoctorKashfCount == 0 && kashftype == 2)

                    {
                        kashf_error();
                    }
                    else if (obj.lastDoctorKashfCount == 0 && kashftype == 0)
                    {
                        $('#kashftype1').attr('checked', 'checked');
                        kashf_error();
                    }
                    else if (obj.lastDoctorKashfCount == 1 && kashftype == 2)
                    {
                        $('#kashftype2').attr('checked', 'checked');
                        $('#kashfError').hide();
                        $('#kashf_serial').css('display', 'inline-block');
                        $('#kashf_serial').val('');
                        $('#kashfValue').val(0);
                        $('#kashfValueP').html('0');
                        $('#kashfError2').hide();

                    }
                    calcTotal();
                });
            }
        }
    });

    function fillExternalKashfFixed(kashf)
    {
        kashf.ldsphere = getNumberSigned(kashf.ldsphere);
        kashf.ldcylinder = getNumberSigned(kashf.ldcylinder);
        kashf.ldprism = getNumberSigned(kashf.ldprism);
        kashf.ldva = getNumberSigned(kashf.ldva);
        kashf.lnsphere = getNumberSigned(kashf.lnsphere);
        kashf.lncylinder = getNumberSigned(kashf.lncylinder);
        kashf.lnprism = getNumberSigned(kashf.lnprism);
        kashf.lnva = getNumberSigned(kashf.lnva);

        $('#D_Lsphere').val(kashf.ldsphere);
        $('#D_Lcylinder').val(kashf.ldcylinder);
        $('#D_Laxis').val(kashf.ldaxis);//no signs required
        $('#D_Lprism').val(kashf.ldprism);
        $('#D_Lva').val(kashf.ldva);

        $('#N_Lsphere').val(kashf.lnsphere);
        $('#N_Lcylinder').val(kashf.lncylinder);
        $('#N_Laxis').val(kashf.lnaxis);//no signs required
        $('#N_Lprism').val(kashf.lnprism);
        $('#N_Lva').val(kashf.lnva);

        kashf.rdsphere = getNumberSigned(kashf.rdsphere);
        kashf.rdcylinder = getNumberSigned(kashf.rdcylinder);
        kashf.rdprism = getNumberSigned(kashf.rdprism);
        kashf.rdva = getNumberSigned(kashf.rdva);
        kashf.rnsphere = getNumberSigned(kashf.rnsphere);
        kashf.rncylinder = getNumberSigned(kashf.rncylinder);
        kashf.rnprism = getNumberSigned(kashf.rnprism);
        kashf.rnva = getNumberSigned(kashf.rnva);
        kashf.ladd = getNumberSigned(kashf.ladd);

        kashf.lbiofocal = getNumberSigned(kashf.lbiofocal);
        kashf.radd = getNumberSigned(kashf.radd);
        kashf.rbiofocal = getNumberSigned(kashf.rbiofocal);

        $('#D_Rsphere').val(kashf.rdsphere);
        $('#D_Rcylinder').val(kashf.rdcylinder);
        $('#D_Raxis').val(kashf.rdaxis);//no signs required
        $('#D_Rprism').val(kashf.rdprism);
        $('#D_Rva').val(kashf.rdva);

        $('#N_Rsphere').val(kashf.rnsphere);
        $('#N_Rcylinder').val(kashf.rncylinder);
        $('#N_Raxis').val(kashf.rnaxis);//no signs required
        $('#N_Rprism').val(kashf.rnprism);
        $('#N_Rva').val(kashf.rnva);

        $('#ladd').val(kashf.ladd);
        $('#lbiofocal').val(kashf.lbiofocal);
        $('#pd').val(kashf.pd);//no signs required
        $('#bvd').val(kashf.bvd);//no signs required
        $('#radd').val(kashf.radd);
        $('#rbiofocal').val(kashf.rbiofocal);
        $('#notes').val(kashf.notes);
    }

    function getNumberSigned(num) {
        //negative is handled by it self give negative sign
        if (Number(num) > 0)
        {
            num = "+" + num;
        }
        return num;
    }

    $('#checkAll').live('click', function (e) {
        if (this.checked) {
// Iterate each checkbox
            $('.choosenItem').each(function () {
                this.checked = true;
            });
        }
        else {
// Iterate each checkbox
            $(".choosenItem").each(function () {
                this.checked = false;
            });
        }
    });
//######################################### draw  new product row  #########################################

    $("#addNewPro").click(function (e) {
        var itr = $('#hidden_itr').val();
        var newItr = Number(itr) + 1;
        $('#hidden_itr').val(newItr);
          var bill_type = $('#payType').val();
               
        if ($('#addview2').length > 0 && $('#addview2').val() == "1")
        {
            $.post('billsajax.php?do=addnewproduct2', {newItr: newItr ,bill_type:bill_type}, function (rslt) {
                $('#productsTable').append(rslt);
              
               
                if (bill_type == 'buybill') {
                    $('.change_discount').parent().addClass('hide');
                }
            });
        }
        else
        {
            $.post('billsajax.php?do=addnewproduct', {newItr: newItr}, function (rslt) {
                
                
                $('#productsTable').append(rslt);
                $('#product' + newItr).select2({
                    placeholder: "إسم المنتج",
                    //minimumInputLength: 0,
                    minimumInputLength: searchvalue,
                    multiple: false,
                    quietMillis: 100,
                    ajax: {
                        url: "billsajax.php?do=getProducts",
                        dataType: 'json',
                        data: function (term, page) {
                            return {
                                term: term, //search term
                                page_limit: 10, // page size
                                storeid: document.getElementById("storeid").value,
                                pricetype: document.getElementById("pricetype").value,
                                serviceid: document.getElementById("service" + newItr).value
                            };
                        },
                        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);
                    }
                });
            });
        }
    });
//######################################### load product price   #########################################

    $(".productchange").live('change', function (e) {

        var productId = $(this).val();
        var itr = $(this).attr('data-itr');
        var isoptic = $('#product' + itr + ' option:selected').attr('data-optic');
        $('#proIsOptic_' + itr).val(isoptic);
        var isColorSize = $(this).hasClass('colorsize');
        var newRow = $(this).attr('data-newR');
        if (productId == -1)
        {
            $('#pronum' + itr).val(1);
            $('#proprice' + itr).val(0);
            $('#prototal' + itr).html(0);
            $('#totalProductPrice' + itr).val(0);
            calcTotal();
        }
        else
        {
            if ($('#addview2').val() == "1") {
                if (isoptic == 2)
                {
                    if (isColorSize == false)
                    {
                        var id = $('#product' + itr).val();
                        $('#product' + itr).removeClass('productchange');
                        $('#product' + itr).attr('name', 'preproduct' + itr);
                        $('#product' + itr).attr('id', 'preproduct' + itr);
                        $('#s2id_product' + itr).removeClass('productchange');
                        $('#s2id_product' + itr).attr('name', 's2id_preproduct' + itr);
                        $('#s2id_product' + itr).attr('id', 's2id_preproduct' + itr);
                        $('#preproduct' + itr).change();
                    }
                }
                else
                {
                    if ($('#preproduct' + itr).length > 0) {
                        $('#sizeColorDiv_' + itr).remove();

                        $('#preproduct' + itr).attr('name', 'product' + itr);
                        $('#preproduct' + itr).attr('id', 'product' + itr);
                        $('#s2id_preproduct' + itr).attr('name', 'product' + itr);
                        $('#s2id_preproduct' + itr).attr('id', 'product' + itr);
                        $('#s2id_product' + itr).addClass('productchange');
                        $('#s2id_product' + itr).removeClass('productchange');
                    }
                }
            }

            if ($('#addview2').val() == "1") {
                if (isoptic == 2 && isColorSize == false)
                {
                    $('#pronum' + itr).val(1);
                    $('#proprice' + itr).val(0);
                    $('#prototal' + itr).html(0);
                    $('#totalProductPrice' + itr).val(0);
                    calcTotal();
                }
                else
                {
                    var priceType = $('#pricetype').val();
                    $.post('billsajax.php?do=getproductdetails', {productId: productId, priceType: priceType, billType: billType}, function (rslt) {
                        $('#pronum' + itr).val(1);
                        $('#proprice' + itr).val(Number(rslt));
                        $('#prototal' + itr).html(Number(rslt));
                        $('#totalProductPrice' + itr).val(Number(rslt));
                        calcTotal();
                        if ($('#edit').val() != 1)
                        {
                            if (newRow == 0)
                            {
                                $('#product' + itr).attr('data-newR', 1);
                                $("#addNewPro").click();
                            }

                        }


                    });
                }
            }
            else
            {
                var priceType = $('#pricetype').val();
                $.post('billsajax.php?do=getproductdetails', {productId: productId, priceType: priceType, billType: billType}, function (rslt) {
                    $('#pronum' + itr).val(1);
                    $('#proprice' + itr).val(Number(rslt));
                    $('#prototal' + itr).html(Number(rslt));
                    $('#totalProductPrice' + itr).val(Number(rslt));
                    calcTotal();
                    if ($('#edit').val() != 1)
                    {
                        if (newRow == 0)
                        {
                            $('#product' + itr).attr('data-newR', 1);
                            $("#addNewPro").click();
                        }

                    }


                });
            }
        }
        rechange_total_dept();


    });
    $("[id^=preproduct]").live('change', function (e) {
        var itr = $(this).attr('data-itr');
        var id = $('#preproduct' + itr).val();
        $('#sizeColorDiv_' + itr).remove();
        $.post('salesreportajax.php?do=getsizecolor', {id: id, itr: itr}, function (data) {
            $('#productIdDiv_' + itr).append(data);
            var internal_kashf = 0;
            if ($('#kashftype2').is(':checked'))
            {
                internal_kashf = 1;
            }
            calcTotal(internal_kashf);
        });
    });
//######################################### calc product price after change of price or number  #########################################

    $(".changePrice").live('keyup', function (e) {
        var itr = $(this).attr('data-itr');
        var productNumber = $('#pronum' + itr).val();
        var productPrice = $('#proprice' + itr).val();
        var discount = Number($('#discount' + itr).val());

        var discount_pres_direct = Number($('#discount_pres_direct').val());
        var percentageDiscount = Number($('#percentageDiscount').val()); //# from program settings .

        var final_val, result_discount, dis_res;
        //# discount_pres_direct = 1 [ precentage ] , discount_pres_direct = 0 [ direct ] .
        if (discount_pres_direct == '1') {
            if (discount <= percentageDiscount && discount > 0) {

                dis_res = discount / 100;
            } else {
                if (discount == 0) {

                    $('#discount' + itr).val('');
                    dis_res = 0 / 100;
                } else {
                    $('#discount' + itr).val(percentageDiscount);
                    dis_res = percentageDiscount / 100;
                }

            }
            result_discount = productPrice * dis_res;

            final_val = (Number(productNumber) * Number(productPrice)) - result_discount;
        } else {
            final_val = (Number(productNumber) * Number(productPrice)) - discount;

        }


        $('#prototal' + itr).html(Number(final_val));
        $('#totalProductPrice' + itr).val(Number(final_val));
        calcTotal();
    });
//######################################### remove  product row  #########################################

    $(".removeproduct").live('click', function (e) {
        if ($('#del_pro_ids').length > 0)
        {
            var itr = $(this).attr('id').replace("remove", "");
            var id = $('#billProductId' + itr).val();
            var val = $('#del_pro_ids').val();
            var new_val = id + "," + val;
            $('#del_pro_ids').val(new_val);
        }
        $(this).parent().parent().remove();
        calcTotal();

    });
//######################################### remove  product row  #########################################

    $(".saveBill").live('click', function (e) {

        // alert($('#billForm').validate().form());
        if ($('#billForm').validate().form())
        {

            var btnNew = $('#saveBillNew');
            var btnOnly = $('#saveBillOnly');
            var directSave = $('#saveBillNewDirect');
            btnNew.attr('disabled', true);
            btnOnly.attr('disabled', true);
            directSave.attr('disabled', true);

            var newBill = $(this).attr('data-new');
            var direct = $(this).attr('data-direct');
            var totalBalane = calcTotal();
            var totalBayed = Number($('#cashValue').val())
                    + Number($('#waitValue').val())
                    + Number($('#insuranceValue').val())
                    + Number($('#cardValue').val());


            var billNo = $('#billno').val();
            var createdBillNo = $('#createdBillNo').val();
            var edit = $('#edit').val();
            var billId = $('#billId').val();

            var kashfExist = $('#kashfExist').val();
            var insuranceError = 0;
            var cardError = 0;

            if ($('#insuranceChecked').is(':checked') && $('#insuranceCompanies').val() == -1)
            {
                $('#insuranceError').show();
                insuranceError = 1;
            }
            if ($('#insuranceChecked').is(':checked') && $('#attatch').val() == "" && $('#oldattatch').length == 0)
            {
                $('#attatchError').show();
                insuranceError = 1;
            }
            if ($('#cardChecked').is(':checked') && $('#paymentNetworks').val() == -1)
            {
                $('#cardError').show();
                if (billType == 1)
                {
                    $('#accountError').show();
                }
                cardError = 1;
            }

            // if ($('#client').val() != -1 && billNo != '' && kashfExist == 1 && insuranceError != 1 && cardError != 1)
            if ($('#client').val() != -1 && billNo != '' && insuranceError != 1 && cardError != 1)
            {

                if (createdBillNo == billNo && edit != 1)
                {
                    if (totalBalane == totalBayed)
                    {
                        //print_Custom('mycustomheader');
                        $('#new').val(newBill);
                        $('#directSave').val(direct);
                        //########## submit form
                        if ($('#client').val() == 1 && Number($('#waitValue').val()) > 0)
                        {
                            alert('عميل نقدى يجب ان يكون بلا أجل');
                            btnNew.attr('disabled', false);
                            btnOnly.attr('disabled', false);
                            directSave.attr('disabled', false);
                        } else {
                            $('#billForm').submit();
                        }
                    }
                    else
                    {
                        alert('صافى قيمة الفاتورة  لا يساوى قيمة المدفوع بطرق الدفع المختلفة ');
                        btnNew.attr('disabled', false);
                        btnOnly.attr('disabled', false);
                        directSave.attr('disabled', false);
                    }
                }
                else
                {

                    $.post('billsajax.php?do=checkbillno', {billNo: billNo, edit: edit, billId: billId, billType: billType}, function (rslt) {

                        if (Number(rslt) == 1)
                        {

                            if (totalBalane == totalBayed)
                            {
                                //print_Custom('mycustomheader');
                                $('#new').val(newBill);
                                $('#directSave').val(direct);
                                //########## submit form
                                if ($('#client').val() == 1 && Number($('#waitValue').val()) > 0)
                                {
                                    alert('عميل نقدى يجب ان يكون بلا أجل');
                                    btnNew.attr('disabled', false);
                                    btnOnly.attr('disabled', false);
                                    directSave.attr('disabled', false);
                                } else {
                                    $('#billForm').submit();
                                }
                            }
                            else
                            {
                                alert('صافى قيمة الفاتورة  لا يساوى قيمة المدفوع بطرق الدفع المختلفة ');
                                btnNew.attr('disabled', false);
                                btnOnly.attr('disabled', false);
                                directSave.attr('disabled', false);
                            }
                        }
                        else
                        {
                            $('#billError').html('رقم الفاتورة موجود من قبل لفاتورة أخرى ');
                            $('#billError').show();
                            btnNew.attr('disabled', false);
                            btnOnly.attr('disabled', false);
                            directSave.attr('disabled', false);
                        }

                    });
                }

            }
            else
            {
                if ($('#client').val() == -1)
                {
                    $('#nameError').show();
                }
                else if (billNo == '')
                {
                    $('#billError').html('ادخل رقم الفاتورة');
                    $('#billError').show();
                }
                else if (kashfExist != 1)
                {
                    $('#kashfError').show();
                    $('#kashfExist').val(0);
                }

                btnNew.attr('disabled', false);
                btnOnly.attr('disabled', false);
                directSave.attr('disabled', false);

            }

        }


    });
//######################################### show or hide payment methods details  #########################################

    $(".changePayment").live('change', function (e) {
        var id = $(this).val();
        var id1 = $(this).attr('data-id1');
        var id2 = $(this).attr('data-id2');
        if ($(this).is(':checked'))
        {
            $('#' + id1).select2('enable');
            $('#' + id2).removeAttr('disabled');
            if (billType == 1 && id == "card") {
                $('#accountid').select2('enable');
            }
            if (id == 'insurance')
            {
                $('#clientPercent').removeAttr('disabled');
                $('#clientMax').removeAttr('disabled');
                $('#clientCarry').removeAttr('disabled');
                $('#insAccept').removeAttr('disabled');
                $('#approvalNo').removeAttr('disabled');
                $('#attatch').removeAttr('disabled');
            }
        }
        else
        {
            $('#' + id1).select2("enable", false);
            $('#' + id2).attr('disabled', true);
            if (billType == 1 && id == "card") {
                $('#accountid').select2("enable", false);
            }
            $('#' + id1).select2("val", -1);
            $('#' + id2).val(0);
            if (id == 'insurance')
            {
                $('#clientPercent').attr('disabled', true);
                $('#clientMax').attr('disabled', true);
                $('#clientCarry').attr('disabled', true);
                $('#insAccept').attr('disabled', true);
                $('#approvalNo').attr('disabled', true);
                $('#attatch').attr('disabled', true);

                $('#clientPercent').val(0);
                $('#clientMax').val(0);
                $('#clientCarry').val(0);
                $('#insAccept').val(0);
                $('#approvalNo').val('');
                $('#attatch').val('');

                $('#insuranceInst').hide();
            }
        }

        calcTotal();
    });
//######################################### search in bills  #########################################
//tab1
    $(".searchBills").live('click', function (e) {
        // alert(11);
        var clientId = $('#client1').val();
        //alert('clientId'+clientId);
        var billNo = $('#billNo').val();
        var fromDate = $('#fromDate').val();
        var toDate = $('#toDate').val();

        var url = 'billsajax.php?do=billssearch';
        if (billType == 1)
        {
            url = 'billsajax.php?do=billssearchbuy';
        }
        $.post(url, {clientId: clientId, billNo: billNo, fromDate: fromDate, toDate: toDate, insuranceOnly: 0, approved: 0}, function (rslt) {
            // alert(rslt);
            $('#searchResult').html('');
            $('#searchResult').html(rslt);
        });
    });
    //tab2
    $(".searchBills2").live('click', function (e) {
        var clientId = $('#client2').val();
        var billNo = $('#billNo2').val();
        var fromDate = $('#fromDate2').val();
        var toDate = $('#toDate2').val();
        $.post('billsajax.php?do=billssearch', {clientId: clientId, billNo: billNo, fromDate: fromDate, toDate: toDate, insuranceOnly: 1, approved: 0}, function (rslt) {
            // alert(rslt);
            $('#searchResult2').html('');
            $('#searchResult2').html(rslt);
        });
    });
    //tab3
    $(".searchBills3").live('click', function (e) {
        var clientId = $('#client3').val();
        var billNo = $('#billNo3').val();
        var fromDate = $('#fromDate3').val();
        var toDate = $('#toDate3').val();
        $.post('billsajax.php?do=billssearch', {clientId: clientId, billNo: billNo, fromDate: fromDate, toDate: toDate, insuranceOnly: 1, approved: 1}, function (rslt) {
            // alert(rslt);
            $('#searchResult3').html('');
            $('#searchResult3').html(rslt);
        });
    });
    //tab4
    $(".searchBills4").live('click', function (e) {
        var clientId = $('#client4').val();
        var billNo = $('#billNo4').val();
        var fromDate = $('#fromDate4').val();
        var toDate = $('#toDate4').val();
        $.post('billsajax.php?do=billssearch', {clientId: clientId, billNo: billNo, fromDate: fromDate, toDate: toDate, insuranceOnly: 1, approved: 2}, function (rslt) {
            // alert(rslt);
            $('#searchResult4').html('');
            $('#searchResult4').html(rslt);
        });
    });
//######################################### change discount  #########################################

    $(".changeDiscount").live('keyup', function (e) {

        var netBillValue = $('#netBillValue').val();

        if ($(this).attr('id') == 'discType')
        {
            $('#discValue').val(0);
            var discValue = $('#discValue').val();
            var discType = $('#discType').val();
        }
        else
        {
            var discValue = $('#discValue').val();
            var discType = $('#discType').val();
            $.post('billsajax.php?do=checkdiscount', {discValue: discValue, discType: discType, netBillValue: netBillValue}, function (rslt) {
                if (rslt == 9)
                {
                    alert('قيمة الخصم تتجاوز الحدود المسموح بها ');
                    $('#discValue').val(0);
                }
            });
        }

        //###########################################################################################################################


        if (discType == 1)
        {
            var netValue = netBillValue - discValue;
        }
        else if (discType == 2)
        {
            discValue = netBillValue * discValue / 100;
            var netValue = netBillValue - discValue;
        }


        $('#netValue').val(netValue);
        $('#netValueP').html(netValue);
        $('.calcBillRest').keyup();
    });
//######################################### calc total price   #########################################

    function calcTotal(internal_kashf)
    {
        var itr = $('#hidden_itr').val();
        var total = 0;
        var productTotalPrice = 0;
        var productNumber = 0;
        var productPrice = 0;
        var productDiscount = 0;

        var discount_pres_direct = 0;
        if ($('#discount_pres_direct').length > 0)
        {
            discount_pres_direct = Number($('#discount_pres_direct').val());
        }
        var percentageDiscount = Number($('#percentageDiscount').val()); //# from program settings .


        for (var i = 1; i <= itr; i++)
        {
            if ($('#pronum' + i).length > 0 && $('#proprice' + i).length > 0)
            {
                productNumber = $('#pronum' + i).val();
                productPrice = $('#proprice' + i).val();
                var bill_type = $('#bill_type').val();
                if (bill_type == 'buybill') {

                    productDiscount = 0;
                } else {
                    if ($('#discount' + i).length > 0)
                    {
                        productDiscount = $('#discount' + i).val();
                    }
                    else
                    {
                        productDiscount = 0;
                    }

                }

                var final_val, result_discount, dis_res;
                //# discount_pres_direct = 1 [ precentage ] , discount_pres_direct = 0 [ direct ] .
                if (discount_pres_direct == '1') {
                    if (productDiscount <= percentageDiscount && productDiscount > 0) {

                        dis_res = productDiscount / 100;
                    } else {
                        if (productDiscount == 0) {

                            dis_res = 0 / 100;
                        } else {
                            dis_res = percentageDiscount / 100;
                        }

                    }
                    result_discount = productPrice * dis_res;

                    productTotalPrice = Number(productNumber) * Number(productPrice);
                    total = total + productTotalPrice - result_discount;

                } else {

                    productTotalPrice = Number(productNumber) * Number(productPrice);
                    total = total + productTotalPrice - productDiscount;
                }
            }
        }

        $('#buyBillTotal').html(Number(total));
        $('#totalBuyBill').val(Number(total));
        $('#totalBillPrice').val(Number(total));




        var kashfValue = $('#kashfValue').val();

        if (Number(total) > kashfValue)
        {
            $('#kashDiscValue').val(kashfValue);
            $('#kashDiscValueP').html(kashfValue);
        }
        else
        {
            $('#kashDiscValue').val(0);
            $('#kashDiscValueP').html(0);
        }


        var kashDiscValue = $('#kashDiscValue').val();
        var kashf_serial = Number($('#kashf_serial').val());

        var usedkashf = $('#usedkashf').val();
        if (usedkashf == '1') {

            $('#kashDiscValueP').html(0);
        } else {
            $('#kashDiscValueP').html(kashfValue);
        }
        if (kashf_serial != '' && kashf_serial != 0 && usedkashf == '0') {

            //# الدفع داخلى برقم الكشف و الكشف لم يستخدم من قبل
            var netBillValue = Number(total) - Number(kashfValue);
        }
        else if (kashf_serial != '' && kashf_serial != 0 && usedkashf == '1') {

            //# الدفع داخلى برقم الكشف و الكشف  استخدم من قبل
            var netBillValue = Number(total);
        }
        else {
            //# الدفع مع الفاتورة
            var netBillValue = Number(total) + Number(kashfValue) - Number(kashDiscValue);

        }

        $('#netBillValue').val(netBillValue);
        $('#netBillValueP').html(netBillValue);

        var discValue = $('#discValue').val();
        var discType = $('#discType').val();
        $.post('billsajax.php?do=checkdiscount', {discValue: discValue, discType: discType, netBillValue: netBillValue}, function (rslt) {
            if (rslt == 9)
            {
                if (internal_kashf != 1)
                {
                    alert('قيمة الخصم تتجاوز الحدود المسموح بها ');
                }
                $('#discValue').val(0);
            }
        });


        if (discType == 1)
        {
            var netValue = Number(netBillValue) - discValue;
        }
        else if (discType == 2)
        {
            discValue = Number(netBillValue) * discValue / 100;
            var netValue = Number(netBillValue) - discValue;
        }


        $('#netValue').val(netValue);
        $('#netValueP').html(netValue);
        $('.calcBillRest').keyup();
        return Number(netValue);
    }


//######################################### pricetype#########################################

    $("#pricetype").live('change', function (e) {
        var priceType = $('#pricetype').val();
        var itr = $('#hidden_itr').val();
        var x = 1;

        for (var i = 1; i <= itr; i++)
        {

            var productId = $('#product' + x).val();
            if (productId != -1)
            {
                $.post('billsajax.php?do=getproductdetails', {productId: productId, priceType: priceType, billType: billType}, function (rslt) {
//                pronum = $('#pronum' + x).val();
                    $('#proprice' + x).val(Number(rslt));
                    $('#prototal' + x).html(Number(rslt) * Number($('#pronum' + x).val()));
                    $('#totalProductPrice' + x).val(Number(rslt) * Number($('#pronum' + x).val()));
                    calcTotal();
                    x++;
                });
            }


        }
    });
//######################################### accept && reject bill ######################################
    ////---reject-------------------------------------
    $('.confirmRejectBill').live('click', function () {
        var id = $(this).attr('data-id');
        $('#rejectBillId').val(id);
        $('#rejectBillModal').modal('show');
    });
    $('.rejectBill').live('click', function () {
        var me = $(this);
        me.attr('disabled', 'disabled');
        var id = $('#rejectBillId').val();
        $.post("billsajax.php?do=rejectbill", {id: id}, function (data) {
            if (data == 1)
            {
                $('#bill' + id).html("تم الرفض");
                me.removeAttr('disabled');
                $('#rejectBillModal').modal('hide');
                $(".searchBills").click();

                //to show new rejected
                $('#client4').val('').trigger('change.select2');
                $('#billNo4').val('').trigger('change.select2');
                $('#fromDate4').val('');
                $('#toDate4').val('');
                $('.searchBills4').click();
            }
            else
            {
                alert('عفوا لقد حدث خطأ');
            }
        });
    });
    //---accept-------------------------------------
    $('.confirmAcceptBill').live('click', function () {
        var id = $(this).attr('data-id');
        $('#acceptedBillId').val(id);
        $('#acceptBillModal').modal('show');
    });
    $('.acceptBill').live('click', function () {
        $(this).attr('disabled', 'disabled');
        var acceptanceNo = $('#acceptanceNo').val();
        if (acceptanceNo == "")
        {
            $('#acceptanceNoError').html('ادخل رقم الموافقة');
            $('#acceptanceNoError').show();
            $(this).removeAttr('disabled');
        }
        else
        {
            $('#acceptanceNoError').hide();
            $('#acceptBillForm').submit();
        }
    });
    $("#acceptBillForm").on('submit', (function (e) {
        e.preventDefault();
        //return false;
        $.ajax({
            url: "billsajax.php?do=acceptbill", // Url to which the request is send
            type: "POST", // Type of request to be send, called as method
            data: new FormData(this), // Data sent to server, a set of key/value pairs representing form fields and values
            contentType: false, // The content type used when sending data to the server. Default is: "application/x-www-form-urlencoded"
            cache: false, // To unable request pages to be cached
            processData: false, // To send DOMDocument or non processed data file it is set to false (i.e. data should not be in the form of string)
            success: function (data)  		// A function to be called if request succeeds
            {
                //alert(data);
                data = data.split(',');
                if (data[0] == 1)
                {
                    var id = $('#acceptedBillId').val();
                    $('#bill' + id).html("تمت الموافقة");
                    $('#acceptanceNo').val("");
                    $('#acceptedFile').val("");
                    $('.acceptBill').removeAttr('disabled');
                    $('#acceptBillModal').modal('hide');
                    if (data[1] == 1)
                    {
                        alert("الكمية بالمخزن لا تكفى");
                    }
                    $(".searchBills").click();

                    //to show new rejected
                    $('#client3').val('').trigger('change.select2');
                    $('#billNo3').val('').trigger('change.select2');
                    $('#fromDate3').val('');
                    $('#toDate3').val('');
                    $('.searchBills3').click();
                }
                else
                {
                    alert('عفوا لقد حدث خطأ');
                }
            }
        });
    }));

//######################################### cal Client Carry   #########################################

    $(".calClientCarry").live('keyup', function (e) {
        var clientPercent = $('#clientPercent').val();
        var clientMax = $('#clientMax').val();
        var netValue = $('#netValue').val();
        var percentValue = netValue * (clientPercent / 100);
        if (percentValue > clientMax)
        {
            $('#clientCarry').val(clientMax);
        }
        else
        {
            $('#clientCarry').val(percentValue);
        }

        $('.calcInsValue').keyup();
    });
    //######################################### calc Ins Value   #########################################

    $(".calcInsValue").live('keyup', function (e) {
        var insAccept = $('#insAccept').val();
        var clientCarry = $('#clientCarry').val();
        var insuranceValue = insAccept - clientCarry;
        if (insuranceValue < 0)
        {
            insuranceValue = 0;
        }

        $('#insuranceValue').val(insuranceValue);
        $('.calcBillRest').keyup();
    });
//######################################### calc Bill Rest   #########################################

    $(".calcBillRest").live('keyup', function (e) {

        var billRest = $('#netValue').val();
        //console.log(billRest);
        if ($('#insuranceChecked').is(':checked'))
        {
            var insuranceValue = $('#insuranceValue').val();
            billRest = billRest - insuranceValue;
        }

        if ($('#cardChecked').is(':checked'))
        {
            var cardValue = $('#cardValue').val();
            billRest = billRest - cardValue;
        }

        if ($('#cashChecked').is(':checked'))
        {
            var cashValue = $('#cashValue').val();
            billRest = billRest - cashValue;
        }




        $('#waitValue').val(billRest);
        $('#waitValueP').html(billRest);
        rechange_total_dept();

    });

//######################################### change discount value M7md  #########################################

    $(".change_discount").live('keyup', function (e) {
        var discount_pres_direct = Number($('#discount_pres_direct').val());
        var percentageDiscount = Number($('#percentageDiscount').val()); //# from program settings .

        var itr = $(this).attr('data-itr');
        var discount_val = Number($(this).val());
        var proprice = Number($('#proprice' + itr).val());
        var pronum = Number($('#pronum' + itr).val());

        var final_val, result_discount, dis_res;
        //# discount_pres_direct = 1 [ precentage ] , discount_pres_direct = 0 [ direct ] .
        if (discount_pres_direct == '1') {
            if (discount_val <= percentageDiscount && discount_val > 0) {

                dis_res = discount_val / 100;
            } else {
                if (discount_val == 0) {

                    $('#discount' + itr).val('');
                    dis_res = 0 / 100;
                } else {
                    $('#discount' + itr).val(percentageDiscount);
                    dis_res = percentageDiscount / 100;
                }

            }
            result_discount = proprice * dis_res;
            final_val = (proprice * pronum) - result_discount;
        } else {
            final_val = (proprice * pronum) - discount_val;
        }
        $('#prototal' + itr).html(final_val);
        $('#totalProductPrice' + itr).val(final_val);

        calcTotal()

    });


//######################################### change product quantity   #########################################

    $(".proNumChange").live('keyup', function (e) {

        var itr = $(this).attr('data-itr');
        var quantity = $(this).val();
        var productId = $('#product' + itr).val();
        var storeId = $('#storeid').val();
        //var edit = $('#edit').val();
        var quantityOld = $('#pronumOld' + itr).val();

        if ($('#buyoptic').length < 1)//dont check for quantity if it is buy optic
        {
            $.post('billsajax.php?do=checkstorequantity', {productId: productId, quantity: quantity, storeId: storeId, quantityOld: quantityOld}, function (rslt) {
                if (Number(rslt) == 99)
                {
                    alert('الكمية المطلوبة تتعدى الكمية الموجودة بالمخزن ');
                }
            });
        }
    });

//###########################################################################################################################################################
//######################################### insurance company  controller   ##############################################################################################
//###########################################################################################################################################################

    $("#companyName").live('change', function (e) {
        var edit = $('#edit').val();
        var companyName = $('#companyName').val();
        var companyId = $('#companyId').val();
        $.post('billsajax.php?do=checkcompanyname', {companyName: companyName, edit: edit, companyId: companyId}, function (rslt) {
            if (Number(rslt) == 1)
            {
                $('#nameError').hide();
            }
            else
            {
                $('#nameError').show();
            }

        });
    });
    $("#saveInsCompany").live('click', function (e) {

        var edit = $('#edit').val();
        var companyName = $('#companyName').val();
        var companyId = $('#companyId').val();
        $.post('billsajax.php?do=checkcompanyname', {companyName: companyName, edit: edit, companyId: companyId}, function (rslt) {
            var nameValid = Number(rslt);
            switch (nameValid)
            {
                case 1 :           // valid company name
                    $('#nameError').hide();
                    submitCompanyForm();
                    break;
                default :          // invalid company name
                    $('#nameError').show();
                    break;
            }
        });
        function submitCompanyForm()
        {
            var x = $('#insuranceCompanyForm').validate();
            var validated_p = x.form();
            if (validated_p)
            {
                $('#insuranceCompanyForm').submit();
            }

        }



    });

    //###########################################################################################################################################################
//######################################### payment network  controller   ##############################################################################################
//###########################################################################################################################################################

    $("#networkName").live('change', function (e) {
        var edit = $('#edit').val();
        var networkName = $('#networkName').val();
        var networkId = $('#networkId').val();
        $.post('billsajax.php?do=checknetworkname', {colName: 'name', networkName: networkName, edit: edit, networkId: networkId}, function (rslt) {
            if (Number(rslt) == 1)
            {
                $('#networkNameError').hide();
            }
            else
            {
                $('#networkNameError').show();
            }

        });
    });


    $("#networkNameEn").live('change', function (e) {
        var edit = $('#edit').val();
        var networkNameEn = $('#networkNameEn').val();
        var networkId = $('#networkId').val();
        $.post('billsajax.php?do=checknetworkname', {colName: 'nameen', networkName: networkNameEn, edit: edit, networkId: networkId}, function (rslt) {
            if (Number(rslt) == 1)
            {
                $('#networkNameEnError').hide();
            }
            else
            {
                $('#networkNameEnError').show();
            }

        });
    });


    $("#saveNetwork").live('click', function (e) {

        var edit = $('#edit').val();
        var networkId = $('#networkId').val();
        var networkName = $('#networkName').val();
        var networkNameEn = $('#networkNameEn').val();


        $.post('billsajax.php?do=checknetworkname', {colName: 'name', networkName: networkName, edit: edit, networkId: networkId}, function (rslt) {
            var nameValid = Number(rslt);
            switch (nameValid)
            {
                case 1 :           // valid network name
                    $('#networkNameError').hide();
                    $.post('billsajax.php?do=checknetworkname', {colName: 'nameen', networkName: networkNameEn, edit: edit, networkId: networkId}, function (rslt1) {
                        var nameEnValid = Number(rslt1);
                        switch (nameEnValid)
                        {
                            case 1 :           // valid network english name
                                $('#networkNameEnError').hide();
                                submitNetworkForm();
                                break;
                            default :          // invalid network english name
                                $('#networkNameEnError').show();
                                break;
                        }

                    });
                    break;
                default :          // invalid network name
                    $('#networkNameError').show();
                    break;
            }

        });
    });



    function submitNetworkForm()
    {
        var x = $('#networkForm').validate();
        var validated_p = x.form();
        if (validated_p)
        {
            $('#networkForm').submit();
        }

    }


    /*--fatma--*/
    $('.productCat').live('change', function () {
        var id = $(this).val();
        var level = Number($(this).attr('data-level'));
        level = level + 1;
        var itr = $(this).attr('data-itr');
        $('#level_' + itr).val(level);

        $('#pronum' + itr).val(1);
        $('#proprice' + itr).val(0);
        $('#prototal' + itr).html(0);
        $('#totalProductPrice' + itr).val(0);

        var internal_kashf = 0;
        if ($('#kashftype2').is(':checked'))
        {
            internal_kashf = 1;
        }
        calcTotal(internal_kashf);

        $.post('salesreportajax.php?do=getsubcatbills', {id: id, level: level, itr: itr}, function (data) {
            $('.productCat' + itr).each(function () {
                var thisLevel = Number($(this).attr('data-level'));
                if (thisLevel >= level) {
                    $(this).parent('div').remove();
                }
            });
            $('#productIdDiv_' + itr).remove();
            if (data != "-1") {
                $('#manyParents_' + itr).append(data);
            }
            else
            {
                $.post('salesreportajax.php?do=getproductsbills', {id: id, itr: itr}, function (data) {
                    $('#manyParents_' + itr).append(data);
                });
            }
        });

    });

    if ($('.searchBills').length > 0)
    {
        //in show page
        $('.searchBills2').click();
        $('.searchBills3').click();
        $('.searchBills4').click();

    }

});

