﻿// FastDue Form types
var FastDueForms = { "Invoice": 0, "Pastdue": 1, "Expense": 2, "Receipt": 3 };

// Class FastDueSubtotal
var FastDueSubtotal = Class.create();
FastDueSubtotal.prototype =
{
    initialize: function(encryptedId, name, total, interest, tax, endTotal, visible, lineItems) {
        this.encryptedId = encryptedId;
        this.name = name;
        this.total = total;
        this.interest = interest;
        this.tax = tax;
        this.endTotal = endTotal;
        this.visible = visible;
        this.lineItems = lineItems;
    }
};

// Class FastDueLineItem
var FastDueLineItem = Class.create();
FastDueLineItem.prototype =
{
    initialize: function(encryptedId, date, unit, unitCustom, quantity, description, unitPrice, total, interestRate, taxRate, interest, tax, interestDate, endTotal) {
        this.encryptedId = encryptedId;
        this.date = date;
        this.quantity = quantity;
        this.description = description;
        this.unitPrice = unitPrice;
        this.unit = unit;
        this.unitCustom = unitCustom;
        this.total = total;
        this.interestRate = interestRate;
        this.taxRate = taxRate;
        this.interest = interest;
        this.tax = tax;
        this.interestDate = interestDate;
        this.endTotal = endTotal;
    }
};

// Class FastDueUnit
var FastDueUnit = Class.create();
FastDueUnit.prototype =
{
    initialize: function(encryptedId, name) {
        this.encryptedId = encryptedId;
        this.name = name;
    }
};

// Form Units collection global vriable
var formUnits = null;

// Auto Complete Description List
var autoCompDescs = new Array();

// Auto Complete Description History List from Premium User
var autoCompDescsHistory = null;

// Object PastDueLineItemUtil
var PastDueLineItemUtil = new Object();
PastDueLineItemUtil.swapLineItems = function(arrLineItems, index1, index2) {
    var temp = arrLineItems[index1];
    arrLineItems[index1] = arrLineItems[index2];
    arrLineItems[index2] = temp;

    return arrLineItems;
}

// Object PastDueSubtotalUtil
var PastDueSubtotalUtil = new Object();
PastDueSubtotalUtil.removeIfEmpty = function(subtotals, subtotalId) {
    if (subtotals[subtotalId].lineItems.size() == 0) {
        subtotals[subtotalId] = null;
        subtotals = financeMaster.subtotals.compact();
    }
    return subtotals;
}

