
Runner.pages.PageSettings.addPageEvent( 
	"sales", 
	"add", 
	"afterPageReady", 
	function(pageObj, proxy, pageid, inlineRow, inlineObject, row ) {
		/* ============================================================
   BuildLedger Sales Add Page
   - Equalize section layout
   - Add spacing between section boxes
   - Preview invoice summary before Save
   - Preview computed inline detail amounts
   ============================================================ */

(function () {

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

        value = String(value)
            .replace(/,/g, "")
            .replace("₱", "")
            .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 blGetHeaderIndex($table, possibleLabels) {
        var foundIndex = -1;

        $table.find("thead th, tr:first th, tr:first td").each(function (index) {
            var text = $.trim($(this).text()).toLowerCase();

            for (var i = 0; i < possibleLabels.length; i++) {
                if (text.indexOf(possibleLabels[i].toLowerCase()) >= 0) {
                    foundIndex = index;
                    return false;
                }
            }
        });

        return foundIndex;
    }

    function blSetCellByHeader($row, possibleLabels, value) {
        var $table = $row.closest("table");
        var index = blGetHeaderIndex($table, possibleLabels);

        if (index < 0) {
            return;
        }

        var $cell = $row.children("td").eq(index);

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

        var amount = blMoney(value);

        var $input = $cell.find("input").first();

        if ($input.length) {
            $input.val(amount);
        } else {
            $cell.text(amount);
        }
    }

    function blSetRowValue($row, fieldName, labels, value) {
        var amount = blMoney(value);
        var $field = blFindField($row, fieldName);

        if ($field.length) {
            $field.val(amount);
        }

        blSetCellByHeader($row, labels, value);
    }

    function blParseRateFromSelect($select) {
        if (!$select.length) {
            return 0;
        }

        var text = $select.find("option:selected").text();
        var match = text.match(/(\d+(\.\d+)?)/);

        if (match) {
            return blNumber(match[1]);
        }

        return 0;
    }

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

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

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

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

    function blMakeLineNoReadonly() {
        $("input[name*='line_no']").each(function () {
            $(this)
                .prop("readonly", true)
                .attr("tabindex", "-1")
                .css({
                    "background-color": "#f7f7f7",
                    "pointer-events": "none"
                });
        });
    }

    function blRecalculateInvoicePreview() {

        var subtotalAmount = 0;
        var commercialDiscountAmount = 0;
        var statutoryDiscountAmount = 0;
        var vatAmount = 0;
        var withholdingAmount = 0;
        var grandTotalAmount = 0;

        var hasLine = false;

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

            var $row = $(this);

            var $qty = blFindField($row, "quantity");
            var $unitPrice = blFindField($row, "unit_price");

            if (!$qty.length || !$unitPrice.length) {
                return;
            }

            var qty = blNumber($qty.val());
            var unitPrice = blNumber($unitPrice.val());

            if (qty <= 0 && unitPrice <= 0) {
                return;
            }

            hasLine = true;

            var commercialRate = blNumber(blFindField($row, "commercial_discount_rate").val());
            var commercialAmount = blNumber(blFindField($row, "commercial_discount_amount").val());

            var statutoryRate = blNumber(blFindField($row, "statutory_discount_rate").val());
            var statutoryAmount = blNumber(blFindField($row, "statutory_discount_amount").val());

            var vatRate = blNumber(blFindField($row, "vat_rate_snapshot").val());
            var withholdingRate = blNumber(blFindField($row, "withholding_rate_snapshot").val());

            if (vatRate <= 0) {
                vatRate = blParseRateFromSelect(blFindField($row, "vat_tax_code_id"));
            }

            if (withholdingRate <= 0) {
                withholdingRate = blParseRateFromSelect(blFindField($row, "withholding_tax_code_id"));
            }

            var gross = qty * unitPrice;

            if (commercialAmount <= 0 && commercialRate > 0) {
                commercialAmount = gross * (commercialRate / 100);
            }

            var afterCommercial = gross - commercialAmount;

            if (statutoryAmount <= 0 && statutoryRate > 0) {
                statutoryAmount = afterCommercial * (statutoryRate / 100);
            }

            var netBeforeTax = afterCommercial - statutoryAmount;

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

            var lineVatAmount = netBeforeTax * (vatRate / 100);
            var lineWithholdingAmount = netBeforeTax * (withholdingRate / 100);
            var lineTotalAmount = netBeforeTax + lineVatAmount - lineWithholdingAmount;

            subtotalAmount += gross;
            commercialDiscountAmount += commercialAmount;
            statutoryDiscountAmount += statutoryAmount;
            vatAmount += lineVatAmount;
            withholdingAmount += lineWithholdingAmount;
            grandTotalAmount += lineTotalAmount;

            blSetRowValue($row, "gross_amount", ["Gross Amount"], gross);
            blSetRowValue($row, "vat_amount", ["VAT Amount", "Vat Amount"], lineVatAmount);
            blSetRowValue($row, "withholding_amount", ["Withholding Amount", "Withholding"], lineWithholdingAmount);
            blSetRowValue($row, "line_total_amount", ["Line Total Amount", "Line Total"], lineTotalAmount);
        });

        if (!hasLine) {
            blSetHeaderAmount("subtotal_amount", 0);
            blSetHeaderAmount("commercial_discount_amount", 0);
            blSetHeaderAmount("statutory_discount_amount", 0);
            blSetHeaderAmount("vat_amount", 0);
            blSetHeaderAmount("withholding_amount", 0);
            blSetHeaderAmount("grand_total_amount", 0);
            blSetHeaderAmount("base_grand_total_amount", 0);
            return;
        }

        blSetHeaderAmount("subtotal_amount", subtotalAmount);
        blSetHeaderAmount("commercial_discount_amount", commercialDiscountAmount);
        blSetHeaderAmount("statutory_discount_amount", statutoryDiscountAmount);
        blSetHeaderAmount("vat_amount", vatAmount);
        blSetHeaderAmount("withholding_amount", withholdingAmount);
        blSetHeaderAmount("grand_total_amount", grandTotalAmount);
        blSetHeaderAmount("base_grand_total_amount", grandTotalAmount);
    }

    function blEqualizeSalesPanels() {

        var allowedTitles = [
            "Customer",
            "Document",
            "Address",
            "Currency",
            "Remarks",
            "Invoice Summary"
        ];

        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 / 30) * 30;

            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 blRunAll() {
        blMakeLineNoReadonly();
        blRecalculateInvoicePreview();
        blEqualizeSalesPanels();

        setTimeout(blMakeLineNoReadonly, 300);
        setTimeout(blRecalculateInvoicePreview, 300);
        setTimeout(blEqualizeSalesPanels, 300);

        setTimeout(blMakeLineNoReadonly, 900);
        setTimeout(blRecalculateInvoicePreview, 900);
        setTimeout(blEqualizeSalesPanels, 900);
    }

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

    $(document).on("click", ".rnr-button, .btn, a", function () {
        setTimeout(blRunAll, 300);
        setTimeout(blRunAll, 900);
    });

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

    setTimeout(blRunAll, 300);
    setTimeout(blRunAll, 900);
    setTimeout(blRunAll, 1500);

})();
});


