// JavaScript Document

$(".select2Supp2").select2({
    allowClear: true,
    placeholder: "كل العملاء",
    //minimumInputLength: document.getElementById("searchvalue").value,
    minimumInputLength: 0,
    multiple: false,
    quietMillis: 100,
    ajax: {
        url: "clientControllerAjax.php?do=select2ClientsAjax",
        dataType: 'json',
        data: function (term, page) {
            return {
                term: term, //search term
                page_limit: 7, // page size
                //withAddOption: 1,
                //withNakdi: 1,
                //jsonRowRet: 1,
            };
        },
        results: function (data) {
            return {results: data};
        }
    },
    formatResult: function (data) {
        if (Number(data.id) == -2) {
            return  '<span class="newoption">' + data.text + '</span >';
        } else {
            return  '<span>' + data.text + '</span >';
        }
    },
    initSelection: function (element, callback) {
        var item = element.val().split(':');
        //  var data = {id: item[0], text: item[1]};
        var data = {id: item[0], text: item[1], productquantity: item[2], price: item[3]};
        callback(data);
    },
    //dropdownCssClass: "bigdrop", // apply css that makes the dropdown taller
});

var select2Supp2id = $('#select2Supp2id').val();
if (select2Supp2id) {
    $('.select2Supp2').select2('data', {id: select2Supp2id, text: $('#select2Supp2text').val()});
}
var closingcustomeraccount = $('#closingcustomeraccount').val();
if (closingcustomeraccount == 1) {
    $(document).on('change', ".select2Supp", function () {
        var clientid = $(this).val();
        $.post("closingAccountController.php?do=getdata", {client_id: clientid}, function (data) {
            var nu = Number(data);
            $('#totalpayments').val(nu);
        });
    });
}

$(".select2Recits").select2({
    allowClear: true,
    placeholder: "كل الايصالات",
    //minimumInputLength: document.getElementById("searchvalue").value,
    minimumInputLength: 2,
    multiple: false,
    quietMillis: 100,
    ajax: {
        url: "clientPayedDeptControllerAjax.php?do=select2receipts",
        dataType: 'json',
        data: function (term, page) {
            return {
                term: term, //search term
                page_limit: 7, // page size
            };
        },
        results: function (data) {
            return {results: data};
        }
    },
    formatResult: function (data) {
        return  '<span>' + data.text + '</span >';

    },
    initSelection: function (element, callback) {
        var item = element.val().split(':');
        //  var data = {id: item[0], text: item[1]};
        var data = {id: item[0], text: item[1], productquantity: item[2], price: item[3]};
        callback(data);
    },
    //dropdownCssClass: "bigdrop", // apply css that makes the dropdown taller
});
$("#paySerialNu").select2({
    allowClear: true,
    placeholder: "كل الايصالات",
    //minimumInputLength: document.getElementById("searchvalue").value,
    minimumInputLength: 0,
    multiple: false,
    quietMillis: 100,
    ajax: {
        url: "clientPayedDeptControllerAjax.php?do=select2paySerialNo",
        dataType: 'json',
        data: function (term, page) {
            return {
                term: term, //search term
                page_limit: 7, // page size
            };
        },
        results: function (data) {
            return {results: data};
        }
    },
    formatResult: function (data) {
        return  '<span>' + data.text + '</span >';

    },
    initSelection: function (element, callback) {
        var item = element.val().split(':');
        //  var data = {id: item[0], text: item[1]};
        var data = {id: item[0], text: item[1], productquantity: item[2], price: item[3]};
        callback(data);
    },
    //dropdownCssClass: "bigdrop", // apply css that makes the dropdown taller
});
$(document).ready(function (e) {

    $(document).on('change', ".clientorsupplier", function () {
        var clientorsupplier = $('input[name=clientorsupplier]:checked').val();
        if (clientorsupplier == 1) {
            $('.supplierform').hide();
            $('.clientform').show();
            $('.saveorbankform').show();
            $('#myform').attr('action', 'clientPayedDeptController.php?do=add');
        } else {
            $('.clientform').hide();
            $('.supplierform').show();
            $('.saveorbankform').hide();
            $('.bankshow').hide();
            $('.saveshow').show();
            $('#myform').attr('action', 'supplierPayedDeptController.php?do=add');
        }

    });

    $("#supplierid").change(function (e) {
        $.ajax({
            url: "supplierPayedDeptControllerAjax.php?id=" + $(this).val(),
            type: "get",
            success: function (data) {
                var response = $.parseJSON(data);
                $("#debtBefore").val(response.suppliercurrentDebt);
                $("#lastDate").val(response.supplierdate);
            },
            error: function () {
                alert("لقد حدث خطأ أثناء إجراء العملية");
            }
        });
    });


    function matcher(term, text, opt) {
        //var label = $(opt).val();//.attr('id');
        var label = String($(opt).data('mobile'));//data of option to search into it too

        term = term.toUpperCase();//term to search
        text = text.toUpperCase();//text of option

        if (text.indexOf(term) > -1 || (label !== undefined && label.toUpperCase().indexOf(term) > -1)) {
            return true;
        }

        return false;
    }
    // $('.select2Supp').select2({
    //     matcher: matcher
    // });

    if (!localStorage.getItem('azmy')) {
        $("#clientid").change(function (e) {
            $("#lastDate").val("");
            $("#payedDept").val("");
            $("#debtAfter").val("");

            $("#debtBefore").val("");
            $("#lastDate").val("");
            if (Number($(this).val()) > 0) {
                $.ajax({
                    url: "clientPayedDeptControllerAjax.php?id=" + $(this).val(),
                    type: "get",
                    async: false,
                    success: function (data) {
                        var response = $.parseJSON(data);
                        $("#debtBefore").val(response.clientdebt);
                        $(".debtBefore").val(response.clientdebt);
                        $("#lastDate").val(response.clientdate);
                    },
                    error: function () {
                        alert("لقد حدث خطأ أثناء إجراء العملية");
                    }
                });
            }
        });
    }
    ///////////////////////////////////////////////
//
//    $("#clientid").change(function (e) {  // return all inputs to the default state
//        $("#lastDate").val("");
//        $("#payedDept").val("");
//        $("#debtAfter").val("");
//    });

});