// Class Layout
var FormLayout = new Object;
FormLayout.draw = function(layer) {
    var newSubtotal = FormLayout.draw.arguments[1];
    var subtotalId = FormLayout.draw.arguments[2];
    var lineItemId = FormLayout.draw.arguments[3];
    var hasLineInterestRate = false;
    var hasLineTaxRate = false;
    var i, j, k, ctrlIndex, tableWidth, columnSpan;
    var displayHidden;

    i = 0; // Subtotal counter
    if (financeMaster.subtotals != null) {
        financeMaster.subtotals.each(function(subtotal) {
            j = 0; // LineItem counter in a subtotal
            subtotal.lineItems.each(function(lineItem) {
                if (!hasLineInterestRate && financeMaster.subtotals[i].lineItems[j].interestRate > 0) { hasLineInterestRate = true; }
                if (!hasLineTaxRate && financeMaster.subtotals[i].lineItems[j].taxRate > 0) { hasLineTaxRate = true; }
                j++;
            });
            i++;
        });
    }

    var widthDate, widthUnit, widthQty, widthDesc, widthUnitPrice, widthTotal, widthTax, widthInt, widthEndTotal;
    var widthDescControl;

    if (financeMaster.isSimple) {
        tableWidth = 57;
        columnSpan = 6;
        widthDate = 95; widthQty = 45; widthDesc = 413; widthUnitPrice = 121; widthTotal = 115;
        widthDescControl = 32.2;
    }
    else {
        if (hasLineTaxRate && hasLineInterestRate) {
            tableWidth = 57;
            columnSpan = 10;
            widthDate = 93; widthUnit = 60; widthQty = 43; widthDesc = 91; widthUnitPrice = 117; widthTotal = 90; widthTax = 85; widthInt = 85; widthEndTotal = 90;
            widthDescControl = 6.8;
        }
        else if (hasLineTaxRate || hasLineInterestRate) {
            tableWidth = 57;
            columnSpan = 9;
            widthDate = 93; widthUnit = 60; widthQty = 43; widthDesc = 180; widthUnitPrice = 117; widthTotal = 90; widthInt = 85; widthTax = 85; widthEndTotal = 90;
            widthDescControl = 14.0;
        }
        else {
            tableWidth = 57;
            columnSpan = 7;
            widthDate = 93; widthUnit = 60; widthQty = 43; widthDesc = 338; widthUnitPrice = 117; widthTotal = 115;
            widthDescControl = 26.0;
        }
    }
    var innerHTML = new Array();
    if (financeMaster.isSimple) {
        innerHTML.push("<table cellpadding='0' cellspacing='0' border='0' id='tableBillingActivity' style='width:" + tableWidth + "em; border-style: none; table-layout:fixed;'>");
    }
    else {
        innerHTML.push("<table cellpadding='0' cellspacing='0' border='0' id='tableBillingActivity' style='width:" + tableWidth + "em; border-style: none; table-layout:fixed; margin-top:50px;'>");
    }

    innerHTML.push("<tr style='height: 26px; color:#ffffff;'>");

    innerHTML.push("<th style='width:8px; background-color:#EE8431;'><img src='images/spacer.gif' style='width:10px; height:1px; border: none;' alt=''></th>");
    if (fastdueForm == FastDueForms.Invoice || fastdueForm == FastDueForms.Receipt) {
        displayHidden = "display: none;";
        innerHTML.push("<th class='left padright' style='width:" + widthDate + "px; background-color:#EE8431;'>Date</th>");
    }
    else {
        displayHidden = "";
        innerHTML.push("<th class='left padright' style='width:" + widthDate + "px; background-color:#EE8431;'>Due date</th>");
    }
    if (!financeMaster.isSimple) { innerHTML.push("<th class='left padleft padright' style='width:" + widthUnit + "px; background-color:#EE8431;'>Unit</th>"); }
    innerHTML.push("<th class='left padleft padright' style='width:" + widthQty + "px; background-color:#EE8431;'>Qty</th>");
    innerHTML.push("<th class='left padleft padright' style='width:" + widthDesc + "px; background-color:#EE8431;'>Description</th>");
    innerHTML.push("<th class='right padleft' style='width:" + widthUnitPrice + "px; background-color:#EE8431;'><div style='margin-right:2.3em;'>Unit Price</div></th>");
    innerHTML.push("<th class='right padleft padright' style='width:" + widthTotal + "px; background-color:#EE8431;'>Total</th>");

    if (hasLineInterestRate && !financeMaster.isSimple) { innerHTML.push("<th class='right padright' style='width:" + widthInt + "px; background-color:#EE8431;'>Interest</th>"); }
    if (hasLineTaxRate && !financeMaster.isSimple) { innerHTML.push("<th class='right padright' style='width:" + widthTax + "px; background-color:#EE8431;'>Tax</th>"); }
    if ((hasLineInterestRate || hasLineTaxRate) && !financeMaster.isSimple) { innerHTML.push("<th class='right padright' style='width:" + widthEndTotal + "px; background-color:#EE8431;'>End Total</th>"); }

    if (financeMaster.isSimple) {
        innerHTML.push("<th style='font-weight: normal; width:58px; background-color:#EE8431;'>&nbsp;</th>");
    }
    else {
        innerHTML.push("<th style='width:98px; vertical-align:top;'><div style='position:relative;'><img src='images/adv_form_vert_labels.gif' style='top:-42px; left:0px; right0px; position:absolute; border-style: none; width:98px; height:70px;'></div></th>");
    }
    innerHTML.push("</tr>");

    innerHTML.push("<tr>");
    innerHTML.push("<td colspan='" + (columnSpan + 1) + "'><img src='images/spacer.gif' style='width:1px; height:7px; border-style: none;' alt=''></td>");
    innerHTML.push("</tr>");

    i = j = k = 0;

    if (financeMaster.subtotals != null) {
        financeMaster.subtotals.each(function(subtotal) {
            k += j;
            j = 0;
            subtotal.lineItems.each(function(lineItem) {
                ctrlIndex = "_" + i + "_" + j;

                if (financeMaster.isSimple) {
                    lineSeperator = ((i == financeMaster.subtotals.size() - 1) && (j == subtotal.lineItems.size() - 1)) ? "" : " style='border-bottom: solid 2px #E4EFEF;'";
                }
                else {
                    lineSeperator = (j < subtotal.lineItems.size() - 1) ? " style='border-bottom: solid 2px #E4EFEF;'" : "";
                }

                innerHTML.push("<tr onmouseover=\"this.style.backgroundColor= '#f5f5f5';\" onmouseout=\"this.style.backgroundColor= '#ffffff';\" style='height: 37px;'>");
                // Spacer
                innerHTML.push("<td><img src='images/spacer.gif' width='1' height='1'></td>");
                // Due Date
                innerHTML.push("<td id='colDueDate" + ctrlIndex + "' class='padright'><input id='txtDueDate" + ctrlIndex + "' type='text' autocomplete='off' style='text-align:left; width:7.0em' maxLength='10' class='formFieldGridCal'/></td>");
                // Unit
                if (!financeMaster.isSimple) {
                    innerHTML.push("<td class='padleft padright'><select id='lstUnit" + ctrlIndex + "' class='formFieldGridSelect' style='width: 5em; height: 2em;'><option>Loading...</option></select>");
                    innerHTML.push("<input id='txtUnitCustom" + ctrlIndex + "' type='text' autocomplete='off' style='width:4.5em; display:none;' maxlength='15' class='formFieldGrid'/></td>");
                }
                // Quantity
                innerHTML.push("<td class='padleft padright'><input id='txtQuantity" + ctrlIndex + "' type='text' style='text-align:right; width: 2.8em' value='1' autocomplete='off' maxlength='9' class='formFieldGrid'/></td>");
                // Description
                innerHTML.push("<td class='padleft padright'><input id='txtDescription" + ctrlIndex + "' name='txtDescription" + ctrlIndex + "' type='text' class='formFieldGrid' value='' autocomplete='off' maxlength='200' style='width:" + widthDescControl + "em'/><div class='autocompleteDesc' id='descList" + ctrlIndex + "' style='display:none'></div></td>");
                // Unit Price
                innerHTML.push("<td class='padleft padright'><span id='spanUnitPriceCS" + ctrlIndex + "' style='margin-right:2px; font-size:12px;'>$</span><input id='txtUnitPrice" + ctrlIndex + "' type='text' style='text-align: right; width: 5.8em;' maxlength='12' autocomplete='off' class='formFieldGrid' size='5'/>&nbsp;</td>");
                // Total
                innerHTML.push("<td class='padleft padright'" + lineSeperator + "><span id='spanTotalCS" + ctrlIndex + "' style='float:left;'>$</span><span id='divTotal" + ctrlIndex + "' style='float: right;'></span></td>");
                // Interest
                if (hasLineInterestRate && !financeMaster.isSimple) {
                    innerHTML.push("<td class='padleft padright'" + lineSeperator + " nowrap><div id='spanInterestCS" + ctrlIndex + "' style='float:left; display:inline'>$</div><div id='divInterest" + ctrlIndex + "' style='display:inline; float: right;'></div></td>");
                }
                // Tax
                if (hasLineTaxRate && !financeMaster.isSimple) {
                    innerHTML.push("<td class='padleft padright'" + lineSeperator + "><div id='spanTaxCS" + ctrlIndex + "' style='float:left; display:inline'>$</div><div id='divTax" + ctrlIndex + "' style='display:inline; float: right;'></div></td>");
                }
                // End Total
                if ((hasLineInterestRate || hasLineTaxRate) && !financeMaster.isSimple) {
                    innerHTML.push("<td class='padleft padright'" + lineSeperator + "><div id='spanEndTotalCS" + ctrlIndex + "' style='float:left; display:inline'>$</div><div id='divEndTotal" + ctrlIndex + "' style='display:inline; float: right;'></div></td>");
                }
                if (financeMaster.isSimple) {
                    // Remove
                    innerHTML.push("<td" + lineSeperator + "><a href='javascript:;' onclick=\"FormLayout.removeLine('divFormGrid'," + i + "," + j + ");\" style='float:right;'><img src='images/bttnRmvLine.gif' style='width:23px; height:22px; border-style:none;' alt='' /></a></td>");
                }
                else {
                    // Advanced Options Popups
                    // Tax and Interest
                    innerHTML.push("<td>");
                    innerHTML.push("<div class='bluBgBox'>");
                    innerHTML.push("<img src='images/advFormUnselBluBox.gif' class='bluBgBox'>");
                    innerHTML.push("<a id='lnkAdvancedOptions" + ctrlIndex + "' href='javascript:;'><img id='imgAdvancedOptions" + ctrlIndex + "' src='images/advFormSmallPctBlu.gif' class='pctButtonSm' style='border: none'/></a>");
                    innerHTML.push("<a href='javascript:;'><img src='images/advFormSmallUpBlu.gif' class='upButtonSm' onclick=\"FormLayout.moveLineUp('divFormGrid', " + i + "," + j + ");\" style='border: none'/></a>");
                    innerHTML.push("<a href='javascript:;'><img src='images/advFormSmallDownBlu.gif' class='downButtonSm' onclick=\"FormLayout.moveLineDown('divFormGrid', " + i + "," + j + ");\" style='border: none'/></a>");
                    innerHTML.push("<a id='lnkInsertOptions" + ctrlIndex + "' href='javascript:;'><img id='imgInsertOptions" + ctrlIndex + "' src='images/advFormSmallPlusBlu.gif' class='plusButtonSm' style='border: none'></a>");
                    innerHTML.push("<a href='javascript:;'><img src='images/advFormSmallXBlu.gif' class='exButtonSm' onclick=\"FormLayout.removeLine('divFormGrid'," + i + "," + j + ");\" style='border: none'></a>");
                    innerHTML.push("</div>");

                    innerHTML.push("<div style='position:relative; z-index:3'><div style='position:absolute; left:-125px; top:-9px; width:18em; border:3px solid #DE6E32; background-color:#F9EFE1; padding:10px; display:none; z-index:2; font-size: 1.1em' id='divAdvancedOptions" + ctrlIndex + "'>");
                    innerHTML.push("<table width='100%' border='0' cellspacing='0' cellpadding='0'>");
                    innerHTML.push("<tr>");
                    innerHTML.push("<td width='100%' colspan='2' style='padding-bottom:15px;'><strong>Tax and Interest for this line item</strong></td>");
                    innerHTML.push("</tr>");
                    innerHTML.push("<tr>");
                    innerHTML.push("<td width='50%'>Interest Rate</td>");
                    innerHTML.push("<td width='50%'><input type='text' id='txtInterestRate" + ctrlIndex + "' autocomplete='off' style='width:50px; text-align:right;' value='' maxlength='5' class='formFieldGrid'/> %</td>");
                    innerHTML.push("</tr>");
                    innerHTML.push("<tr>");
                    innerHTML.push("<td>Tax Rate </td>");
                    innerHTML.push("<td><input type='text' id='txtTaxRate" + ctrlIndex + "' autocomplete='off' style='width:50px; text-align:right;' value='' maxlength='5' class='formFieldGrid'/> %</td>");
                    innerHTML.push("</tr>");
                    innerHTML.push("<tr><td colspan='2'>&nbsp;</td></tr>");
                    innerHTML.push("<tr><td colspan='2' style='padding-bottom:10px;'>Calculate Interest From</td></tr>");
                    innerHTML.push("<tr>");
                    innerHTML.push("<td colspan='2'>");
                    innerHTML.push("<label><input name='rbInterestDate" + ctrlIndex + "' id='rbInterestDate" + ctrlIndex + "_1' type='radio' checked='checked' onclick=\"$('divDueDateAdvance" + ctrlIndex + "').hide();\" />Due Date</label><br />");
                    innerHTML.push("<label><input name='rbInterestDate" + ctrlIndex + "' id='rbInterestDate" + ctrlIndex + "_2' type='radio' onclick=\"$('divDueDateAdvance" + ctrlIndex + "').show();\" />Other Date</label>");
                    innerHTML.push("<div id='divDueDateAdvance" + ctrlIndex + "' style='display: none;'>");
                    innerHTML.push("<input id='txtInterestDate" + ctrlIndex + "' type='text' autocomplete='off' style='width: 7.5em; text-align:left; font-size:0.9em' value='' class='formFieldGridCal'/></div>");
                    innerHTML.push("</td></tr>");
                    innerHTML.push("<tr><td colspan='2' align='right'><img src='images/okButtonPopup.jpg' id='btnAdvancedOptions" + ctrlIndex + "' style='width:54px; height:34px; border: none;' alt=''></td></tr>");
                    innerHTML.push("</table></div></div>");
                    // Insert Options
                    innerHTML.push("<div style='position:relative; z-index:2'><div style='position:absolute; top: -9px; left:-100px; width: 200px; padding: 10px; border:3px solid #DE6E32; background-color:#F9EFE1; display:none; text-align:left; z-index: 2' id='divInsertOptions" + ctrlIndex + "'>");
                    innerHTML.push("<div style='padding-bottom:10px;'><strong>Insert Row</strong></div>");
                    innerHTML.push("- <a href='javascript:;' onclick=\"FormLayout.insertLine('divFormGrid'," + i + "," + j + ");\" style='line-height: 22px;'>Insert Line Above</a><br/>");
                    innerHTML.push("- <a href='javascript:;' onclick=\"FormLayout.insertLine('divFormGrid'," + i + "," + (j + 1) + ");\" style='line-height: 20px;'>Insert Line Below</a><br/>");
                    innerHTML.push("- <a href='javascript:;' onclick=\"FormLayout.makeSubtotal('divFormGrid'," + i + "," + j + ",'');\" style='line-height: 20px;'>Make Subtotal Below</a><br/><br/>");
                    innerHTML.push("<img src='images/okButtonPopup.jpg' id='btnInsertOptions" + ctrlIndex + "' style='width:54px; height:34px; border: none; float:right' alt=''>");
                    innerHTML.push("</div></div></td>");
                }

                innerHTML.push("</tr>");
                j++;
            });

            // Subtotal - Subtotal Zone //
            // if (financeMaster.subtotals.size() > 1 && subtotal.visible)
            if (subtotal.visible && !financeMaster.isSimple) {
                ctrlIndex = "_" + i;
                innerHTML.push("<tr style='height:37px; background-color: #E4EFEF'>");
                // Left Border
                innerHTML.push("<td><img src='images/spacer.gif' width='1' height='1'></td>");
                // Subtotal Static Label
                innerHTML.push("<td colspan='3' style='font-weight:bold;'>Subtotal:</td>");
                // Subtotal TextBox
                innerHTML.push("<td class='padleft padright'><input id='txtSubtotal" + ctrlIndex + "' autocomplete='off' name='txtSubtotal" + ctrlIndex + "' type='text' class='formFieldGrid' value='' maxlength='90' style='font-weight:bold; width:" + widthDescControl + "em'/></td>");
                // Unit Price
                innerHTML.push("<td>&nbsp;</td>");
                // Total
                innerHTML.push("<td style='text-align:right;' class='padleft padright'><div id='spanTotalCS" + ctrlIndex + "' style='float:left; display:inline'>$</div><div id='divTotal" + ctrlIndex + "' style='display:inline;'></div></td>");
                // Interest
                if (hasLineInterestRate) { innerHTML.push("<td style='text-align:right;' class='padleft padright'><div id='spanInterestCS" + ctrlIndex + "' style='float:left; display:inline'>$</div><div id='divInterest" + ctrlIndex + "'></div></td>"); }
                // Tax
                if (hasLineTaxRate) { innerHTML.push("<td class='padleft padright' style='text-align:right;'><div id='spanTaxCS" + ctrlIndex + "' style='float:left; display:inline'>$</div><div id='divTax" + ctrlIndex + "'></div></td>"); }
                // End Total
                if (hasLineInterestRate || hasLineTaxRate) { innerHTML.push("<td class='padleft padright' style='text-align:right;'><div id='spanEndTotalCS" + ctrlIndex + "' style='float:left; display:inline'>$</div><div id='divEndTotal" + ctrlIndex + "'></div></td>"); }
                // Advanded Options and Remove
                innerHTML.push("<td><a href='javascript:;' onclick=\"FormLayout.removeSubtotal('divFormGrid'," + i + ");\"><img src='images/advFormSmallXBlu.gif' style='width:13px; height:14px; border:none; float:right; margin-right: 6px;' /></a></td>");
                // Insert Options
                innerHTML.push("</tr>");

                k++;
            }
            //innerHTML.push("<tr><td colspan='9'><a href='javascript:;' onclick=\"FormLayout.addLine('divFormGrid'," + i + ");\">Add new line</a></td></tr>");
            i++;
        });
    }

    innerHTML.push("<tr>");
    innerHTML.push("<td colspan='" + (columnSpan + 1) + "' style='padding-bottom:0.25em;'><img src='images/spacer.gif' style='width:912px; height:1px; border-bottom:solid 2px #E4EFEF;' alt=''></td>");
    innerHTML.push("</tr>");

    innerHTML.push("<tr>");
    innerHTML.push("<td style='width: 10px'><img src='images/spacer.gif' style='width:1px; height:1px; border: none;' alt=''></td>");
    innerHTML.push("<td class='blue_em' colspan='" + columnSpan + "' style='width:892px;'><img src='images/blueArrow.gif' class='arrow'><a href='javascript:;' style='font-size: 0.85em' onclick=\"FormLayout.addLineAtEnd('divFormGrid');\" class='blue_em'>Add a line</a>");
    innerHTML.push("<img src='images/spacer.gif' style='height:1px; width: 20px' alt=''>");
    if (financeMaster.isSimple) {
        innerHTML.push("<img src='images/blueArrow.gif' alt='' class='arrow'><a href='javascript:;' style='font-size: 0.85em' onclick=\"financeMaster.isSimple = false; FormLayout.CDUB('" + layer + "');\">Enable advanced features (unit fields, subtotals, tax and interest per line, move lines)</a>");
    }
    else {
        innerHTML.push("<img src='images/blueArrow.gif' alt='' class='arrow'><a href='javascript:;' style='font-size: 0.85em' onclick=\"financeMaster.isSimple = true; FormLayout.CDUB('" + layer + "');\">Disable advanced features</a>");
    }
    innerHTML.push("</td>");
    innerHTML.push("</tr>");

    if (financeMaster.isSimple) {        
        var grandTotalLabel = fastdueForm == FastDueForms.Receipt ? "TOTAL RECEIVED:" : "TOTAL DUE:";
        var amountImageName = fastdueForm == FastDueForms.Receipt ? "AmountReceived.gif" : "PayThisAmount.jpg";
        /////// Subtotal ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        innerHTML.push("<tr style='height: 2.5em;'>");
        innerHTML.push("<td colspan='3'><img src='images/spacer.gif' style='width:1px; height:1px;' alt=''></td>");
        innerHTML.push("<td colspan='2' class='right padright3'><span class='gray_bold' style='padding-right: 1.0em; padding-top: 0.45em'>Subtotal:</span></td>");
        innerHTML.push("<td class='padleft padright'><div id='spanSubtotalCS' style='float:left;'>$</div><div id='divSubtotal' style='float:right;'>0.00</div></td>");
        innerHTML.push("<td><img src='images/spacer.gif' style='width:1px; height:1px;' alt=''></td>");
        innerHTML.push("</tr>");
        /////// Divider  ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        innerHTML.push("<tr style='height: 1px;'>");
        innerHTML.push("<td colspan='3'><img src='images/spacer.gif' style='width:1px; height:1px;' alt=''></td>");
        innerHTML.push("<td colspan='2' class='right'><div style='position:relative; width:11.3em; float:right; border-bottom: solid 2px #E4EFEF;'><img src='images/spacer.gif' style='width:1px; height:0px; border-style:none;' alt=''></div></td>");
        innerHTML.push("<td><div style='width:100%; border-bottom: solid 2px #E4EFEF;'><img src='images/spacer.gif' style='width:1px; height:0px; border-style:none;' alt=''></div></td>");
        innerHTML.push("<td><img src='images/spacer.gif' style='width:1px; height:1px; border-style:none;' alt=''></td>");
        innerHTML.push("</tr>");
        /////// Interest ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        innerHTML.push("<tr style='height: 2.5em;" + displayHidden + "'>");
        innerHTML.push("<td colspan='3'><img src='images/spacer.gif' style='width:1px; height:1px;' alt=''></td>");
        innerHTML.push("<td colspan='2' class='right padright3'><div style='position:relative; width:11.0em; float:right; text-align:left;'><span style='float:left;'><input id='txtInterestRate' autocomplete='off' type='text' style='width:3em; font-size: 0.9em' maxlength='5' class='formFieldGrid'>%</span><span class='gray_bold' style='padding-right: 1.0em; padding-top: 0.2em; float:right;'>Interest:</span></div></td>");
        innerHTML.push("<td class='padleft padright'><div id='spanInterestCS' style='float:left;'>$</div><div id='divInterest' style='float:right;'>0.00</div></td>");
        innerHTML.push("<td><img src='images/spacer.gif' style='width:1px; height:1px;' alt=''></td>");
        innerHTML.push("</tr>");
        /////// Divider  ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        innerHTML.push("<tr style='height: 1px;" + displayHidden + "'>");
        innerHTML.push("<td colspan='3'><img src='images/spacer.gif' style='width:1px; height:1px;' alt=''></td>");
        innerHTML.push("<td colspan='2' class='right'><div style='position:relative; width:11.3em; float:right; border-bottom: solid 2px #E4EFEF;'><img src='images/spacer.gif' style='width:1px; height:0px; border-style:none;' alt=''></div></td>");
        innerHTML.push("<td><div style='width:100%; border-bottom: solid 2px #E4EFEF;'><img src='images/spacer.gif' style='width:1px; height:0px; border-style:none;' alt=''></div></td>");
        innerHTML.push("<td><img src='images/spacer.gif' style='width:1px; height:1px; border-style:none;' alt=''></td>");
        innerHTML.push("</tr>");
        /////// Tax ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        innerHTML.push("<tr style='height: 2.5em;'>");
        innerHTML.push("<td colspan='3'><img src='images/spacer.gif' style='width:1px; height:1px;' alt=''></td>");
        innerHTML.push("<td colspan='2' class='right padright3'><div style='position:relative; width:11.0em; float:right; text-align:left;'><span style='float:left;'><input id='txtTaxRate' type='text' autocomplete='off' style='width:3em; font-size: 0.9em;' maxlength='5' class='formFieldGrid'>%</span><span class='gray_bold' style='padding-right: 1.0em; padding-top: 0.2em; float:right;'>Tax:</span></div></td>");
        innerHTML.push("<td class='padleft padright'><div id='spanTaxCS' style='float:left;'>$</div><div id='divTax' style='float:right;'>0.00</div></td>");
        innerHTML.push("<td><img src='images/spacer.gif' style='width:1px; height:1px;' alt=''></td>");
        innerHTML.push("</tr>");
        /////// Total //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        innerHTML.push("<tr>");
        innerHTML.push("<td colspan='3'><img src='images/spacer.gif' style='width:1px; height:1px;' alt=''></td>");
        innerHTML.push("<td colspan='2' style='color: #000000; font-weight: bold;' class='right;'><div style='position:relative; background-color: #E4EFEF; height:2.4em; width:10.3em; float:right; text-align:right; padding-right:1.0em; padding-top:1.1em;'>" + grandTotalLabel + "</div><div style='position: relative;'><img src='images/" + amountImageName + "' style='position:absolute; top:5.0em; left:34.75em; z-index: 10; border-style:none;' alt=''/></div></td>");
        innerHTML.push("<td class='padleft padright' style='background-color: #E4EFEF; font-weight: bold; color: #000000;'><div id='spanTotalCS' style='float:left;' class='scrunch'>$</div><div id='divTotal' style='float:right;' class='scrunch'>0.00</div></td>");
        innerHTML.push("<td><img src='images/spacer.gif' style='width:1px; height:1px;' alt=''></td>");
        innerHTML.push("</tr>");
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    }
    innerHTML.push("</table>");

    if (financeMaster.isSimple) { FormLayout.drawAdvancedFooter(false); } else { FormLayout.drawAdvancedFooter(true); }
    $(layer).innerHTML = innerHTML.join("");
    if (!financeMaster.isSimple) { FormLayout.fillUnitsToGrid(); }
}

