﻿// 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, category, categoryCustom, clientOrJobCode, description, reimbursement, unitPrice, amountDue)
    {
        this.encryptedId = encryptedId;
        this.date = date;
		this.clientOrJobCode = clientOrJobCode;
		this.description = description;
		this.unitPrice = unitPrice;
        this.category = category;
		this.reimbursement = reimbursement;
		this.categoryCustom = categoryCustom;
        this.amountDue = amountDue;
    }
};

// Class FastDueUnit
var FastDueCategory = Class.create();
FastDueCategory.prototype =
{
    initialize: function(encryptedId, name)
    {
        this.encryptedId = encryptedId;
        this.name = name;
	}
};

// Form Categories collection global vriable
var formCategories = 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;

	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 = 8;
		widthDate = 95;  widthClientOrJobCode = 55; widthCategory = 75; widthDesc = 280; widthReimbursement = 70; widthUnitPrice = 121; widthAmountDue = 123;
		widthDescControl = 21.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>");

	innerHTML.push("<th class='left padright' style='width:" + widthDate +"px; background-color:#EE8431;'>Date</th>");
	innerHTML.push("<th class='left padleft padright' style='width:" + widthClientOrJobCode + "px; background-color:#EE8431;'>Job</th>");
	innerHTML.push("<th class='left padleft padright' style='width:" + widthCategory + "px; background-color:#EE8431;'>Category</th>");
	innerHTML.push("<th class='left padleft padright' style='width:" + widthDesc + "px; background-color:#EE8431;'>Description</th>");
	innerHTML.push("<th class='left padleft padright' style='width:" + widthReimbursement + "px; background-color:#EE8431;'>%</th>");
	innerHTML.push("<th class='right padleft' style='width:" + widthUnitPrice + "px; background-color:#EE8431;'><div style='margin-right:2.3em; font-size:11px'>Item Amount</div></th>");
	innerHTML.push("<th class='right padleft padright' style='width:" + widthTotal + "px; background-color:#EE8431;'>Due Amount</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:40px; 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; padding-top:4px;'";
				}
				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: 65px; vertical-align:top;'>");
				// Spacer
				innerHTML.push("<td><img src='images/spacer.gif' width='1' height='1'></td>");
				// Date
				innerHTML.push("<td id='colDueDate" + ctrlIndex + "' class='padright'><input id='txtDueDate" + ctrlIndex + "' type='text' style='text-align:left; width:7.0em' maxLength='10' class='formFieldGridCal'/></td>");
				// Client Or Job Code
				innerHTML.push("<td class='padleft padright'><input id='txtClientOrJobCode" + ctrlIndex + "' type='text' style='width: 3.8em' value='1' maxlength='9' class='formFieldGrid'/></td>");
				// Category
				innerHTML.push("<td class='padleft padright'><select id='lstCategory" + ctrlIndex + "' class='formFieldGridSelect' style='width: 7em; height: 2em;'><option>Loading...</option></select>");
				innerHTML.push("<input id='txtCategoryCustom" + ctrlIndex + "' type='text' style='width:5.5em; display:none;' maxlength='15' class='formFieldGrid'/></td>");
				// Description
				innerHTML.push("<td class='padleft padright'><textarea id='txtDescription" + ctrlIndex + "' name='txtDescription" + ctrlIndex + "' type='text' class='formFieldGrid' value='' maxlength='200' style='width:" + widthDescControl + "em; height:49px; font-family: Arial;'/></textarea></td>");
				// Reimbursement
				innerHTML.push("<td class='padleft padright'><input id='txtReimbursement" + ctrlIndex + "' type='text' style='text-align:right; width: 3.1em' value='1' maxlength='9' class='formFieldGrid'/><span style='vertical-align: text-bottom;'>%</span></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' class='formFieldGrid' size='5'/>&nbsp;</td>");
				// Amount Due
				innerHTML.push("<td class='padleft padright'" + lineSeperator + "><span id='spanTotalCS" + ctrlIndex + "' style='float:left; font-family:Arial;'>$</span><span id='divAmountDue" + ctrlIndex + "' style='float: right; font-family: Arial;'></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 + "' 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 + "' 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' 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 + "' 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)
	{
		/////// Subtotal ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		innerHTML.push("<tr style='height: 2.5em; display:none;'>");
		innerHTML.push("<td colspan='5'><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='5'><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; display:none;'>");
		innerHTML.push("<td colspan='5'><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' 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;'>");
		innerHTML.push("<td colspan='5'><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; display: none;'>");
		innerHTML.push("<td colspan='5'><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' 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='5'><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;'>TOTAL DUE:</div><div style='position: relative;'><img src='images/PayThisAmount.jpg' style='position:absolute; top:5.0em; left:5.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; font-family: Arial;' 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("");
	FormLayout.fillCategoriesToGrid();
}

FormLayout.drawAdvancedFooter = function(visible)
{
	if (!visible) { $('divFormAdvancedFooter').innerHTML = ''; return; }
	if (!$('divFormAdvancedFooter').innerHTML.blank()) { return; }

	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;'>");
	innerHTML.push("<td class='right padright3' style='border-bottom: solid 2px #E4EFEF;'><span style='float: left'><input id='txtInterestRate' type='text' 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' 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;'>TOTAL DUE:</div><div style='position:relative;'><img src='images/PayThisAmount.jpg' 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.loadCategories = function()
{
	var fdh = new FastDueHandler();
	formCategories = fdh.getAllCategories();
}

// Fill loaded Units into a single HTML <select> form element
FormLayout.fillCategories = function(element)
{
	element.remove(0);
	var opt;

	opt = document.createElement('option');
	opt.text = '';
	opt.value = '';
	opt.style.backgroundColor = '#FFFFFF';

	try { element.add(opt, null); }
	catch(ex) { element.add(opt); }

	for(var i = 0; i < formCategories.length; i++) {
		opt = document.createElement('option');
		opt.text = formCategories[i].name;
		opt.value = formCategories[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.fillCategoriesToGrid = 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.fillCategories($('lstCategory' + ctrlIndex));
				j++;
			});
			i++;
		});
	}
}