//function will allow negative numbers in debtAfter
function populateDebtAfter(TriggerInputName)
{
    if (TriggerInputName == 'payedDeptCurr') {
        //get payedDept in Main currency
        var cFactor = Number($('#cFactor').val());//Number($('#currencyId :selected').data('cfactor'));
        var payedDeptCurr = Number($("#payedDeptCurr").val());
        payedDept = Number((payedDeptCurr / cFactor).toFixed(4));//convert to main curr
        $("#payedDept").val(payedDept);
    } else if (TriggerInputName == 'payedDept') {
        //payedDept is in Main currency
        var payedDeptCurr = Number($("#payedDeptCurr").val());
        var payedDept = Number($("#payedDept").val());
//        if (payedDeptCurr == 0) {
//            var cFactor = Number($('#cFactor').val());
//            payedDeptCurr = Number((payedDept * cFactor).toFixed(4));
//        }else
        cFactor = Number((payedDeptCurr / payedDept).toFixed(7));
        $('#cFactor').val(cFactor);
    }

    var payedDept = Number($("#payedDept").val());
    var debtBefore = Number($("#debtBefore").val());
    var earlyRepayment = Number($("#earlyRepayment").val());
    var clientnegative = Number($("#clientnegative").val());
    var clientorsupplier = $('input[name=clientorsupplier]:checked').val();


    if (!earlyRepayment)
        var earlyRepayment = 0;

    if (clientnegative == 0)
    {
        if (debtBefore)
        {
            if (payedDept <= debtBefore)
            {
                if (clientorsupplier == 2) {
                    var debtAfter = debtBefore - earlyRepayment + payedDept;
                } else {
                    var debtAfter = debtBefore - earlyRepayment - payedDept;
                }
                $("#debtAfter").val(debtAfter);
            } else
            {
                $("#debtAfter").val(0);
                $("#payedDept").val(debtBefore)
                var payedDeptCurr = Number((debtBefore * cFactor).toFixed(4));//convert from main curr
                $("#payedDeptCurr").val(payedDeptCurr);
            }
        } else//if user didn't choose any client yet
        {
            $("#payedDept").val(0);
            $("#payedDeptCurr").val(0);
            //alert("يرجى اختيار عميل");
        }
    } else
    {
        if (clientorsupplier == 2) {
            var debtAfter = debtBefore - earlyRepayment + payedDept;
        } else {
            var debtAfter = debtBefore - earlyRepayment - payedDept;
        }


        // var debtAfter = debtBefore - payedDept;
        $("#debtAfter").val(debtAfter);
        //alert(1);


    }
}