FormLayout.drawAdvancedFooter = function(visible) {
    var grandTotalLabel = fastdueForm == FastDueForms.Receipt ? "TOTAL RECEIVED:" : "TOTAL DUE:";
    var amountImageName = fastdueForm == FastDueForms.Receipt ? "AmountReceived.gif" : "PayThisAmount.jpg";
    if (!visible) { $('divFormAdvancedFooter').innerHTML = ''; return; }
    if (!$('divFormAdvancedFooter').innerHTML.blank()) { return; }
    displayHidden = fastdueForm == FastDueForms.Invoice || fastdueForm == FastDueForms.Receipt ? "display: none;" : "";

    var innerHTML = new Array();
    innerHTML.push("<table cellpadding='0' cellspacing='0' border='0' style='width:900px; font-size: smaller; table-layout:fixed;'>");
    innerHTML.push("<tr><td style='width: 640px; background-color: white'>&nbsp;</td>");
    innerHTML.push("<td style='width: 260px;'>");
    innerHTML.push("<table cellpadding='0' cellspacing='0' border='0' style='width:260px;'>");
    /////// Subtotal ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    innerHTML.push("<tr style='height: 2.8em;'>");
    innerHTML.push("<td class='right padright3' style='border-bottom: solid 2px #E4EFEF; width:145px;'><div class='gray_bold' style='padding-right: 1.0em; padding-top: 0.25em'>Subtotal:</div></td>");
    innerHTML.push("<td class='padleft padright' style='border-bottom: solid 2px #E4EFEF; width:115px;'><div id='spanSubtotalCS' style='float:left;'>$</div><div id='divSubtotal' style='float:right;'>0.00</div></td>");
    innerHTML.push("</tr>");
    /////// Interest ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    innerHTML.push("<tr style='height: 2.8em;" + displayHidden + "'>");
    innerHTML.push("<td class='right padright3' style='border-bottom: solid 2px #E4EFEF;'><span style='float: left'><input id='txtInterestRate' type='text' autocomplete='off' style='width:3em; font-size: 0.9em' maxlength='5' class='formFieldGrid'>%</span><div class='gray_bold' style='padding-right: 1.0em; padding-top: 0.2em'>Interest:</div></td>");
    innerHTML.push("<td class='padleft padright' style='border-bottom: solid 2px #E4EFEF;'><div id='spanInterestCS' style='float:left;'>$</div><div id='divInterest' style='float:right;'>0.00</div></td>");
    innerHTML.push("</tr>");
    /////// Tax ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    innerHTML.push("<tr style='height: 2.8em;'>");
    innerHTML.push("<td class='right padright3'><span style='float: left'><input id='txtTaxRate' type='text' autocomplete='off' style='width:3em; font-size: 0.9em;' maxlength='5' class='formFieldGrid'>%</span><div class='gray_bold' style='padding-right: 1.0em; padding-top: 0.2em'>Tax:</div></td>");
    innerHTML.push("<td class='padleft padright'><div id='spanTaxCS' style='float:left;'>$</div><div id='divTax' style='float:right;'>0.00</div></td>");
    innerHTML.push("</tr>");
    /////// Total //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    innerHTML.push("<tr style='height: 3.2em; background-color: #E4EFEF'>");
    innerHTML.push("<td style='color:#000000; font-weight: bold;' class='right padright3'><div style='position:relative; padding-top:0.1em; padding-right: 1.0em;'>" + grandTotalLabel + "</div><div style='position:relative;'><img src='images/" + amountImageName + "' style='position:absolute; top:2.0em; left:2.0em; z-index: 10;'></div></td>");
    innerHTML.push("<td class='padleft padright' style='font-weight: bold; color: #000000;'><div id='spanTotalCS' style='float:left;' class='scrunch'>$</div><div id='divTotal' style='float:right;' class='scrunch'>0.00</div></td>");
    innerHTML.push("</tr>");
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    innerHTML.push("</table>");
    innerHTML.push("</td></tr></table>");

    $('divFormAdvancedFooter').innerHTML = innerHTML.join("");
}

