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

    });
    var formatResult;

    var hosturl = $("#hosturl").val();

    formatResult = function (data) {

        return  data.text;
    }
    /*===========================client ===========================*/
    if ($("#client_id").length > 0)
    {
        $("#client_id").select2({
            placeholder: "إسم  العميل",
            minimumInputLength: document.getElementById("searchvalue").value,
            //minimumInputLength: 3,
            multiple: false,
            quietMillis: 100,
            ajax: {
                url: "projectControllerAjax.php?do=getclient",
                dataType: 'json',
                data: function (term, page) {
                    return {
                        term: term, //search term
                        page_limit: 10 // page size
                    };
                },
                results: function (data) {
                    return {results: data};
                }
            },
            formatResult: formatResult,
            initSelection: function (element, callback) {
                var item = element.val().split(':');
                var data = {id: item[0], text: item[1]};
                callback(data);
            }
        });

        $("#client_id").live("change", function () {
            var id = $("#client_id").val();
            $.post('projectControllerAjax.php?do=clientdebt', {id: id}, function (data)
            {
                $("#currentDebt").val(data);
            });
        });

    }

    $("#receipt-form").validate();



    /* =========================================================================================================== */

    $('.sellbill-payed,.bills-payed').live('click', function () {

//to dispaly new debt
        var item = $(this).closest("tr")   // Finds the closest row <tr>
                .find('td:eq(2)').html();   // Gets a descendent with class="nr"
        // Retrieves the text within <td>
//alert(item);

        var billid = $(this).attr('data-id');
        var billtype = $(this).attr('data-type');
        var clientid = $(this).attr('data-clientid');
        var debtbefore = $(this).attr('data-debtbefore');
        var itr = $(this).attr('data-itr');

        $("#billid").val(billid);
        $("#billtype").val(billtype);//0 فاتورة مبيعات //1 فاتورة بصريات
        $("#billclientid").val(clientid);
        $("#debtbefore").val(debtbefore);
        ////////modal
        $("#payed-modal").modal('show');

        $("#currentitr").val(itr);
        //$("#clientpayed").focus();


    })

    $("#bankid").live('change', function () {
        var id = $(this).val();
        $.post("projectControllerAjax.php?do=getbankaccount", {id: id}, function (data) {
            $("#bankaccountid").html(data);
        });
    });
    /*------------------------------------------------------------------------*/
    $("#clientpayed").live('keyup', function () {
        distributePayed();
    });
    $(".payedVal").live('keyup', function () {
        correctPayed();
    });
    function distributePayed() {
        var totalPayed = Number($("#clientpayed").val());
        var itr = 1;
        var clientpayed = 0;
        $('.payedVal').each(function () {
            var billdebt = $("[data-itr='" + itr + "']").attr('data-debtbefore');
            var thevalue = 0;
            var debtafter = 0;
            if (totalPayed == billdebt) {
                thevalue = totalPayed;
                debtafter = 0;
            }
            else if (totalPayed > billdebt)
            {
                thevalue = billdebt;
                debtafter = 0;
            }
            else if (totalPayed < billdebt) {
                thevalue = totalPayed;
                debtafter = billdebt - totalPayed;
            }
            var newDebt = billdebt - thevalue;
            $("#remain" + itr).html(newDebt);
            var remain = totalPayed - thevalue;
            totalPayed = remain;
            if (thevalue == 0) {
                thevalue = "";
            }
            $("[data-itr='" + itr + "']").first().val(thevalue);
            itr++;
            clientpayed += Number(thevalue);

        });

        var currentDebt = $("#currentDebt").val();
        var totalDebtAfter = currentDebt - clientpayed;
        $("#totalDebtAfter").html(totalDebtAfter);
    }
    function correctPayed() {
        var totalPayed = 0;
        var itr = 1;
        $('.payedVal').each(function () {
            var billdebt = Number($("[data-itr='" + itr + "']").attr('data-debtbefore'));
            var thevalue = Number($("[data-itr='" + itr + "']").first().val());
            if (thevalue > billdebt) {
                thevalue = billdebt;
                if (thevalue == 0) {
                    $("[data-itr='" + itr + "']").first().val("");
                }
                else
                {
                    $("[data-itr='" + itr + "']").first().val(thevalue);
                }
            }
            totalPayed += thevalue;
            var newDebt = billdebt - thevalue;
            $("#remain" + itr).html(newDebt);
            itr++;


        });

        $("#clientpayed").val(totalPayed);

        var currentDebt = $("#currentDebt").val();
        var totalDebtAfter = currentDebt - totalPayed;
        $("#totalDebtAfter").html(totalDebtAfter);
    }
    /*------------------------------------------------------------------------*/
    $(".payedtypeck").live('change', function () {

        var whatis = $(this).val();
        if (whatis == 0) {
            $('#check-div').hide();
            $('#bank-div').hide();
        } else if (whatis == 1) {
            $('#check-div').show();
            $('#bank-div').hide();
        }
        else if (whatis == 2) {
            $('#bank-div').show();
            $('#check-div').hide();
        }
    });


    $("#submit_paynetwork").live('click', function () {
        payBill();
    });
    function payBill() {

        var paymethod = Number($('#mypaymethod').val());
        if (paymethod == 0)
        {
            var noOfBillsLeft = $(".payedVal").length;
            if (noOfBillsLeft < 1)
            {
                var thecurrency = $('#thecurrency').val();
                alert("عفوا لا يوجد فواتير اخرى لدفعها وتبقى مبلغ " + $("#clientpayed").val() + thecurrency);
                return false;
            }


            var xxitr = $("#currentitr").val();
            var debtbefore = $("[data-itr='" + xxitr + "']").attr('data-debtbefore');
            var billclientid = $("[data-itr='" + xxitr + "']").attr('data-clientid');
            var billtype = $("[data-itr='" + xxitr + "']").attr('data-type');
            var billid = $("[data-itr='" + xxitr + "']").attr('data-id');
            $('#debtbefore').val(debtbefore);
            $('#billclientid').val(billclientid);
            $('#billtype').val(billtype);
            $('#billid').val(billid);
        }
        $.post('projectControllerAjax.php?do=paynetwork', $('#paynetwork-form').serialize(), function (data)
        {
            //alert(data);
            if (data == "paymethod1success")
            {
                window.location = "clientreceiptController.php?do=sucess";
            }
            else {
                //$("#mydivToPay").html(data);
                var itr = $("#currentitr").val();
                data = data.split("-");
                var newDebt = data[0];
                var remainPayed = data[1];
                newDebt = Number(newDebt);
                remainPayed = Number(remainPayed);
                if (newDebt <= 0)
                {
                    $("[data-itr='" + itr + "']").parent().parent().remove();
                }
                else if (newDebt > 0)
                {
                    $("[data-itr='" + itr + "']").attr('data-debtbefore', newDebt);
                    $("#sellbillremain" + itr).html(newDebt);
                    $("[data-itr='" + itr + "']").first().val("");
                }
                else
                {
                    alert("عفوا لقد حدث خطأ");
                }



                if (remainPayed == 0)
                {
                    ////////modal
                    $("#payed-modal").modal('hide');
                    $("#clientpayed").val("");
                }
                else if (remainPayed > 0) {

                    itr = Number(itr);
                    itr = itr + 1;
                    $("#currentitr").val(itr);
                    $("#clientpayed").val(remainPayed);
                    //pay another bill
                    payBill();
                }
            }


        })
    }

    $(".searchRecit").live("change", function () {

        $.post('projectControllerAjax.php?do=search', $("#receipt-form").serialize(), function (data)
        {
            //alert(data);
            $("#mydivToPay").html(data);
        });
    });

})