$('#currencyId').live('change', function (e) {
    $('#currencyText').text($('#currencyId').select2('data').text);
    var cfactor = $('#currencyId').select2("data").element[0].attributes['data-cfactor'].value
    $('#cFactor').val(cfactor);
    populateDebtAfter();
});
$('#saveid').live('change', function (e) {
    var curr = Number($('#saveid option:selected').data('curr'));
    $('#currencyId').val(curr).change();
});

$(function () {
    if ($('#currencyId').length > 0) {
        //$('#currencyId').change();
        $('#saveid').change();//and this will trigger currency
    }
    if (Number($('#clientidFromGET').val()) > 0) {
        //$('#currencyId').change();
        $('#clientid').select2("enable", false);
        $('#clientid').val($('#clientidFromGET').val()).change();
    }
});

$('#saveBtn, #saveAndNewBtn').live('click', function (e) {
    if (!$(this).hasClass('precessing')) {
        $('.saveBtnClass').addClass('precessing');

        var thisBtn = $(this);
        var clientid = $('#clientid').val();

        $.post("premiumAjaxController.php?do=checkPremiumClient", {clientID: clientid}, function (data) {
            var nu = Number(data);

            if (nu == 1) {
                $('.clientNotPremium').remove();
            } else {
                $('.clientFindPremium').remove();
                var payedDept = $('#payedDept').val();
            }

            var voucher = $('#voucher').val();
            var currentDate = $('#currentDate').val();
            var clientorsupplier = $('input[name=clientorsupplier]:checked').val();
            var saveorbank = Number($('input[name=saveorbank]:checked').val());
            var payedDeptBank = $('#txtAmountxx').val();
            var ddlBank = Number($('#ddlBank').val());
            var accountid = Number($('#accountid').val());




            if (clientid == '-1' && clientorsupplier == 1) {
                $('#clientError').show();
                $('#clientError').html("<p style='color: #CC3333;border: 1px solid #CC3333;width: 69px;'>*اختر عميل</p>");
                $('.saveBtnClass').removeClass('precessing');
            } else if (ddlBank < 1 && saveorbank == 2) {
                $('#clientError').hide();
                $('#bankerror').show();
                $('#bankerror').html("<p style='color: #CC3333;border: 1px solid #CC3333;width: 124px;'>* اختر البنك</p>");
                $('.saveBtnClass').removeClass('precessing');
            } else if (accountid < 1 && saveorbank == 2) {
                $('#clientError').hide();
                $('#bankerror').hide();
                $('#counterror').show();
                $('#counterror').html("<p style='color: #CC3333;border: 1px solid #CC3333;width: 124px;'>* اختر الحساب</p>");
                $('.saveBtnClass').removeClass('precessing');
            } else if (voucher == '') {
                $('#clientError').hide();
                $('#bankerror').hide();
                $('#counterror').hide();
                $('#voucherError').show();
                $('#voucherError').html("<p style='color: #CC3333;border: 1px solid #CC3333;width: 98px;'>* ادخل رقم الايصال </p>");
                $('.saveBtnClass').removeClass('precessing');
            } else if (currentDate == '') {
                $('#clientError').hide();
                $('#bankerror').hide();
                $('#counterror').hide();
                $('#voucherError').hide();
                $('#dateError').show();
                $('#dateError').html("<p style='color: #CC3333;border: 1px solid #CC3333;width: 153px;'>* ادخل تاريخ  السداد الحالى </p>");
                $('.saveBtnClass').removeClass('precessing');
            } else if ((payedDept == '' || payedDept == '0') && saveorbank == 1) {
                $('#clientError').hide();
                $('#bankerror').hide();
                $('#counterror').hide();
                $('#voucherError').hide();
                $('#dateError').hide();
                $('#payedDeptError').show();
                $('#payedDeptError').html("<p style='color: #CC3333;border: 1px solid #CC3333;width: 124px;'>* ادخل  قيمة المدفوع</p>");
                $('.saveBtnClass').removeClass('precessing');
            } else if ((payedDeptBank == '' || payedDeptBank == '0') && saveorbank == 2) {
                $('#clientError').hide();
                $('#bankerror').hide();
                $('#counterror').hide();
                $('#voucherError').hide();
                $('#dateError').hide();
                $('#payedDeptError').hide();
                $('#chekamountError').show();
                $('#chekamountError').html("<p style='color: #CC3333;border: 1px solid #CC3333;width: 124px;'>* ادخل  قيمة الايداع</p>");
                $('.saveBtnClass').removeClass('precessing');
            } else {
                $('#clientError').hide();
                //get latest debt before submit
                var payedDept = Number($('#payedDept').val());
                $('#clientid').change();
                $('#payedDept').val(payedDept).keyup();
                //
                $('#clientid').select2("enable");
                if (thisBtn.attr('id') == "saveAndNewBtn") {
                    $('#add_And_New').val(1);
                }
                $('#myform').submit();
                $('#saveBtn').attr("disabled", true);
                $('#add_print_btn').attr("disabled", true);
                $('#add_print_btn').attr("disabled", true);
            }


        });
    }

});

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

    if (!$(this).hasClass('precessing')) {
        $('.saveBtnClass').addClass('precessing');

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

        $.post("premiumAjaxController.php?do=checkPremiumClient", {clientID: clientid}, function (data) {
            var nu = Number(data);

            if (nu == 1) {
                $('.clientNotPremium').remove();
            } else {
                $('.clientFindPremium').remove();
                var payedDept = $('#payedDept').val();
            }

            var voucher = $('#voucher').val();
            var currentDate = $('#currentDate').val();
            var clientorsupplier = $('input[name=clientorsupplier]:checked').val();
            var saveorbank = Number($('input[name=saveorbank]:checked').val());
            var payedDeptBank = $('#txtAmountxx').val();
            var ddlBank = Number($('#ddlBank').val());
            var accountid = Number($('#accountid').val());




            if (clientid == '-1' && clientorsupplier == 1) {
                $('#clientError').show();
                $('#clientError').html("<p style='color: #CC3333;border: 1px solid #CC3333;width: 69px;'>*اختر عميل</p>");
                $('.saveBtnClass').removeClass('precessing');
            } else if (ddlBank < 1 && saveorbank == 2) {
                $('#clientError').hide();
                $('#bankerror').show();
                $('#bankerror').html("<p style='color: #CC3333;border: 1px solid #CC3333;width: 124px;'>* اختر البنك</p>");
                $('.saveBtnClass').removeClass('precessing');
            } else if (accountid < 1 && saveorbank == 2) {
                $('#clientError').hide();
                $('#bankerror').hide();
                $('#counterror').show();
                $('#counterror').html("<p style='color: #CC3333;border: 1px solid #CC3333;width: 124px;'>* اختر الحساب</p>");
                $('.saveBtnClass').removeClass('precessing');
            } else if (voucher == '') {
                $('#clientError').hide();
                $('#bankerror').hide();
                $('#counterror').hide();
                $('#voucherError').show();
                $('#voucherError').html("<p style='color: #CC3333;border: 1px solid #CC3333;width: 98px;'>* ادخل رقم الايصال </p>");
                $('.saveBtnClass').removeClass('precessing');
            } else if (currentDate == '') {
                $('#clientError').hide();
                $('#bankerror').hide();
                $('#counterror').hide();
                $('#voucherError').hide();
                $('#dateError').show();
                $('#dateError').html("<p style='color: #CC3333;border: 1px solid #CC3333;width: 153px;'>* ادخل تاريخ  السداد الحالى </p>");
                $('.saveBtnClass').removeClass('precessing');
            } else if ((payedDept == '' || payedDept == '0') && saveorbank == 1) {
                $('#clientError').hide();
                $('#bankerror').hide();
                $('#counterror').hide();
                $('#voucherError').hide();
                $('#dateError').hide();
                $('#payedDeptError').show();
                $('#payedDeptError').html("<p style='color: #CC3333;border: 1px solid #CC3333;width: 124px;'>* ادخل  قيمة المدفوع</p>");
                $('.saveBtnClass').removeClass('precessing');
            } else if ((payedDeptBank == '' || payedDeptBank == '0') && saveorbank == 2) {
                $('#clientError').hide();
                $('#bankerror').hide();
                $('#counterror').hide();
                $('#voucherError').hide();
                $('#dateError').hide();
                $('#payedDeptError').hide();
                $('#chekamountError').show();
                $('#chekamountError').html("<p style='color: #CC3333;border: 1px solid #CC3333;width: 124px;'>* ادخل  قيمة الايداع</p>");
                $('.saveBtnClass').removeClass('precessing');
            } else {
                $('#add_print').val('1'); /////////////// only diffrence to normal save btn
                $('#clientError').hide();
                //get latest debt before submit
                var payedDept = Number($('#payedDept').val());
                $('#clientid').change();
                $('#payedDept').val(payedDept).keyup();
                //
                $('#clientid').select2("enable");
                $('#myform').submit();
                $('#saveBtn').attr("disabled", true);
                $('#add_print_btn').attr("disabled", true);
                $('#add_print_btn').attr("disabled", true);

            }

        });


    }
});