// Synchronous JSON-RPC to load units from Server (Server Method: Unit.GetAllUnits())
FormLayout.loadUnits = function() {
    var fdh = new FastDueHandler();
    formUnits = fdh.getAllUnits();
}

// Asynchronous JSON-RPC to load LineItem descriptions from Server
FormLayout.loadDistinctLineItemDescriptions = function() {
    var fdh = new FastDueHandler();
    fdh.getDistinctLineItemDescriptions(function(response) {
    autoCompDescsHistory = response.result;
        if (autoCompDescsHistory != null) FormLayout.updateAutoComplete();
    });
}

// Fill loaded Units into a single HTML <select> form element
FormLayout.fillUnits = function(element) {
    element.remove(0);
    var opt;
    for (var i = 0; i < formUnits.length; i++) {
        opt = document.createElement('option');
        opt.text = formUnits[i].name;
        opt.value = formUnits[i].encryptedId;
        opt.style.backgroundColor = '#FFFFFF';

        try { element.add(opt, null); }
        catch (ex) { element.add(opt); }
    }

    opt = document.createElement('option');
    opt.text = "-custom-";
    opt.value = 0;
    opt.style.backgroundColor = '#CCFFCC';
    try { element.add(opt, null); }
    catch (ex) { element.add(opt); }
}

// Fill loaded Units into the Grid
FormLayout.fillUnitsToGrid = function() {
    var i, j, ctrlIndex;

    i = 0;
    if (financeMaster.subtotals != null) {
        financeMaster.subtotals.each(function(subtotal) {
            j = 0;
            subtotal.lineItems.each(function(lineItem) {
                ctrlIndex = "_" + i + "_" + j;
                FormLayout.fillUnits($('lstUnit' + ctrlIndex));
                j++;
            });
            i++;
        });
    }
}

FormLayout.addLine = function(layer, subtotalId) {
    financeMaster.subtotals[subtotalId].lineItems.push(new FastDueLineItem(0, null, null, unitCustomDefault, 1, null, unitPriceDefault, 0, 0.0, 0.0, 0, 0, null, 0.0));
    FormLayout.CDUB(layer);
}

FormLayout.addLineAtEnd = function(layer) {
    if (financeMaster.subtotals != null && financeMaster.subtotals.size() == 0) { financeMaster.subtotals = null; }
    if (financeMaster.subtotals == null) {
        financeMaster.subtotals = new Array();
        financeMaster.subtotals.push(new FastDueSubtotal(0, "", 0.0, 0.0, 0.0, 0.0, false, new Array()));
    }
    FormLayout.addLine(layer, financeMaster.subtotals.size() - 1);
}

FormLayout.insertLine = function(layer, subtotalId, lineItemId) {
    financeMaster.subtotals[subtotalId].lineItems.insert(lineItemId, new FastDueLineItem(0, null, null, unitCustomDefault, 1, null, unitPriceDefault, 0, 0.0, 0.0, 0, 0, null, 0.0));
    FormLayout.CDUB(layer);
}

FormLayout.removeLine = function(layer, subtotalId, lineItemId) {
    financeMaster.subtotals[subtotalId].lineItems[lineItemId] = null;
    financeMaster.subtotals[subtotalId].lineItems = financeMaster.subtotals[subtotalId].lineItems.compact();

    financeMaster.subtotals = PastDueSubtotalUtil.removeIfEmpty(financeMaster.subtotals, subtotalId);
    if (financeMaster.subtotals.size() == 0) {
        financeMaster.subtotals = null;
    }
    FormLayout.CDUB(layer, true);
}

FormLayout.moveLineUp = function(layer, subtotalId, lineItemId) {
    if (financeMaster.subtotals.size() == 1 || ((financeMaster.subtotals[subtotalId].lineItems.size() > 1) && (lineItemId > 0))) {
        financeMaster.subtotals[subtotalId].lineItems = (lineItemId == 0)
			? PastDueLineItemUtil.swapLineItems(financeMaster.subtotals[subtotalId].lineItems, lineItemId, financeMaster.subtotals[subtotalId].lineItems.size() - 1)
			: PastDueLineItemUtil.swapLineItems(financeMaster.subtotals[subtotalId].lineItems, lineItemId, lineItemId - 1);
    }
    else if (financeMaster.subtotals.size() > 1) {
        subtotalIndex = (subtotalId == 0) ? financeMaster.subtotals.size() - 1 : subtotalId - 1;
        financeMaster.subtotals[subtotalIndex].lineItems.push(Object.clone(financeMaster.subtotals[subtotalId].lineItems[lineItemId]));
        financeMaster.subtotals[subtotalId].lineItems[lineItemId] = null;
        financeMaster.subtotals[subtotalId].lineItems = financeMaster.subtotals[subtotalId].lineItems.compact();
    }

    financeMaster.subtotals = PastDueSubtotalUtil.removeIfEmpty(financeMaster.subtotals, subtotalId);
    FormLayout.CDUB(layer);
}

FormLayout.moveLineDown = function(layer, subtotalId, lineItemId) {
    if (financeMaster.subtotals.size() == 1 || ((financeMaster.subtotals[subtotalId].lineItems.size() > 1) && (lineItemId < financeMaster.subtotals[subtotalId].lineItems.size() - 1))) {
        financeMaster.subtotals[subtotalId].lineItems = (lineItemId == financeMaster.subtotals[subtotalId].lineItems.size() - 1)
			? PastDueLineItemUtil.swapLineItems(financeMaster.subtotals[subtotalId].lineItems, lineItemId, 0)
			: PastDueLineItemUtil.swapLineItems(financeMaster.subtotals[subtotalId].lineItems, lineItemId, lineItemId + 1);
    }
    else if (financeMaster.subtotals.size() > 1) {
        subtotalIndex = (subtotalId == financeMaster.subtotals.size() - 1) ? 0 : subtotalIndex = subtotalId + 1;
        financeMaster.subtotals[subtotalIndex].lineItems.insert(0, Object.clone(financeMaster.subtotals[subtotalId].lineItems[lineItemId]));
        financeMaster.subtotals[subtotalId].lineItems[lineItemId] = null;
        financeMaster.subtotals[subtotalId].lineItems = financeMaster.subtotals[subtotalId].lineItems.compact();
    }

    financeMaster.subtotals = PastDueSubtotalUtil.removeIfEmpty(financeMaster.subtotals, subtotalId);
    FormLayout.CDUB(layer);
}

FormLayout.makeSubtotal = function(layer, subtotalId, lineItemId, name) {
    //if (name == null || name.blank()) { return; }

    newSubtotal = new FastDueSubtotal(0, name, 0.0, 0.0, 0.0, 0.0, true, new Array());
    for (i = 0; i <= lineItemId; i++) {
        newSubtotal.lineItems.push(Object.clone(financeMaster.subtotals[subtotalId].lineItems[i]));
        financeMaster.subtotals[subtotalId].lineItems[i] = null;
    }
    financeMaster.subtotals[subtotalId].lineItems = financeMaster.subtotals[subtotalId].lineItems.compact();
    financeMaster.subtotals = PastDueSubtotalUtil.removeIfEmpty(financeMaster.subtotals, subtotalId);
    financeMaster.subtotals.insert(subtotalId, newSubtotal);
    FormLayout.CDUB(layer);
}

