
Runner.pages.PageSettings.addPageEvent( 
	"customer_payment", 
	"add", 
	"afterPageReady", 
	function(pageObj, proxy, pageid, inlineRow, inlineObject, row ) {
		/* ============================================================
   BuildLedger Customer Payment Add Page
   - Preview payment summary before Save
   ============================================================ */

(function () {

    function blNumber(value) {
        if (value === null || value === undefined) {
            return 0;
        }

        value = String(value).replace(/,/g, "").replace("₱", "").trim();

        var n = parseFloat(value);
        return isNaN(n) ? 0 : n;
    }

    function blMoney(value) {
        return Number(value || 0).toFixed(2);
    }

    function blFindField($row, fieldName) {
        return $row.find(
            "input[name*='" + fieldName + "'], " +
            "select[name*='" + fieldName + "'], " +
            "textarea[name*='" + fieldName + "']"
        ).first();
    }

    function blSetHeaderAmount(fieldName, value) {
        var amount = blMoney(value);

        try {
            var ctrl = Runner.getControl(pageid, fieldName);

            if (ctrl) {
                ctrl.setValue(amount);
                return;
            }
        } catch (e) {
        }

        $("input[name*='" + fieldName + "']").val(amount);
        $("span[id*='" + fieldName + "']").text(amount);
        $("td[id*='" + fieldName + "']").text(amount);
        $("div[id*='" + fieldName + "']").text(amount);
    }

    function blGetHeaderAmount(fieldName) {
        try {
            var ctrl = Runner.getControl(pageid, fieldName);

            if (ctrl) {
                return blNumber(ctrl.getValue());
            }
        } catch (e) {
        }

        return blNumber($("input[name*='" + fieldName + "']").first().val());
    }

    function blRecalculatePaymentPreview() {

        var grossAmount = blGetHeaderAmount("gross_amount");
        var bankChargeAmount = blGetHeaderAmount("bank_charge_amount");

        var appliedAmount = 0;
        var discountTakenAmount = 0;
        var withholdingAmount = 0;

        $("tr").each(function () {

            var $row = $(this);

            var $salesId = blFindField($row, "sales_id");
            var $applied = blFindField($row, "applied_amount");

            if (!$salesId.length || !$applied.length) {
                return;
            }

            appliedAmount += blNumber($applied.val());
            discountTakenAmount += blNumber(blFindField($row, "discount_taken_amount").val());
            withholdingAmount += blNumber(blFindField($row, "withholding_applied_amount").val());
        });

        var netReceivedAmount = grossAmount - withholdingAmount - bankChargeAmount;

        if (netReceivedAmount < 0) {
            netReceivedAmount = 0;
        }

        var unappliedAmount = netReceivedAmount - appliedAmount;

        blSetHeaderAmount("withholding_amount", withholdingAmount);
        blSetHeaderAmount("net_received_amount", netReceivedAmount);
        blSetHeaderAmount("applied_amount", appliedAmount);
        blSetHeaderAmount("unapplied_amount", unappliedAmount);
    }

    function blEqualizePaymentPanels() {

        var allowedTitles = [
            "Customer",
            "Payment Method",
            "Payment Document",
            "Currency",
            "Payment Summary",
            "Remarks",
            "Audit / Status"
        ];

        var $panels = $(".panel").filter(function () {
            var title = $.trim($(this).find(".panel-heading").first().text());

            return allowedTitles.indexOf(title) >= 0;
        });

        if (!$panels.length) {
            return;
        }

        $panels.css("min-height", "");

        var groups = {};

        $panels.each(function () {
            var $panel = $(this);
            var top = Math.round($panel.offset().top / 25) * 25;

            if (!groups[top]) {
                groups[top] = [];
            }

            groups[top].push($panel);
        });

        $.each(groups, function (top, panels) {
            if (panels.length < 2) {
                return;
            }

            var maxHeight = 0;

            $.each(panels, function (i, $panel) {
                maxHeight = Math.max(maxHeight, $panel.outerHeight());
            });

            $.each(panels, function (i, $panel) {
                $panel.css("min-height", maxHeight + "px");
            });
        });
    }

    function blRunFix() {
        blEqualizePaymentPanels();

        setTimeout(blEqualizePaymentPanels, 300);
        setTimeout(blEqualizePaymentPanels, 900);
    }

    $(document).on("keyup change blur", "input, select, textarea", function () {
        setTimeout(blRecalculatePaymentPreview, 100);
        setTimeout(blRunFix, 150);
    });

    $(window).on("resize", function () {
        setTimeout(blRunFix, 150);
    });

    setTimeout(blRunFix, 300);
    setTimeout(blRecalculatePaymentPreview, 500);

})();
});


Runner.pages.PageSettings.addPageEvent( 
	"customer_payment", 
	"edit", 
	"afterPageReady", 
	function(pageObj, proxy, pageid, inlineRow, inlineObject, row ) {
		/* ============================================================
   BuildLedger Customer Payment Edit Page
   - Layout only
   - Do not overwrite saved payment summary
   ============================================================ */

(function () {

    function blEqualizeCustomerPaymentPanels() {

        var allowedTitles = [
            "Customer",
            "Payment Document",
            "Payment Method",
            "Currency",
            "Remarks",
            "Payment Summary",
            "Audit / Status"
        ];

        var $panels = $(".panel").filter(function () {
            var title = $.trim($(this).find(".panel-heading").first().text());
            return allowedTitles.indexOf(title) >= 0;
        });

        if (!$panels.length) {
            return;
        }

        $panels.css("min-height", "");

        var groups = {};

        $panels.each(function () {
            var $panel = $(this);
            var top = Math.round($panel.offset().top / 25) * 25;

            if (!groups[top]) {
                groups[top] = [];
            }

            groups[top].push($panel);
        });

        $.each(groups, function (top, panels) {
            if (panels.length < 2) {
                return;
            }

            var maxHeight = 0;

            $.each(panels, function (i, $panel) {
                maxHeight = Math.max(maxHeight, $panel.outerHeight());
            });

            $.each(panels, function (i, $panel) {
                $panel.css("min-height", maxHeight + "px");
            });
        });
    }

    function blRunLayoutFix() {
        blEqualizeCustomerPaymentPanels();
        setTimeout(blEqualizeCustomerPaymentPanels, 300);
        setTimeout(blEqualizeCustomerPaymentPanels, 900);
    }

    $(window).on("resize", function () {
        setTimeout(blRunLayoutFix, 150);
    });

    setTimeout(blRunLayoutFix, 300);

})();
});