FormLayout.addLine = function(layer, subtotalId)
{
	financeMaster.subtotals[subtotalId].lineItems.push(new FastDueLineItem(0, null, null, null, null, null, 100.0, 0.0, 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, null, null, null, 100.0, 0.0, 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);
}

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 : '';
				$('txtClientOrJobCode' + ctrlIndex).value = (lineItem.clientOrJobCode != null) ? lineItem.clientOrJobCode : '';
				$('txtDescription' + ctrlIndex).value = (lineItem.description != null) ? lineItem.description : '';
				$('txtReimbursement' + ctrlIndex).value = (lineItem.reimbursement != null) ? FDUtil.formatCurrency(lineItem.reimbursement) : '';
				$('txtUnitPrice' + ctrlIndex).value = (lineItem.unitPrice != null) ? FDUtil.formatCurrency(lineItem.unitPrice) : '';
				$('divAmountDue' + ctrlIndex).innerHTML = (lineItem.amountDue != null) ? FDUtil.formatCurrency(lineItem.amountDue) : '';

				$('spanUnitPriceCS' + ctrlIndex).innerHTML = crncySymbl;
				$('spanTotalCS' + ctrlIndex).innerHTML = crncySymbl;
				if (lineItem.category != null && lineItem.category.encryptedId != null) {
						for (var k = 0; k < $('lstCategory' + ctrlIndex).options.length; k++) {
							if ($('lstCategory' + ctrlIndex).options[k].value == lineItem.category.encryptedId) {
								$('lstCategory' + ctrlIndex).options[k].selected = true;
								break;
							}
						}
					}
				$('txtCategoryCustom' + ctrlIndex).value = (lineItem.categoryCustom != null) ? lineItem.categoryCustom : '';

				// Iff categoryCustom has some value or category.encryptedId is 0 then hide Category list box and show caregoryCutom textbox
					if ((lineItem.categoryCustom != null && !lineItem.categoryCustom.blank()) || (lineItem.category != null && lineItem.category.encryptedId == 0)) { $('lstCategory' + ctrlIndex).hide(); $('txtCategoryCustom' + ctrlIndex).show(); }

				if (!financeMaster.isSimple) {
					$('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(); }
				}
				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++;
		});
	}

	$('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.clientOrJobCode = null;
				lineItem.description = null;
				lineItem.unitPrice = 0;
				lineItem.reimbursement = 100;
			});
		});
	}
	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
{
	// Load categoriess if required
	if (formCategories == null) { FormLayout.loadCategories(); }
	// Do Calculate, draw, updateControls, bindEvents
	Calculator.calculate();
	FormLayout.draw(layer, FormLayout.CDUB.arguments[1], FormLayout.CDUB.arguments[2], FormLayout.CDUB.arguments[3]);
	FormLayout.updateControls();
	FormEvent.bindEvents();
	FormEvent.bindTooltips();

	//$('divJSON').innerHTML = (Object.toJSON(financeMaster));
}

FormLayout.calcAndUpdateControls = function(layer) // [C]alculate, [D]raw, [U]pdate, [B]ind Events
{
	Calculator.calculate();
	FormLayout.updateControls();
}

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;
}