FormLayout.removeSubtotal = function(layer, subtotalId) {
    var nextSubtotalId = subtotalId + 1;
    if (nextSubtotalId == financeMaster.subtotals.size()) {
        financeMaster.subtotals[subtotalId].visible = false;
    }
    else {
        var i = 0;
        financeMaster.subtotals[subtotalId].lineItems.each(function(lineItem) { financeMaster.subtotals[nextSubtotalId].lineItems.insert(i++, Object.clone(lineItem)); });
        financeMaster.subtotals[subtotalId] = null;
        financeMaster.subtotals = financeMaster.subtotals.compact();
    }
    FormLayout.CDUB(layer);
}

FormLayout.updateControls = function() {
    var i, j, ctrlIndex;

    i = 0;
    if (financeMaster.subtotals != null) {
        financeMaster.subtotals.each(function(subtotal) {
            j = 0;
            subtotal.lineItems.each(function(lineItem) {
                ctrlIndex = "_" + i + "_" + j;
                lineItem.date = FormLayout.validateDate(lineItem.date);
                $('txtDueDate' + ctrlIndex).value = (lineItem.date != null) ? lineItem.date : '';
                $('txtQuantity' + ctrlIndex).value = (lineItem.quantity != null) ? lineItem.quantity : '';
                $('txtDescription' + ctrlIndex).value = (lineItem.description != null) ? lineItem.description : '';
                $('txtUnitPrice' + ctrlIndex).value = (lineItem.unitPrice != null) ? FDUtil.formatCurrency(lineItem.unitPrice) : '';
                $('divTotal' + ctrlIndex).innerHTML = (lineItem.total != null) ? FDUtil.formatCurrency(lineItem.total) : '';

                $('spanUnitPriceCS' + ctrlIndex).innerHTML = crncySymbl;
                $('spanTotalCS' + ctrlIndex).innerHTML = crncySymbl;

                if (!financeMaster.isSimple) {
                    if (lineItem.unit != null && lineItem.unit.encryptedId != null) {
                        for (var k = 0; k < $('lstUnit' + ctrlIndex).options.length; k++) {
                            if ($('lstUnit' + ctrlIndex).options[k].value == lineItem.unit.encryptedId) {
                                $('lstUnit' + ctrlIndex).options[k].selected = true;
                                break;
                            }
                        }
                    }
                    $('txtUnitCustom' + ctrlIndex).value = (lineItem.unitCustom != null) ? lineItem.unitCustom : '';
                    $('txtInterestRate' + ctrlIndex).value = FDUtil.formatCurrency(lineItem.interestRate);
                    $('txtTaxRate' + ctrlIndex).value = FDUtil.formatCurrency(lineItem.taxRate);

                    lineItem.interestDate = FormLayout.validateDate(lineItem.interestDate);
                    $('txtInterestDate' + ctrlIndex).value = (lineItem.interestDate != null) ? lineItem.interestDate : '';

                    if ($('divInterest' + ctrlIndex) != null) { $('divInterest' + ctrlIndex).innerHTML = FDUtil.formatCurrency(lineItem.interest); $('spanInterestCS' + ctrlIndex).innerHTML = crncySymbl; }
                    if ($('divTax' + ctrlIndex) != null) { $('divTax' + ctrlIndex).innerHTML = FDUtil.formatCurrency(lineItem.tax); $('spanTaxCS' + ctrlIndex).innerHTML = crncySymbl; }
                    if ($('divEndTotal' + ctrlIndex) != null) { $('divEndTotal' + ctrlIndex).innerHTML = FDUtil.formatCurrency(lineItem.endTotal); $('spanEndTotalCS' + ctrlIndex).innerHTML = crncySymbl; }

                    // Iff lineItem.interestDate exists then raise radio button event with Interest Date option
                    if (lineItem.interestDate != null && !lineItem.interestDate.blank()) { $('rbInterestDate' + ctrlIndex + '_2').click(); }

                    // Iff unitCustom has some value or unit.encryptedId is 0 then hide Unit list box and show unitCutom textbox
                    if ((lineItem.unitCustom != null && !lineItem.unitCustom.blank()) || (lineItem.unit != null && lineItem.unit.encryptedId == 0)) { $('lstUnit' + ctrlIndex).hide(); $('txtUnitCustom' + ctrlIndex).show(); }
                }
                j++;
            });

            if (subtotal.visible && !financeMaster.isSimple) {
                ctrlIndex = "_" + i;
                $('txtSubtotal' + ctrlIndex).value = (subtotal.name != null) ? subtotal.name : '';
                $('divTotal' + ctrlIndex).innerHTML = FDUtil.formatCurrency(subtotal.total);
                if ($('divInterest' + ctrlIndex) != null) { $('divInterest' + ctrlIndex).innerHTML = FDUtil.formatCurrency(subtotal.interest); }
                if ($('divTax' + ctrlIndex) != null) { $('divTax' + ctrlIndex).innerHTML = FDUtil.formatCurrency(subtotal.tax); }
                if ($('divEndTotal' + ctrlIndex) != null) { $('divEndTotal' + ctrlIndex).innerHTML = FDUtil.formatCurrency(subtotal.endTotal); }
            }
            i++;
        });

        FormLayout.updateAutoComplete();
    }

    $('txtFormNumber').value = (financeMaster.formNumber != null) ? financeMaster.formNumber : '';
    financeMaster.formDate = FormLayout.validateDate(financeMaster.formDate);
    $('txtFormDate').value = (financeMaster.formDate != null) ? financeMaster.formDate : '';
    $('txtCustomerId').value = (financeMaster.customerId != null) ? financeMaster.customerId : '';
    $('txtComments').value = (financeMaster.comments != null) ? financeMaster.comments : '';

    $('txtFOB').value = (financeMaster.fOB != null) ? financeMaster.fOB : '';
    $('txtPurchaseOrder').value = (financeMaster.purchaseOrder != null) ? financeMaster.purchaseOrder : '';
    $('txtRepresentative').value = (financeMaster.representative != null) ? financeMaster.representative : '';
    $('txtProject').value = (financeMaster.project != null) ? financeMaster.project : '';
    financeMaster.shipDate = FormLayout.validateDate(financeMaster.shipDate);
    $('txtShipDate').value = (financeMaster.shipDate != null) ? financeMaster.shipDate : '';
    $('txtTerms').value = (financeMaster.terms != null) ? financeMaster.terms : '';

    $('txtTaxRate').value = FDUtil.formatCurrency(financeMaster.taxRate);
    $('txtInterestRate').value = FDUtil.formatCurrency(financeMaster.interestRate);
    $('divSubtotal').innerHTML = FDUtil.formatCurrency(financeMaster.subTotal);
    $('divInterest').innerHTML = FDUtil.formatCurrency(financeMaster.interest);
    $('divTax').innerHTML = FDUtil.formatCurrency(financeMaster.tax);
    $('divTotal').innerHTML = FDUtil.formatCurrency(financeMaster.total);

    $('spanSubtotalCS').innerHTML = crncySymbl;
    $('spanTaxCS').innerHTML = crncySymbl;
    $('spanInterestCS').innerHTML = crncySymbl;
    $('spanTotalCS').innerHTML = crncySymbl;
}

FormLayout.resetControls = function() {
    if (!confirm("The form data is going to be reset. Press OK if you're sure?")) {
        return false;
    }
    if (financeMaster.subtotals != null) {
        financeMaster.subtotals.each(function(subtotal) {
            subtotal.lineItems.each(function(lineItem) {
                lineItem.date = null;
                lineItem.quantity = 1;
                lineItem.description = null;
                lineItem.unitPrice = 0;
            });
        });
    }
    Calculator.calculate();
    FormLayout.updateControls();

    return true;
}

// Validate and Format date string from JSON returned by server
FormLayout.validateDate = function(val) {
    if (val != null && val.length > 10) {
        val = val.substring(0, 10);
        val = parseDate(val);
        return (val != null) ? formatDate(val, 'MM/dd/y') : null;
    }
    else {
        return val;
    }
}

FormLayout.CDUB = function(layer) // [C]alculate, [D]raw, [U]pdate, [B]ind Events and Tooltips
{
    var dontValidateDescription = FormLayout.CDUB.arguments[1];    
    // Load units if required
    if (!financeMaster.isSimple && formUnits == null) { FormLayout.loadUnits(); }
    // Load lineitem descriptions if required
    if (autoCompDescsHistory == null) { FormLayout.loadDistinctLineItemDescriptions(); }
    // Do Calculate, draw, updateControls, bindEvents
    Calculator.calculate();
    if (financeMaster.isSimple && !dontValidateDescription) FormLayout.validateDescription(); // Sync textbox value with lineItem.description if filled with auto complete
    FormLayout.draw(layer, FormLayout.CDUB.arguments[1], FormLayout.CDUB.arguments[2], FormLayout.CDUB.arguments[3]);
    FormLayout.updateControls();
    FormEvent.bindEvents();
    FormEvent.bindTooltips();
    if (financeMaster.isSimple) FormEvent.bindAutoComplete();

    //$('divJSON').innerHTML = (Object.toJSON(financeMaster));
}

FormLayout.calcAndUpdateControls = function(layer)
{
    Calculator.calculate();
    FormLayout.updateControls();
    // To update auto completes    
}

FormLayout.validateRequired = function() {
    var result = false;

    if (financeMaster.subtotals != null) {
        financeMaster.subtotals.each(function(subtotal) {
            subtotal.lineItems.each(function(lineItem) {
                if (lineItem.date != null || (lineItem.description != null && !lineItem.description.blank()) || lineItem.unitPrice > 0) {
                    result = true;
                }
            });
        });
    }

    return result;
}

