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

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

    });

    $("#clientid").change(function (e) {
        $("#lastDate").val("");
        $("#payedDept").val("");
        $("#debtAfter").val("");

        $("#debtBefore").val("");
        $("#debtBeforebank").val("");
        $("#lastDate").val("");
        $("#txtAmountxx").val("");
        $("#debtAfterBank").val("");

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


});


//function will allow negative numbers in debtAfter
function populateDebtAfter(TriggerInputName) {
    if (TriggerInputName == 'payedDeptCurr') {
        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 , get cFactor using payedDeptCurr also
        var payedDeptCurr = Number($("#payedDeptCurr").val());
        var payedDept = Number($("#payedDept").val());
        cFactor = Number((payedDeptCurr / payedDept).toFixed(7));
        $('#cFactor').val(cFactor);
        $('#otherCFactor').val(Number(1 / cFactor))
    }

    //alert(2222);
    var payedDept = Number($("#payedDept").val());
    var debtBefore = Number($("#debtBefore").val());
    var suplliernegative = Number($("#suplliernegative").val());
    var clientorsupplier = $('input[name=clientorsupplier]:checked').val();
    //alert(suplliernegative);

    if (suplliernegative == 0) {
        //alert('in if');
        if (debtBefore) {
            if (payedDept <= debtBefore) {
                if (clientorsupplier == 2) {
                    var debtAfter = debtBefore + payedDept;
                } else {
                    var debtAfter = debtBefore - 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 {
        //alert('in else');

        if (debtBefore >= 0 || debtBefore <= 0) {
            if (clientorsupplier == 2) {
                var debtAfter = debtBefore + payedDept;
            } else {
                var debtAfter = debtBefore - payedDept;
            }
            $("#debtAfter").val(debtAfter);
        } else//if user didn't choose any client yet
        {
            $("#payedDept").val(0);
            $("#payedDeptCurr").val(0);
            //alert("يرجى اختيار مورد");
        }

    }
}


$('#saveSupPayBtn').live('click', function (e) {
    var supplierid = $('#supplierid').val();
    var value = $('#payedDept').val();
    var valueBank = $('#txtAmountxx').val();
    var clientorsupplier = $('input[name=clientorsupplier]:checked').val();
    var saveorbank = $('input[name=saveorbank]:checked').val();
    value = value.trim();
    valueBank = valueBank.trim();
    var ddlBank = Number($('#ddlBank').val());
    var accountid = Number($('#accountid').val());
    var accountbeginingbalance = Number($('#accountbeginingbalance').val());
    if (supplierid == '-1' && clientorsupplier == 1) {
        $('#suppError').show();
        $('#suppError').html("<p style='color: #CC3333;border: 1px solid #CC3333;width: 105px;'>*اختر اسم المورد </p>");
    } else if (ddlBank < 1 && saveorbank == 2) {
        $('#suppError').hide();
        $('#bankerror').show();
        $('#bankerror').html("<p style='color: #CC3333;border: 1px solid #CC3333;width: 124px;'>* اختر البنك</p>");
    } else if (accountid < 1 && saveorbank == 2) {
        $('#suppError').hide();
        $('#bankerror').hide();
        $('#counterror').show();
        $('#counterror').html("<p style='color: #CC3333;border: 1px solid #CC3333;width: 124px;'>* اختر الحساب</p>");
    } else if (value == '' && saveorbank == 1) {
        $('#suppError').hide();
        $('#bankerror').hide();
        $('#counterror').hide();
        $('#valueError').show();
        $('#valueError').html("<p style='color: #CC3333;border: 1px solid #CC3333;width: 119px;'>* ادخل قيمة المدفوع </p>");
    } else if (valueBank == '' && saveorbank == 2) {
        $('#suppError').hide();
        $('#valueError').hide();
        $('#bankerror').hide();
        $('#counterror').hide();
        $('#chekamountError').show();
        $('#chekamountError').html("<p style='color: #CC3333;border: 1px solid #CC3333;width: 119px;'>* ادخل قيمة السحب </p>");
    } else if (Number(valueBank) > accountbeginingbalance && saveorbank == 2) {
        $('#suppError').hide();
        $('#valueError').hide();
        $('#bankerror').hide();
        $('#counterror').hide();
        $('#chekamountError').show();
        $('#chekamountError').html("<p style='color: #CC3333;border: 1px solid #CC3333;width: 143px;'>* لقد تخطيت قيمة الحساب </p>");
    } else {
        $('#suppError').hide();
        $('#valueError').hide();
        $('#chekamountError').hide();
        $('#saveSupPayBtn').attr("disabled", true);
        $('#add_print_btn').attr("disabled", true);
        $('#mySupPayForm').submit();
    }
});

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

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

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

});

$('#add_print_btn').live('click', function (e) {
    var supplierid = $('#supplierid').val();
    var value = $('#payedDept').val();
    var valueBank = $('#txtAmountxx').val();
    var clientorsupplier = $('input[name=clientorsupplier]:checked').val();
    var saveorbank = $('input[name=saveorbank]:checked').val();
    value = value.trim();
    valueBank = valueBank.trim();
    var ddlBank = Number($('#ddlBank').val());
    var accountid = Number($('#accountid').val());
    var accountbeginingbalance = Number($('#accountbeginingbalance').val());
    if (supplierid == '-1' && clientorsupplier == 1) {
        $('#suppError').show();
        $('#suppError').html("<p style='color: #CC3333;border: 1px solid #CC3333;width: 105px;'>*اختر اسم المورد </p>");
    } else if (ddlBank < 1 && saveorbank == 2) {
        $('#suppError').hide();
        $('#bankerror').show();
        $('#bankerror').html("<p style='color: #CC3333;border: 1px solid #CC3333;width: 124px;'>* اختر البنك</p>");
    } else if (accountid < 1 && saveorbank == 2) {
        $('#suppError').hide();
        $('#bankerror').hide();
        $('#counterror').show();
        $('#counterror').html("<p style='color: #CC3333;border: 1px solid #CC3333;width: 124px;'>* اختر الحساب</p>");
    } else if (value == '' && saveorbank == 1) {
        $('#suppError').hide();
        $('#bankerror').hide();
        $('#counterror').hide();
        $('#valueError').show();
        $('#valueError').html("<p style='color: #CC3333;border: 1px solid #CC3333;width: 119px;'>* ادخل قيمة المدفوع </p>");
    } else if (valueBank == '' && saveorbank == 2) {
        $('#suppError').hide();
        $('#valueError').hide();
        $('#bankerror').hide();
        $('#counterror').hide();
        $('#chekamountError').show();
        $('#chekamountError').html("<p style='color: #CC3333;border: 1px solid #CC3333;width: 119px;'>* ادخل قيمة السحب </p>");
    } else if (Number(valueBank) > accountbeginingbalance && saveorbank == 2) {
        $('#suppError').hide();
        $('#valueError').hide();
        $('#bankerror').hide();
        $('#counterror').hide();
        $('#chekamountError').show();
        $('#chekamountError').html("<p style='color: #CC3333;border: 1px solid #CC3333;width: 143px;'>* لقد تخطيت قيمة الحساب </p>");
    } else {
        $('#add_print').val('1'); /////////////// only diffrence to normal save btn
        $('#suppError').hide();
        $('#valueError').hide();
        $('#chekamountError').hide();
        $('#saveSupPayBtn').attr("disabled", true);
        $('#add_print_btn').attr("disabled", true);
        $('#mySupPayForm').submit();
    }
});
$('#currencyId').live('change', function (e) {
    $('#currencyText').text($('#currencyId').select2('data').text);
    var cfactor = $('#currencyId').select2("data").element[0].attributes['data-cfactor'].value;
    var oldOtherCFactor = $('#currencyId').select2("data").element[0].attributes['data-othercfactor'].value;
    $('#cFactor').val(cfactor);
    $('#otherCFactor').val(oldOtherCFactor);
    populateDebtAfter();
});
//changing cFactor affect otherCFactor,otherCFactor changing affect cFactor
$('.calcOther').live('keyup change', function () {
    var val = Number($(this).val());
    if (val == 0) {
        var otherVal = 0;
    } else {
        var otherVal = Number((1 / val).toFixed(6));
    }
    if ($(this).attr('id') == 'cFactor') {
        $('#otherCFactor').val(otherVal);
    } else {
        $('#cFactor').val(otherVal);
    }

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

function populateDebtAfterBank(TriggerInputName) {
    var payedDept = Number($("#txtAmountxx").val());
    var debtBefore = Number($("#debtBeforebank").val());
    var suplliernegative = Number($("#suplliernegative").val());
    var clientorsupplier = $('input[name=clientorsupplier]:checked').val();

    if (suplliernegative == 0) {
        if (debtBefore) {
            if (payedDept <= debtBefore) {
                if (clientorsupplier == 2) {
                    var debtAfter = debtBefore + payedDept;
                } else {
                    var debtAfter = debtBefore - payedDept;
                }

                $("#debtAfterbank").val(debtAfter);
            } else {
                $("#debtAfterbank").val(0);
                $("#txtAmountxx").val(debtBefore);
            }
        } else//if user didn't choose any client yet
        {
            $("#txtAmountxx").val(0);
        }
    } else {
        var debtAfter = 0;
        if (debtBefore >= 0 || debtBefore <= 0) {
            if (clientorsupplier == 2) {
                debtAfter = debtBefore + payedDept;
            } else {
                var debtAfter = debtBefore - payedDept;
            }
            $("#debtAfterbank").val(debtAfter);
        } else//if user didn't choose any client yet
        {
            $("#txtAmountxx").val(0);
        }
    }
}