$(document).on('change', ".saveorbank", function () {
    var saveorbank = $('input[name=saveorbank]:checked').val();
    if (saveorbank == 1) {
        $('.supplierform').hide();
        $('.bankshow').hide();
        $('.saveshow').show();

        $('#myform').attr('action', 'clientPayedDeptController.php?do=add');
    } else {
        $('.supplierform').hide();
        $('.saveshow').hide();
        $('.bankshow').show();

        $('#myform').attr('action', 'depositcheckController.php?do=add');
    }

});


$(document).on('change', ".saveorbankPremium", function () {
    var saveorbank = $('input[name=saveorbankPremium]:checked').val();
    if (saveorbank == 1) {
        $('.supplierform').hide();
        $('.bankshowPremium').hide();
        $('.saveshowPremium').show();

        $('#myform').attr('action', 'clientPayedDeptController.php?do=add');
    } else {
        $('.supplierform').hide();
        $('.saveshowPremium').hide();
        $('.bankshowPremium').show();

        $('#myform').attr('action', 'depositcheckController.php?do=add');
    }

});

$('.editBillPayment').live('click', function (e) {
    var btn = $(this);
    if (!btn.hasClass('processing...')) {
        btn.addClass('processing...');

        var id = $(this).data('id');
        var billid = $(this).data('billid');
        var type = $(this).data('paytype');
        type = type.split('-');
        if (type[0].trim() == "خزنة")
            type = "save";
        else if (type[0].trim() == "بنك")
            type = "bank";

        if (confirm("هل انت متاكد؟\n\
        سيتم حذف الدفعه الحاليه الان وتحويلك لاضافه دفعة جديده.") == true) {
            $.post('sellbillAjaxController.php?do=delMakeSellBillPayment', {clientdebtchangeId: id, paytype: type}, function (data) {
                btn.removeClass('processing...');
                if (Number(data) == 1) {
                    //btn.parent().parent().remove();
                    window.location = 'clientPayedDeptSellBillsController.php?bill_no=' + billid;
                } else {
                    alert('عفوا حدث خطأ.حاول مرة اخرى')
                }
            });


        }
    } else {
        //"You canceled!";
    }
});