FormLayout.validateDescription = function() {
    var i, j, ctrlIndex;
    i = 0;
    if (financeMaster.subtotals != null) {
        financeMaster.subtotals.each(function(subtotal) {
            j = 0;
            subtotal.lineItems.each(function(lineItem) {
                ctrlIndex = "_" + i + "_" + j;
                if ($('txtDescription' + ctrlIndex) != null && $F('txtDescription' + ctrlIndex) != lineItem.description)
                    lineItem.description = $F('txtDescription' + ctrlIndex);
                j++;
            });
            i++;
        });
    }
}

FormLayout.updateAutoComplete = function() {
    autoCompDescs.clear();

    if (autoCompDescsHistory != null) {
        autoCompDescsHistory.each(function(li) {
            autoCompDescs.push(li);
        });
    }

    if (financeMaster.subtotals != null) {
        financeMaster.subtotals.each(function(subtotal) {
            subtotal.lineItems.each(function(lineItem) {
                if (lineItem.description != null && !lineItem.description.blank()) {
                    if (autoCompDescs.indexOf(lineItem.description) == -1) {
                        autoCompDescs.push(lineItem.description);
                    }
                }
            });
        });
    }
}

// FormEvent Object
var FormEvent = new Object();

FormEvent.updateDescription = function(event, subtotalId, lineItemId) { var element = Event.element(event); financeMaster.subtotals[subtotalId].lineItems[lineItemId].description = element.value.strip(); FormLayout.validateDescription(); FormLayout.calcAndUpdateControls(); }
FormEvent.updateQuantity = function(event, subtotalId, lineItemId) { var element = Event.element(event); financeMaster.subtotals[subtotalId].lineItems[lineItemId].quantity = (parseFloat(element.value.parseQty()) > 999999.99) ? 999999.99 : parseFloat(element.value.parseQty()); FormLayout.calcAndUpdateControls(); }
FormEvent.updateUnit = function(event, subtotalId, lineItemId) { var element = Event.element(event); financeMaster.subtotals[subtotalId].lineItems[lineItemId].unit = new FastDueUnit(element.options[element.selectedIndex].value, element.options[element.selectedIndex].text); }
FormEvent.updateUnitCustom = function(event, subtotalId, lineItemId) { var element = Event.element(event); financeMaster.subtotals[subtotalId].lineItems[lineItemId].unitCustom = element.value; }
FormEvent.updateUnitPrice = function(event, subtotalId, lineItemId) { var element = Event.element(event); financeMaster.subtotals[subtotalId].lineItems[lineItemId].unitPrice = (element.value.parseFloat() > 9999999.99) ? 9999999.99 : element.value.parseFloat(); FormLayout.calcAndUpdateControls(); }
FormEvent.updateInterestDate = function(event, subtotalId, lineItemId) { var element = Event.element(event); financeMaster.subtotals[subtotalId].lineItems[lineItemId].interestDate = (parseDate(element.value.strip()) != null) ? formatDate(parseDate(element.value.strip()), 'MM/dd/y') : null; FormLayout.calcAndUpdateControls(); }
FormEvent.updateInterestRate = function(event, subtotalId, lineItemId) { var element = Event.element(event); financeMaster.subtotals[subtotalId].lineItems[lineItemId].interestRate = (element.value.parseFloat() > 99.99) ? 99.99 : element.value.parseFloat(); FormLayout.calcAndUpdateControls(); }
FormEvent.updateTaxRate = function(event, subtotalId, lineItemId) { var element = Event.element(event); financeMaster.subtotals[subtotalId].lineItems[lineItemId].taxRate = (element.value.parseFloat() > 99.99) ? 99.99 : element.value.parseFloat(); FormLayout.calcAndUpdateControls(); }
FormEvent.updateSubtotal = function(event, subtotalId) { var element = Event.element(event); financeMaster.subtotals[subtotalId].name = element.value.strip(); FormLayout.calcAndUpdateControls(); }
FormEvent.updateFormInterestRate = function(event) { var element = Event.element(event); financeMaster.interestRate = (element.value.parseFloat() > 99.99) ? 99.99 : element.value.parseFloat(); FormLayout.calcAndUpdateControls(); }
FormEvent.updateFormTaxRate = function(event) { var element = Event.element(event); financeMaster.taxRate = (element.value.parseFloat() > 99.99) ? 99.99 : element.value.parseFloat(); FormLayout.calcAndUpdateControls(); }
FormEvent.updateFormFormDate = function(event) { var element = Event.element(event); financeMaster.formDate = (parseDate(element.value.strip()) != null) ? formatDate(parseDate(element.value.strip()), 'MM/dd/y') : null; FormLayout.calcAndUpdateControls(); }
FormEvent.updateFormFormNumber = function(event) { var element = Event.element(event); financeMaster.formNumber = element.value.strip(); FormLayout.calcAndUpdateControls(); }
FormEvent.updateFormCustomerId = function(event) { var element = Event.element(event); financeMaster.customerId = element.value.strip(); FormLayout.calcAndUpdateControls(); }
FormEvent.updateFormComments = function(event) { var element = Event.element(event); financeMaster.comments = element.value.strip().substr(0, 1200); FormLayout.calcAndUpdateControls(); }
FormEvent.updateFormFOB = function(event) { var element = Event.element(event); financeMaster.fOB = element.value.strip(); }
FormEvent.updateFormPurchaseOrder = function(event) { var element = Event.element(event); financeMaster.purchaseOrder = element.value.strip(); }
FormEvent.updateFormRepresentative = function(event) { var element = Event.element(event); financeMaster.representative = element.value.strip(); }
FormEvent.updateFormProject = function(event) { var element = Event.element(event); financeMaster.project = element.value.strip(); }
FormEvent.updateFormShipDate = function(event) { var element = Event.element(event); financeMaster.shipDate = (parseDate(element.value.strip()) != null) ? formatDate(parseDate(element.value.strip()), 'MM/dd/y') : null; }
FormEvent.updateFormTerms = function(event) { var element = Event.element(event); financeMaster.terms = element.value.strip(); }
FormEvent.updateDueDate = function(event, subtotalId, lineItemId) {
    var element = Event.element(event);
    if (element == null) { element = $('txtDueDate' + "_" + subtotalId + "_" + lineItemId); }
    financeMaster.subtotals[subtotalId].lineItems[lineItemId].date = (parseDate(element.value.strip()) != null) ? formatDate(parseDate(element.value.strip()), 'MM/dd/y') : null;
    FormLayout.calcAndUpdateControls();
}

FormEvent.toggleUnitCustom = function(event, subtotalId, lineItemId) {
    var ctrlIndex = "_" + subtotalId + "_" + lineItemId;
    var element = Event.element(event);
    if (element.options[element.selectedIndex].value == 0) {
        element.hide();
        $('txtUnitCustom' + ctrlIndex).show();
    }
}

FormEvent.evalNewLineByDescription = function(event, subtotalId, lineItemId) {
    var ctrlIndex = "_" + subtotalId + "_" + lineItemId;
    if (($F('txtDescription' + ctrlIndex).strip().length > 0) && ($F('txtDescription' + ctrlIndex).strip() != financeMaster.subtotals[subtotalId].lineItems[lineItemId].description)) {
        financeMaster.subtotals[subtotalId].lineItems[lineItemId].description = $F('txtDescription' + ctrlIndex);
        FormLayout.addLine('divFormGrid', subtotalId);
        // Once new line is added bring focus back to the control that was being edited
        setTimeout("$('txtDescription" + ctrlIndex + "').focus(); Cursor.setAtEnd('txtDescription" + ctrlIndex + "');", 50);
    }
}

FormEvent.evalNewLineByDueDate = function(event, subtotalId, lineItemId) {
    var ctrlIndex = "_" + subtotalId + "_" + lineItemId;
    if (($F('txtDueDate' + ctrlIndex).strip().length > 0) && ($F('txtDueDate' + ctrlIndex).strip() != financeMaster.subtotals[subtotalId].lineItems[lineItemId].date)) {
        financeMaster.subtotals[subtotalId].lineItems[lineItemId].date = $F('txtDueDate' + ctrlIndex);
        FormLayout.addLine('divFormGrid', subtotalId);
        // Once new line is added bring focus back to the control that was being edited
        setTimeout("$('txtDueDate" + ctrlIndex + "').focus(); Cursor.setAtEnd('txtDueDate" + ctrlIndex + "');", 50);
    }
}

FormEvent.evalNewLineByQuantity = function(event, subtotalId, lineItemId) {
    var ctrlIndex = "_" + subtotalId + "_" + lineItemId;
    if (($F('txtQuantity' + ctrlIndex).strip().length > 0) && ($F('txtQuantity' + ctrlIndex) != "1") && ($F('txtQuantity' + ctrlIndex).strip() != financeMaster.subtotals[subtotalId].lineItems[lineItemId].quantity)) {
        financeMaster.subtotals[subtotalId].lineItems[lineItemId].quantity = $F('txtQuantity' + ctrlIndex);
        FormLayout.addLine('divFormGrid', subtotalId);
        // Once new line is added bring focus back to the control that was being edited
        setTimeout("$('txtQuantity" + ctrlIndex + "').focus(); Cursor.setAtEnd('txtQuantity" + ctrlIndex + "');", 50);
    }
}

FormEvent.evalNewLineByUnitPrice = function(event, subtotalId, lineItemId) {
    var ctrlIndex = "_" + subtotalId + "_" + lineItemId;
    if (($F('txtUnitPrice' + ctrlIndex).strip().length > 0) && ($F('txtUnitPrice' + ctrlIndex).strip() != financeMaster.subtotals[subtotalId].lineItems[lineItemId].unitPrice)) {
        financeMaster.subtotals[subtotalId].lineItems[lineItemId].unitPrice = $F('txtUnitPrice' + ctrlIndex);
        FormLayout.addLine('divFormGrid', subtotalId);
        // Once new line is added bring focus back to the control that was being edited
        setTimeout("$('txtUnitPrice" + ctrlIndex + "').focus(); Cursor.setAtEnd('txtUnitPrice" + ctrlIndex + "');", 50);
    }
}