Runner.pages.PageSettings.addPageEvent( 
	"sales", 
	"edit", 
	"afterPageReady", 
	function(pageObj, proxy, pageid, inlineRow, inlineObject, row ) {
		/* ============================================================
   BuildLedger Sales Edit Page
   - Equalize section layout
   - Add spacing between section boxes
   - Make line number readonly if visible
   ============================================================ */

(function () {

    function blMakeLineNoReadonly() {
        $("input[name*='line_no']").each(function () {
            $(this)
                .prop("readonly", true)
                .attr("tabindex", "-1")
                .css({
                    "background-color": "#f7f7f7",
                    "pointer-events": "none"
                });
        });
    }

    function blEqualizeSalesPanels() {

        var allowedTitles = [
            "Customer",
            "Document",
            "Address",
            "Currency",
            "Remarks",
            "Invoice Summary"
        ];

        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 / 30) * 30;

            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() {
        blMakeLineNoReadonly();
        blEqualizeSalesPanels();

        setTimeout(blMakeLineNoReadonly, 300);
        setTimeout(blEqualizeSalesPanels, 300);

        setTimeout(blMakeLineNoReadonly, 900);
        setTimeout(blEqualizeSalesPanels, 900);
    }

    $(document).on("click", ".rnr-button, .btn, a", function () {
        setTimeout(blRunLayoutFix, 300);
        setTimeout(blRunLayoutFix, 900);
    });

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

    setTimeout(blRunLayoutFix, 300);
    setTimeout(blRunLayoutFix, 900);
    setTimeout(blRunLayoutFix, 1500);

})();
});


Runner.pages.PageSettings.addPageEvent( 
	"sales", 
	"view", 
	"afterPageReady", 
	function(pageObj, proxy, pageid, inlineRow, inlineObject, row ) {
		/* ============================================================
   BuildLedger Sales Edit Page
   - Equalize section layout
   ============================================================ */

(function () {

    function blEqualizeSalesPanels() {

        var allowedTitles = [
            "Customer",
            "Document",
            "Address",
            "Currency",
            "Remarks",
            "Invoice Summary"
        ];

        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() {
        blEqualizeSalesPanels();

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

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

    setTimeout(blRunLayoutFix, 300);

})();
});