// 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.calcAndUpdateControls();}
FormEvent.updateClientOrJobCode = function(event, subtotalId, lineItemId) { var element = Event.element(event); financeMaster.subtotals[subtotalId].lineItems[lineItemId].clientOrJobCode = element.value.strip(); FormLayout.calcAndUpdateControls();}
FormEvent.updateCategory = function(event, subtotalId, lineItemId) { var element = Event.element(event); financeMaster.subtotals[subtotalId].lineItems[lineItemId].category = new FastDueCategory(element.options[element.selectedIndex].value, element.options[element.selectedIndex].text); }
FormEvent.updateCategoryCustom = function(event, subtotalId, lineItemId) { var element = Event.element(event); financeMaster.subtotals[subtotalId].lineItems[lineItemId].categoryCustom = element.value; }
FormEvent.updateReimbursement = function(event, subtotalId, lineItemId) { var element = Event.element(event); financeMaster.subtotals[subtotalId].lineItems[lineItemId].reimbursement = (element.value.parseFloat() > 100.00) ? 100.00 : element.value.parseFloat(); FormLayout.calcAndUpdateControls(); }
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.toggleCategoryCustom = function(event, subtotalId, lineItemId)
{
	var ctrlIndex = "_" + subtotalId + "_" + lineItemId;
	var element = Event.element(event);
	if (element.options[element.selectedIndex].value == 0)
	{
		element.hide();
		$('txtCategoryCustom' + 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.evalNewLineByClientOrJobCode = function(event, subtotalId, lineItemId)
{
	var ctrlIndex = "_" + subtotalId + "_" + lineItemId;
	if (($F('txtClientOrJobCode' + ctrlIndex).strip().length > 0) && ($F('txtClientOrJobCode' + ctrlIndex) != "1") && ($F('txtClientOrJobCode' + ctrlIndex).strip() != financeMaster.subtotals[subtotalId].lineItems[lineItemId].clientOrJobCode))
	{
		financeMaster.subtotals[subtotalId].lineItems[lineItemId].clientOrJobCode = $F('txtClientOrJobCode' + ctrlIndex);
		FormLayout.addLine('divFormGrid', subtotalId);
		// Once new line is added bring focus back to the control that was being edited
		setTimeout("$('txtClientOrJobCode" + ctrlIndex + "').focus(); Cursor.setAtEnd('txtClientOrJobCode" + 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('txtClientOrJobCode' + ctrlIndex, 'change', FormEvent.updateClientOrJobCode.bindAsEventListener(FormEvent, i, j));
				Event.observe('lstCategory' + ctrlIndex, 'change', FormEvent.updateCategory.bindAsEventListener(FormEvent, i, j));
				Event.observe('txtCategoryCustom' + ctrlIndex, 'change', FormEvent.updateCategoryCustom.bindAsEventListener(FormEvent, i, j));
				Event.observe('txtDescription' + ctrlIndex, 'change', FormEvent.updateDescription.bindAsEventListener(FormEvent, i, j));
				Event.observe('txtReimbursement' + ctrlIndex, 'change', FormEvent.updateReimbursement.bindAsEventListener(FormEvent, i, j));
				Event.observe('txtUnitPrice' + ctrlIndex, 'change', FormEvent.updateUnitPrice.bindAsEventListener(FormEvent, i, j));
				if (!financeMaster.isSimple) {
					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('txtClientOrJobCode' + ctrlIndex, 'keyup', FormEvent.evalNewLineByClientOrJobCode.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('txtClientOrJobCode' + ctrlIndex, 'keyup', FormEvent.evalNewLineByClientOrJobCode.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('txtClientOrJobCode' + ctrlIndex, 'keydown', FormEvent.setFocus.bindAsEventListener(FormEvent, i, j, 'txtClientOrJobCode'));
				//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;
				Event.observe('lstCategory' + ctrlIndex, 'change', FormEvent.toggleCategoryCustom.bindAsEventListener(FormEvent, i, j));
				if (!financeMaster.isSimple) {
					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() {}

FormEvent.bindFinanceMasterTooltips = function() {}

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());

				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;
}

// 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.amountDue = 0.0;
				var interest = 0.0;

				lineItem.amountDue = (lineItem.reimbursement > 0) ? (lineItem.reimbursement / 100) * lineItem.unitPrice : lineItem.unitPrice;
				subtotal.total += lineItem.amountDue;

				if (financeMaster.interestRate > 0)
				{
					interest = FDUtil.findInterest(parseDate($F(expenseDueDateId)), parseDate(financeMaster.formDate), lineItem.amountDue, financeMaster.interestRate);
					interest = (isNaN(lineItem.interest) || !isFinite(lineItem.interest)) ? 0.0 : NumberUtil.roundDecimals(lineItem.interest, 2);

					if (interest > 0) { interest -= lineItem.amountDue; }

				}

				subtotal.interest += interest;
				subtotal.endTotal += lineItem.amountDue;
			});

			financeMaster.subTotal += subtotal.total;
			financeMaster.interest += subtotal.interest;
			//financeMaster.tax += subtotal.tax;
			financeMaster.total = financeMaster.interest + financeMaster.subTotal;
			//financeMaster.total = 444;
		});
	}
}