FormEvent.setFocus = function(event, subtotalId, lineItemId, controlName) {
    var ctrlId = "";
    if (event.keyCode == 38) {
        if (--lineItemId == -1) { if (--subtotalId == -1) { subtotalId = financeMaster.subtotals.size() - 1; } lineItemId = financeMaster.subtotals[subtotalId].lineItems.size() - 1; }
        ctrlId = controlName + "_" + subtotalId + "_" + lineItemId;
    }
    else if (event.keyCode == 40) {
        if (++lineItemId == financeMaster.subtotals[subtotalId].lineItems.size()) { if (++subtotalId == financeMaster.subtotals.size()) { subtotalId = 0; } lineItemId = 0; }
        ctrlId = controlName + "_" + subtotalId + "_" + lineItemId;
    }
    if (ctrlId != "") {
        $(ctrlId).focus();
        Cursor.setAtEnd(ctrlId);
    }
}

FormEvent.advancedOptionsAction = function(event, layer, subtotalId, lineItemId) {
    var ctrlIndex = "_" + subtotalId + "_" + lineItemId;
    $('imgAdvancedOptions' + ctrlIndex).src = 'images/advFormSmallPctBlu.gif';
    $(layer + ctrlIndex).hide();
    if ($("rbInterestDate" + ctrlIndex + "_1").checked) { financeMaster.subtotals[subtotalId].lineItems[lineItemId].interestDate = ""; }
    FormLayout.CDUB('divFormGrid');
}

FormEvent.insertOptionsAction = function(event, layer, subtotalId, lineItemId) {
    var ctrlIndex = "_" + subtotalId + "_" + lineItemId;
    $('imgInsertOptions' + ctrlIndex).src = 'images/advFormSmallPlusBlu.gif';
    $(layer + ctrlIndex).hide();
}

FormEvent.showAdvancedOptions = function(event, layer, subtotalId, lineItemId) {
    FormEvent.hideAllLayeredOptions();

    ctrlIndex = "_" + subtotalId + "_" + lineItemId;
    $('imgAdvancedOptions' + ctrlIndex).src = 'images/advFormSmallPctOrg.gif';
    $(layer + ctrlIndex).show();
}

FormEvent.showInsertOptions = function(event, layer, subtotalId, lineItemId) {
    FormEvent.hideAllLayeredOptions();

    ctrlIndex = "_" + subtotalId + "_" + lineItemId;
    $('imgInsertOptions' + ctrlIndex).src = 'images/advFormSmallPlusOrg.gif';
    $(layer + ctrlIndex).show();
}

FormEvent.hideAllLayeredOptions = function() {
    var i, j, ctrlIndex;

    i = 0;
    if (financeMaster.subtotals != null) {
        financeMaster.subtotals.each(function(subtotal) {
            j = 0;
            subtotal.lineItems.each(function(lineItem) {
                ctrlIndex = "_" + i + "_" + j;
                $('divAdvancedOptions' + ctrlIndex).hide();
                $('divInsertOptions' + ctrlIndex).hide();

                $('imgInsertOptions' + ctrlIndex).src = 'images/advFormSmallPlusBlu.gif';
                $('imgAdvancedOptions' + ctrlIndex).src = 'images/advFormSmallPctBlu.gif';
                j++;
            });
            i++;
        });
    }
}

FormEvent.bindEvents = function() {
    FormEvent.bindUpdateEvents();
    FormEvent.bindEvalNewLineEvents();
    FormEvent.bindFocusEvents();
    FormEvent.bindHTMLContolEvents();
    FormEvent.bindCalendar();
    FormEvent.bindFinanceMasterContolEvents();
}

FormEvent.bindUpdateEvents = function() {
    var i, j, ctrlIndex;

    i = 0;
    if (financeMaster.subtotals != null) {
        financeMaster.subtotals.each(function(subtotal) {
            j = 0;
            subtotal.lineItems.each(function(lineItem) {
                ctrlIndex = "_" + i + "_" + j;
                Event.observe('txtDueDate' + ctrlIndex, 'change', FormEvent.updateDueDate.bindAsEventListener(FormEvent, i, j));
                Event.observe('txtQuantity' + ctrlIndex, 'change', FormEvent.updateQuantity.bindAsEventListener(FormEvent, i, j));
                Event.observe('txtDescription' + ctrlIndex, 'change', FormEvent.updateDescription.bindAsEventListener(FormEvent, i, j));
                Event.observe('txtUnitPrice' + ctrlIndex, 'change', FormEvent.updateUnitPrice.bindAsEventListener(FormEvent, i, j));
                if (!financeMaster.isSimple) {
                    Event.observe('lstUnit' + ctrlIndex, 'change', FormEvent.updateUnit.bindAsEventListener(FormEvent, i, j));
                    Event.observe('txtUnitCustom' + ctrlIndex, 'change', FormEvent.updateUnitCustom.bindAsEventListener(FormEvent, i, j));
                    Event.observe('txtInterestRate' + ctrlIndex, 'change', FormEvent.updateInterestRate.bindAsEventListener(FormEvent, i, j));
                    Event.observe('txtTaxRate' + ctrlIndex, 'change', FormEvent.updateTaxRate.bindAsEventListener(FormEvent, i, j));
                    Event.observe('txtInterestDate' + ctrlIndex, 'change', FormEvent.updateInterestDate.bindAsEventListener(FormEvent, i, j));
                }
                j++;
            });
            if (!financeMaster.isSimple && subtotal.visible) {
                ctrlIndex = "_" + i;
                Event.observe('txtSubtotal' + ctrlIndex, 'change', FormEvent.updateSubtotal.bindAsEventListener(FormEvent, i));
            }
            i++;
        });
    }
}

FormEvent.bindEvalNewLineEvents = function() {
    var i, j, ctrlIndex;

    i = 0;
    if (financeMaster.subtotals != null) {
        if (financeMaster.isSimple) {
            i = financeMaster.subtotals.size() - 1;
            j = financeMaster.subtotals[i].lineItems.size() - 1;
            ctrlIndex = "_" + i + "_" + j;
            Event.observe('txtDueDate' + ctrlIndex, 'keyup', FormEvent.evalNewLineByDueDate.bindAsEventListener(FormEvent, i, j));
            Event.observe('txtQuantity' + ctrlIndex, 'keyup', FormEvent.evalNewLineByQuantity.bindAsEventListener(FormEvent, i, j));
            Event.observe('txtDescription' + ctrlIndex, 'keyup', FormEvent.evalNewLineByDescription.bindAsEventListener(FormEvent, i, j));
            Event.observe('txtUnitPrice' + ctrlIndex, 'keyup', FormEvent.evalNewLineByUnitPrice.bindAsEventListener(FormEvent, i, j));
        }
        else {
            financeMaster.subtotals.each(function(subtotal) {
                j = subtotal.lineItems.size() - 1;
                ctrlIndex = "_" + i + "_" + j;
                Event.observe('txtDueDate' + ctrlIndex, 'keyup', FormEvent.evalNewLineByDueDate.bindAsEventListener(FormEvent, i, j));
                Event.observe('txtQuantity' + ctrlIndex, 'keyup', FormEvent.evalNewLineByQuantity.bindAsEventListener(FormEvent, i, j));
                Event.observe('txtDescription' + ctrlIndex, 'keyup', FormEvent.evalNewLineByDescription.bindAsEventListener(FormEvent, i, j));
                Event.observe('txtUnitPrice' + ctrlIndex, 'keyup', FormEvent.evalNewLineByUnitPrice.bindAsEventListener(FormEvent, i, j));
                i++;
            });
        }
    }
}

FormEvent.bindFocusEvents = function() {
    var i, j, ctrlIndex;

    i = 0;
    if (financeMaster.subtotals != null) {
        financeMaster.subtotals.each(function(subtotal) {
            j = 0;
            subtotal.lineItems.each(function(lineItem) {
                ctrlIndex = "_" + i + "_" + j;
                Event.observe('txtDueDate' + ctrlIndex, 'keydown', FormEvent.setFocus.bindAsEventListener(FormEvent, i, j, 'txtDueDate'));
                Event.observe('txtQuantity' + ctrlIndex, 'keydown', FormEvent.setFocus.bindAsEventListener(FormEvent, i, j, 'txtQuantity'));
                Event.observe('txtDescription' + ctrlIndex, 'keydown', FormEvent.setFocus.bindAsEventListener(FormEvent, i, j, 'txtDescription'));
                Event.observe('txtUnitPrice' + ctrlIndex, 'keydown', FormEvent.setFocus.bindAsEventListener(FormEvent, i, j, 'txtUnitPrice'));
                j++;
            });
            i++;
        });
    }
}

FormEvent.bindHTMLContolEvents = function() {
    var i, j, ctrlIndex;

    i = 0;
    if (financeMaster.subtotals != null) {
        financeMaster.subtotals.each(function(subtotal) {
            j = 0;
            subtotal.lineItems.each(function(lineItem) {
                ctrlIndex = "_" + i + "_" + j;
                if (!financeMaster.isSimple) {
                    Event.observe('lstUnit' + ctrlIndex, 'change', FormEvent.toggleUnitCustom.bindAsEventListener(FormEvent, i, j));
                    Event.observe('lnkAdvancedOptions' + ctrlIndex, 'click', FormEvent.showAdvancedOptions.bindAsEventListener(FormEvent, 'divAdvancedOptions', i, j));
                    Event.observe('lnkInsertOptions' + ctrlIndex, 'click', FormEvent.showInsertOptions.bindAsEventListener(FormEvent, 'divInsertOptions', i, j));
                    Event.observe('btnAdvancedOptions' + ctrlIndex, 'click', FormEvent.advancedOptionsAction.bindAsEventListener(FormEvent, 'divAdvancedOptions', i, j));
                    Event.observe('btnInsertOptions' + ctrlIndex, 'click', FormEvent.insertOptionsAction.bindAsEventListener(FormEvent, 'divInsertOptions', i, j));
                }
                j++;
            });
            i++;
        });
    }
}

FormEvent.bindFinanceMasterContolEvents = function() {
    Event.observe('txtFormDate', 'change', FormEvent.updateFormFormDate.bindAsEventListener(FormEvent));
    Event.observe('txtFormNumber', 'change', FormEvent.updateFormFormNumber.bindAsEventListener(FormEvent));
    Event.observe('txtCustomerId', 'change', FormEvent.updateFormCustomerId.bindAsEventListener(FormEvent));
    Event.observe('txtInterestRate', 'change', FormEvent.updateFormInterestRate.bindAsEventListener(FormEvent));
    Event.observe('txtTaxRate', 'change', FormEvent.updateFormTaxRate.bindAsEventListener(FormEvent));
    Event.observe('txtComments', 'change', FormEvent.updateFormComments.bindAsEventListener(FormEvent));
    Event.observe('txtFOB', 'change', FormEvent.updateFormFOB.bindAsEventListener(FormEvent));
    Event.observe('txtPurchaseOrder', 'change', FormEvent.updateFormPurchaseOrder.bindAsEventListener(FormEvent));
    Event.observe('txtRepresentative', 'change', FormEvent.updateFormRepresentative.bindAsEventListener(FormEvent));
    Event.observe('txtProject', 'change', FormEvent.updateFormProject.bindAsEventListener(FormEvent));
    Event.observe('txtShipDate', 'change', FormEvent.updateFormShipDate.bindAsEventListener(FormEvent));
    Event.observe('txtTerms', 'change', FormEvent.updateFormTerms.bindAsEventListener(FormEvent));
}

FormEvent.bindTooltips = function() {
    var i, j, ctrlIndex;

    i = 0;
    if (financeMaster.subtotals != null) {
        financeMaster.subtotals.each(function(subtotal) {
            j = 0;
            subtotal.lineItems.each(function(lineItem) {
                ctrlIndex = "_" + i + "_" + j;
                if (fastdueForm == FastDueForms.Pastdue) {
                    new Tip($('txtDueDate' + ctrlIndex), 'Interest is calculated based upon the difference between the notice date and the due dates entered. You can customize the way interest will be calculated when advanced features are enabled. Set the interest rate at a yearly rate and the system will automatically apply the interest charge to the past due items.');
                }
                j++;
            });
            i++;
        });
    }

    FormEvent.bindFinanceMasterTooltips();
}

FormEvent.bindFinanceMasterTooltips = function() {
    if (fastdueForm == FastDueForms.Invoice) {
        new Tip($('txtInterestRate'), 'Interest is calculated based upon the difference between the invoice date and the due date. You can customize the way interest will be calculated when advanced features are enabled. Set the interest rate at a yearly rate and the system will automatically apply the interest charge to billed items.');
    }
    else if (fastdueForm == FastDueForms.Pastdue) {
        new Tip($('txtInterestRate'), 'Interest is calculated based upon the difference between the notice date and the due dates entered. You can customize the way interest will be calculated when advanced features are enabled. Set the interest rate at a yearly rate and the system will automatically apply the interest charge to the past due items.');
    }
    //new Tip($('txtTaxRate'), 'Click <a href=\"http://www.taxadmin.org/FTA/rate/sales.html\" target="_blank" style=\"color: #ffffff; text-decoration:underline;\">here</a> to see typical tax rates per state, or choose your own', {hideOn: 'click', closeButton: true});
}

FormEvent.bindCalendar = function() {
    var i, j, ctrlIndex;

    i = 0;
    if (financeMaster.subtotals != null) {
        financeMaster.subtotals.each(function(subtotal) {
            j = 0;
            subtotal.lineItems.each(function(lineItem) {            
                ctrlIndex = "_" + i + "_" + j;
                new Zapatec.Calendar.setup({ firstDay: 1, electric: true, inputField: "txtDueDate" + ctrlIndex, ifFormat: "%m/%d/%Y", daFormat: "%m/%d/%Y", onUpdate: FormEvent.calUpdate });
                if (!financeMaster.isSimple) { new Zapatec.Calendar.setup({ firstDay: 1, electric: true, inputField: "txtInterestDate" + ctrlIndex, ifFormat: "%m/%d/%Y", daFormat: "%m/%d/%Y", onUpdate: FormEvent.calUpdate }); }
                j++;
            });
            i++;
        });
    }
}

FormEvent.calUpdate = function(cal) {
    var i, j, element;

    i = 0;
    if (financeMaster.subtotals != null) {
        financeMaster.subtotals.each(function(subtotal) {
            j = 0;
            subtotal.lineItems.each(function(lineItem) {
                element = $('txtDueDate' + "_" + i + "_" + j);
                var date = parseDate(element.value.strip());

                if (fastdueForm == FastDueForms.Pastdue && date != null && (date >= parseDate(financeMaster.formDate))) {
                    alert("Due Date can not be ahead or same as Notice Date");
                    element.value = financeMaster.subtotals[i].lineItems[j].date;
                }
                else {
                    financeMaster.subtotals[i].lineItems[j].date = (date != null) ? formatDate(date, 'MM/dd/y') : null;
                }
                if (!financeMaster.isSimple) {
                    element = $('txtInterestDate' + "_" + i + "_" + j);
                    financeMaster.subtotals[i].lineItems[j].interestDate = (parseDate(element.value.strip()) != null) ? formatDate(parseDate(element.value.strip()), 'MM/dd/y') : null;
                }
                j++;
            });
            i++;
        });
    }

    FormLayout.calcAndUpdateControls();
}

FormEvent.isFormDateValid = function(formDate) // Compare form date with all due dates but only in the case of PastDue Notice
{
    var i, j, element, lineItemDate, retVal = true;
    i = 0;
    if (financeMaster.subtotals != null) {
        financeMaster.subtotals.each(function(subtotal) {
            j = 0;
            subtotal.lineItems.each(function(lineItem) {
                lineItemDate = parseDate(financeMaster.subtotals[i].lineItems[j].date);
                if (lineItemDate != null && (lineItemDate > formDate)) { retVal = false; }
                j++;
            });
            i++;
        });
    }
    return retVal;
}

FormEvent.bindAutoComplete = function() {
    var i, j, ctrlIndex;
    i = 0;
    if (financeMaster.subtotals != null) {
        financeMaster.subtotals.each(function(subtotal) {
            j = 0;
            subtotal.lineItems.each(function(lineItem) {
                ctrlIndex = "_" + i + "_" + j;
                new Autocompleter.Local('txtDescription' + ctrlIndex, 'descList' + ctrlIndex, autoCompDescs, {choices: 10, ignoreCase: true, frequency:0.01, partialSearch: "on"});
                j++;
            });
            i++;
        });
    }
}

// Class Calculator
var Calculator = new Object;
Calculator.calculate = function() {
    financeMaster.subTotal = 0.0;
    financeMaster.interest = 0.0;
    financeMaster.tax = 0.0;
    financeMaster.total = 0.0;
    var interestRate;

    if (financeMaster.subtotals != null) {
        financeMaster.subtotals.each(function(subtotal) {
            subtotal.total = 0.0;
            subtotal.interest = 0.0;
            subtotal.tax = 0.0;
            subtotal.endTotal = 0.0;

            subtotal.lineItems.each(function(lineItem) {
                lineItem.total = 0.0;
                lineItem.interest = 0.0;
                lineItem.tax = 0.0;
                lineItem.endTotal = 0.0;

                lineItem.total = (lineItem.quantity > 0) ? lineItem.quantity * lineItem.unitPrice : 0;
                lineItem.total = NumberUtil.roundDecimals(lineItem.total, 2);
                subtotal.total += lineItem.total;

                var interestRate = (lineItem.interestRate > 0) ? lineItem.interestRate : financeMaster.interestRate;
                if (interestRate > 0) {
                    if (fastdueForm == FastDueForms.Pastdue && lineItem.total > 0) {
                        lineItem.interest = (isDate(lineItem.interestDate, 'MM/dd/y') == true)
							? FDUtil.findInterest(parseDate(lineItem.interestDate), parseDate(financeMaster.formDate), lineItem.total, interestRate)
							: FDUtil.findInterest(parseDate(lineItem.date), parseDate(financeMaster.formDate), lineItem.total, interestRate);
                    }
                    else {
                        /*
                        lineItem.interest = (isDate(lineItem.interestDate, 'MM/dd/y') == true)
                        ? FDUtil.findInterest(parseDate(financeMaster.formDate), parseDate(lineItem.interestDate), lineItem.total, interestRate)
                        : FDUtil.findInterest(parseDate(financeMaster.formDate), parseDate($F('tbInvoiceDueDate')), lineItem.total, interestRate);
                        */
                        lineItem.interest = 0.0;
                    }

                    lineItem.interest = (isNaN(lineItem.interest) || !isFinite(lineItem.interest)) ? 0.0 : NumberUtil.roundDecimals(lineItem.interest, 2);
                    if (lineItem.interest > 0) { lineItem.interest -= lineItem.total; }
                }
                subtotal.interest += lineItem.interest;

                lineItem.tax = (lineItem.taxRate > 0) ? lineItem.total * (lineItem.taxRate / 100) : lineItem.total * (financeMaster.taxRate / 100);
                lineItem.tax = NumberUtil.roundDecimals(lineItem.tax, 2);
                subtotal.tax += lineItem.tax;

                lineItem.endTotal = lineItem.tax + lineItem.interest + lineItem.total;
                subtotal.endTotal += lineItem.endTotal;
            });

            financeMaster.subTotal += subtotal.total;
            financeMaster.interest += subtotal.interest;
            financeMaster.tax += subtotal.tax;
            financeMaster.total = financeMaster.interest + financeMaster.tax + financeMaster.subTotal;
        });
    }
}
