// INITIALIZATION AND RESET FUNCTIONS /////////////////////////////////////////////////////////////

	// currentPartsList Format ///////////////////////////////////////////////////////////////
	// [ [[[ ],[ ]],INTEGER],... ]                                                          //
	//      |   |      |                                                                    //
	//      |   |      --> [n][1] Table's Row ID for the Part                               //
	//      |   |                                                                           //
	//      |   --> [n][0][1].propertyname (Part Specific Properties)                       //
	//      |        Properties:                                                            //
	//      |        availstatus  (STRING:	A Date indicating when available				//
	//		|		 salestatus   (STRING:  ERROR, ONSALE, ZEROITEM, REGULAR)               //
	//      |        hazardstatus (STRING:  YES, NO)                                        //
	//      |        freeship     (STRING:  YES, NO)                                        //
	//      |        partnum      (STRING:  Returned Hy-Cap Part Number)                    //
	//      |        qty          (INTEGER: Quantity as Entered in Search Form)             //
	//      |        desc         (STRING:  Returned Part Description)                      //
	//      |        dstcost      (NUMBER:  (0.00) Returned Distributor Cost)               //
	//      |        dlrcost      (NUMBER:  (0.00) Returned Dealer Cost)                    //
	//      |        dlrfp        (NUMBER:  (0.00) Returned Dealer Featured Part Cost)      //
	//      |        dstfp        (NUMBER:  (0.00) Returned Distributor Featured Part Cost) //
	//      |        dlrbb        (NUMBER:  (0.00) Returned Dealer Bargain Bin Cost)        //
	//      |        dstbb        (NUMBER:  (0.00) Returned Distributor Bargain Bin Cost)   //
	//      |        core         (NUMBER:  (0.00) Returned Part Core Value)                //
	//      |        obsolete     (INTEGER: (0,1) Returned Obsolete Part Status)            //
	//      |        list		  (NUMBER:  (0.00) Returned Suggested List Price		    //
	//      |                                                                               //
	//      ------> [n][0][0].propertyname (Search Wide Properties)                         //
	//               Properties:                                                            //
	//               searchmode  (STRING: EXACT, STARTS, ANYWHERE)                          //
	//               enterednum  (STRING: Part Number as Entered in Search Form)            //
	//               enteredqty  (INTEGER: Quantity as Entered in Search Form)              //
	//               resultcount (INTEGER: How Many Records Found)                          //
	//               priceview   (STRING: PUBLIC, DIST, DEAL, LIST)							//
	//                                                                                      //
	//////////////////////////////////////////////////////////////////////////////////////////
var fade     = 0;
var thePanel = "";

function initPage(pricingView) {
	initArrays();
	theCurrentDLRTotal      = 0.00;
	theCurrentDISTTotal     = 0.00;
	var theSessionPriceView = ""
	theTable                = document.getElementById("PartsListDisplayTable");
	frm                     = document.getElementById('PartListSearchForm');
	frm.SearchPartQty.value = 1;
	
	frm.SearchPartNum.focus();
	
	document.getElementById('deleteSelectAll').checked  = false;
	document.PartListTableForm.deleteSelectAll.disabled = true;
	//document.PartListTableForm.PartsListReset.disabled  = true;
	//document.PartListTableForm.PartsListCreate.disabled = true;
	
	document.getElementById('button_delete').src = "images/button_delete_OFF.png";
	
	if (pricingView != "NONE") {
		document.getElementById("PartsListDLRTotal").innerHTML  = "<font class='PL_SM_Bold'>$ 0.00</font>";
		document.getElementById("PartsListDISTTotal").innerHTML = "<font class='PL_SM_Bold'>$ 0.00</font>";
	}
	
	tableRow          = theTable.insertRow(theCurrentRow);
	tableRow.id       = "EmptyWarningRow";
	tableCell     	  = tableRow.insertCell(0);
	tableCell.id      = "PartListEmptyWarning";
	tableCell.setAttribute('bgColor', '#DDDDDD');
	tableCell.align   = "center";
	tableCell.colSpan = 20;
	
	document.getElementById("PartListEmptyWarning").innerHTML  = "<font face=\"arial\" size=\"3\" color=\"999999\"><b>There are no parts in the order to display.</b></font><br><font face=\"arial\" size=\"2\" color=\"999999\">Please Search for a part or use the Add Part field above to add parts to this order.</font><br /><br />";
}

function initArrays(){
	currentPartsList        = new Array();
	currentPartsforDeletion = new Array();
	theCurrentRow           = 2;
}

function resetPage(whichAction) {
	if (whichAction == "SHOW") {
		document.getElementById('ResetSkirt').style.height = '800px';
		document.getElementById("ResetSkirt").style.visibility = "visible";
		document.getElementById("ResetConfirmationDialog").style.visibility = "visible";
	}
	if (whichAction == "CANCEL") {
		document.getElementById('ResetSkirt').style.height = '0px';
		document.getElementById("ResetSkirt").style.visibility = "hidden";
		document.getElementById("ResetConfirmationDialog").style.visibility = "hidden";
	}
	if (whichAction == "SAVE") {
		// TO DO: Save the Order
		
		document.getElementById('ResetSkirt').style.height = '0px';
		document.getElementById("ResetSkirt").style.visibility = "hidden";
		document.getElementById("ResetConfirmationDialog").style.visibility = "hidden";
	}
	if (whichAction == "CONFIRM") {
		var tableRowCount = theTable.rows.length;
	
		initPage();
		initNotes();
		
		for (i = (tableRowCount-5); i > 2; i--) {
			theTable.deleteRow(i);
		}
	
		document.getElementById("PartListEmptyWarning").innerHTML = "<font face=\"arial\" size=\"3\" color=\"999999\"><b>There are no parts in the order to display.</b></font><br><font face=\"arial\" size=\"2\" color=\"999999\">Please Search for a part or use the Add Part field above to add parts to this order.</font><br /><br />";
		document.getElementById("finalizeButtons").innerHTML      = "<font class='ViewAllDISABLED'>Reset</font>";
		document.getElementById("finalizeButtons").innerHTML      = document.getElementById("finalizeButtons").innerHTML + "<font class='AddtoOrderDISABLED'>Finalize Order</font><br /><br />";
		
		document.getElementById('ResetSkirt').style.height = '0px';
		document.getElementById("ResetSkirt").style.visibility = "hidden";
		document.getElementById("ResetConfirmationDialog").style.visibility = "hidden";
		
		if (document.getElementById("PromotionAlert")) {
			document.getElementById("PromotionAlert").innerHTML = "<font class='ResultsLarge'><font color='#660000'>The Promotion Selection has been reset.</font></font>";
		}
		
		document.getElementById("SaveOrderButtonHolder").innerHTML  = "<font class='ViewAllDISABLED'>Save Order</font><br>";
		document.getElementById("PrintOrderButtonHolder").innerHTML = "<font class='ViewAllDISABLED'>Print Order</font><br>";
		
		DWREngine._execute(_ajaxConfig._cfscriptLocation, null, 'resetSessionArray',resetSessionArrayResult);		
	}
}

function resetSessionArrayResult() {
	updateYellowBar();
}

function changeItemsPerPage(itemCount,chapter,page) {
	DWREngine._execute(_ajaxConfig._cfscriptLocation, null, 'changePartsPerPage',itemCount,chapter,page,changeItemsPerPageResult);
}
function changeItemsPerPageResult(r) {
	top.location.href = "?CHAPTER=" + r[0] + "&PAGE=" + r[1];
}
// EDIT AND UPDATE FUNCTIONS //////////////////////////////////////////////////////////////////////
function openEdit(viewPricing,whichRow) {
	
	// Stash the Row's Current Style
	currentClass = theTable.rows[whichRow].className;
	theEditRow   = whichRow;
	
	// Adjust Row's Style for Edit Mode
	theTable.rows[whichRow].className = "hilite";
	theTable.rows[whichRow].cells[0].innerHTML = "<img src=\"images/orderformSide_L_hilite.png\" width=\"10\" height=\"22\" valign=\"top\">";
	
	//theTable.rows[whichRow].cells[3].innerHTML = "<a href='#' onClick=\"javascript:saveEdit('" + viewPricing + "','" + currentClass + "',"  + whichRow + ",document.PartListTableForm.editQty.value);\"><input type='image' src='images/button_save.png' width='20' height='10' border='0'></a>";

	theTable.rows[whichRow].cells[3].innerHTML = "<input type='image' src='images/button_save.png' width='20' height='10' border='0' onClick=\"saveEdit();\">";
	
	cell4Code = "";
	cell4Code = cell4Code + "<input type='text' class='qtyField' name='editQty' value='" + currentPartsList[(whichRow-2)][0][1].qty + "'>";
	cell4Code = cell4Code + "<input type='hidden' name='editPrice' value='" + viewPricing + "'>";
	cell4Code = cell4Code + "<input type='hidden' name='editRow' value='" + whichRow + "'>";
	cell4Code = cell4Code + "<input type='hidden' name='editClass' value='" + currentClass + "'>";
	
	cell4Code = cell4Code + "<input type='submit' name='submit' style='visibility:hidden;height:0px;width:0px;'>";
	theTable.rows[whichRow].cells[4].innerHTML = cell4Code;
	
	theTable.rows[whichRow].cells[19].innerHTML = "<img src=\"images/orderformSide_R_hilite.png\" width=\"10\" height=\"22\" valign=\"top\">";
	
	document.PartListTableForm.onSubmit = "saveEdit();";
	document.PartListTableForm.editQty.focus();
}
function saveEdit() {
	var pricingView = document.PartListTableForm.editPrice.value;
	var whichClass  = document.PartListTableForm.editClass.value;
	var whichRow    = document.PartListTableForm.editRow.value;
	var whatQty     = document.PartListTableForm.editQty.value;
	
	if (whatQty == 0) {
		currentPartsforDeletion.push(currentPartsList[(whichRow-2)][0][1].partnum);
		deleteParts(pricingView);
	} else {
		// Update proper element in the currentPartsList Array
		currentPartsList[(whichRow-2)][0][1].qty = whatQty;
		
		// Adjust Row's Style back to it s Previous Style
		theTable.rows[whichRow].className = whichClass;
		if (whichClass == "light") {
			theTable.rows[whichRow].cells[0].innerHTML  = "<img src=\"images/orderformSide_L_light.png\" width=\"10\" height=\"22\" valign=\"top\">";
			theTable.rows[whichRow].cells[19].innerHTML = "<img src=\"images/orderformSide_R_light.png\" width=\"10\" height=\"22\" valign=\"top\">";
		} else {
			theTable.rows[whichRow].cells[0].innerHTML  = "<img src=\"images/orderformSide_L_dark.png\" width=\"10\" height=\"22\" valign=\"top\">";
			theTable.rows[whichRow].cells[19].innerHTML = "<img src=\"images/orderformSide_R_dark.png\" width=\"10\" height=\"22\" valign=\"top\">";
		}
		
		// Adjust the Row's Status Image and Qunatity
		theTable.rows[whichRow].cells[3].innerHTML = "<a href='#' onClick=\"javascript:openEdit('" + pricingView + "'," + whichRow + ");\"><img src='images/button_edit.png' width='20' height='10' border='0'></a>";
		theTable.rows[whichRow].cells[4].innerHTML = "<font class='PL_SM_Bold'>" + whatQty + "</font>";
		
		// Adjust the Row's Totals
		// These columns change based on the Viewing Mode and Selected Pricing View ///////
		switch(pricingView) {
			case "NONE":
				// Column Headers are: Empty. We don't show any pricing to the general public.
				theTable.rows[whichRow].cells[16].innerHTML = "";
				theTable.rows[whichRow].cells[18].innerHTML = "";
				break;
			case "LIST":
				// Column Headers are: Item, Core, List
				theTable.rows[whichRow].cells[16].innerHTML = "<font class='PL_SM_Bold'>" + outputMoney(currentPartsList[whichRow-2][0][1].core * whatQty) + "</font>";
				theTable.rows[whichRow].cells[18].innerHTML = "<font class='PL_SM_Bold'>" + outputMoney(currentPartsList[whichRow-2][0][1].list * whatQty) + "</font>";
				break;
			case "DEAL":
				// Column Headers are: Item, Core, Deal
				var DLRCOST = currentPartsList[whichRow-2][0][1].dlrcost;
				
				if ((currentPartsList[whichRow-2][0][1].dlrfp > 0) && (currentPartsList[whichRow-2][0][1].dlrbb > 0)) {
				
				} else {
					if (currentPartsList[whichRow-2][0][1].dlrfp > 0) {
						DLRCOST = currentPartsList[whichRow-2][0][1].dlrfp;
					}
					if (currentPartsList[whichRow-2][0][1].dlrbb > 0) {
						DLRCOST = currentPartsList[whichRow-2][0][1].dlrbb;
					}
				}
				theTable.rows[whichRow].cells[16].innerHTML = "<font class='PL_SM_Bold'>" + outputMoney(currentPartsList[whichRow-2][0][1].core * whatQty) + "</font>";
				theTable.rows[whichRow].cells[18].innerHTML = "<font class='PL_SM_Bold'>" + outputMoney(DLRCOST * whatQty) + "</font>";
				break;
			case "DIST":
				// Column Headers are: Item, Deal, Dist
				var DLRCOST = currentPartsList[whichRow-2][0][1].dlrcost;
				var DSTCOST = currentPartsList[whichRow-2][0][1].dstcost;
				
				if ((currentPartsList[whichRow-2][0][1].dlrfp > 0) && (currentPartsList[whichRow-2][0][1].dlrbb > 0)) {
				
				} else {
					if (currentPartsList[whichRow-2][0][1].dlrfp > 0) {
						DLRCOST = currentPartsList[whichRow-2][0][1].dlrfp;
					}
					if (currentPartsList[whichRow-2][0][1].dlrbb > 0) {
						DLRCOST = currentPartsList[whichRow-2][0][1].dlrbb;
					}
				}
				if ((currentPartsList[whichRow-2][0][1].dstfp > 0) && (currentPartsList[whichRow-2][0][1].dstbb > 0)) {
				
				} else {
					if (currentPartsList[whichRow-2][0][1].dstfp > 0) {
						DLRCOST = currentPartsList[whichRow-2][0][1].dstfp;
					}
					if (currentPartsList[whichRow-2][0][1].dstbb > 0) {
						DLRCOST = currentPartsList[whichRow-2][0][1].dstbb;
					}
				}
				
				theTable.rows[whichRow].cells[16].innerHTML = "<font class='PL_SM_Bold'>" + outputMoney(DLRCOST * whatQty) + "</font>";
				theTable.rows[whichRow].cells[18].innerHTML = "<font class='PL_SM_Bold'>" + outputMoney(DSTCOST * whatQty) + "</font>";
				break;
			default:
				theTable.rows[whichRow].cells[16].innerHTML = "ERR";
				theTable.rows[whichRow].cells[18].innerHTML = "ERR";
				break;
		}
		DWREngine._execute(_ajaxConfig._cfscriptLocation, null, 'adjustQty', currentPartsList[(whichRow-2)][0][1].partnum,whatQty,adjustQtyRESULT);
		
		// Adjust the List's Totals
		updateListTotals(pricingView);
		updateYellowBar();
	}
	
		
	frm.SearchPartNum.focus();
	//return false;
}

function adjustQtyRESULT(r){
	// The adjustQTY ColdFusion function doesn't return anything.
	if (document.getElementById("PromotionAlert")) {
		DWREngine._execute(_ajaxConfig._cfscriptLocation, null, 'resetSelectedPromotion');
		document.getElementById("PromotionAlert").innerHTML = "<font class='ResultsLarge'><font color='#660000'>The Promotion Selection has been reset.</font></font>";
		//DWREngine._execute(_ajaxConfig._cfscriptLocation, null, 'resetSelectedPromotion');
	}
		
	//updateYellowBar();
	//return true;
}

function deletethePartRESULT(r) {
	updateYellowBar();
	
	// Remove the table rows
	initPage(r[0]);
	tableRowCount = theTable.rows.length;
	for (i = (tableRowCount-6); i > 1; i--) { theTable.deleteRow(i); }
	theCurrentRow = 2;
	
	// Create the Retreiving Details alert
	tableRow          = theTable.insertRow(theCurrentRow);
	tableRow.id       = "EmptyWarningRow";
	tableCell     	  = tableRow.insertCell(0);
	tableCell.id      = "PartListEmptyWarning";
	tableCell.setAttribute('bgColor', '#DDDDDD');
	tableCell.align   = "center";
	tableCell.colSpan = 20;
	
	document.getElementById("PartListEmptyWarning").innerHTML  = "<td colspan=\"19\" align=\"center\"><br /><font face=\"arial\" size=\"3\" color=\"666666\"><b>Retrieving the Order Details...</b></font><br><font face=\"arial\" size=\"2\" color=\"999999\">This may take a few seconds.</font><br /><br /></td>";
	document.getElementById("PartsListDLRTotal").innerHTML     = "<font class='PL_SM_Bold'>$ 0.00</font>";
	document.getElementById("PartsListDISTTotal").innerHTML    = "<font class='PL_SM_Bold'>$ 0.00</font>";
	theCurrentCol3Total = 0;
	theCurrentCol2Total = 0;

	// Rebuild the table with the adjusted list of parts
	for (n = 0; n <= (r[1].length - 1); n++) {
		rebuildOrder(r[1][n].partnum,r[1][n].partqty);
	}
}

function setDeleteList(whichRow,whichPart) {
	if (whichRow == "ALL") {
		if (document.getElementById('deleteSelectAll').checked == true) {
			for (i = 0; i <= (currentPartsList.length - 1); i++) {
				currentPartsforDeletion.push(currentPartsList[i][1]);
				document.getElementById(currentPartsList[i][0][0].enterednum + '_del').checked = true;
			}
		} else {
			currentPartsforDeletion = new Array();
			for (i = 0; i <= (currentPartsList.length - 1); i++) {
				document.getElementById(currentPartsList[i][0][0].enterednum + '_del').checked = false;
			}
		}
	} else {
		if (document.getElementById(whichPart + "_del").checked == true) {
			currentPartsforDeletion.push(whichPart);
		} else {
			currentPartsforDeletion.pop(whichPart);
		}
	}
	
	
	// Set the Proper Delete Button image
	if (currentPartsforDeletion.length > 0) {
		document.getElementById('button_delete').src = "images/button_delete_DIM.png";
	} else {
		document.getElementById('button_delete').src = "images/button_delete_OFF.png";
	}
}
function deleteParts(pricingView) {
	if (currentPartsforDeletion.length > 0) {
		if (currentPartsforDeletion.length == currentPartsList.length) {
			resetPage('SHOW');
		} else {
			// Delete Parts from the JavaScript Array
			for (i = 0; i <= (currentPartsforDeletion.length - 1); i++) {
				partToDelete = currentPartsforDeletion[i];
					
				for (n = 0; n <= (currentPartsList.length - 1); n++) {
					if (currentPartsList[n][0][0].enterednum.toUpperCase() == partToDelete.toUpperCase()) {
						currentPartsList.splice(n,1);
					}
				}
			}
			
			// Send Deletion List to the ColdFusion Function to Remove from the CF Array
			DWREngine._execute(_ajaxConfig._cfscriptLocation, null, 'deletethePart',currentPartsforDeletion,deletethePartRESULT);
			
			document.getElementById('button_delete').src = "images/button_delete_OFF.png";
			frm.SearchPartQty.value = 1;
			frm.SearchPartNum.focus();
		}
	} else {
		frm.SearchPartNum.focus();
	}
}

function createOrderFromList() {
	for (i = 0; i <= (currentPartsList.length - 1); i++) {
		if (currentPartsList[i][0][0].searchmode == "EXACT") {
			for (n = 1; n <= currentPartsList[i][0][1].qty; n++) {
				document.PartsListListForm.partNum.value = document.PartsListListForm.partNum.value + "," + currentPartsList[i][0][1].partnum;
			}
		}
	}
	document.PartsListListForm.partNum.value = document.PartsListListForm.partNum.value.replace(",","");
	//alert(document.PartsListListForm.partNum.value);
	return true;
}

function saveOrder(whichAction,whichDealer,orderName) {
	if (whichAction == "SHOW") {
		document.getElementById('SaveOrderSkirt').style.visibility = 'visible';
		document.getElementById('SaveOrderPanel').style.visibility = 'visible';
		document.getElementById('SaveOrderSkirt').style.height     = '800px';
		document.ordername.newcartname.focus();
	}
	if (whichAction == "CANCEL") {
		document.getElementById('SaveOrderSkirt').style.visibility = 'hidden';
		document.getElementById('SaveOrderPanel').style.visibility = 'hidden';
		document.getElementById('SaveOrderSkirt').style.height     = '0px';
	}
	if (whichAction == "DONE") {
		// Save the Order
		DWREngine._execute(_ajaxConfig._cfscriptLocation, null, 'saveAnOrder', whichDealer, orderName, saveOrderResults);
	}
}
function saveOrderResults(r) {
	var windowHeight  = getWindowHeight();
	thePanel          = document.getElementById("SaveOrderPanel").style;
	var theOpacity    = 100;
	
	// Update the Panel
	document.getElementById('saveordercontent').innerHTML = "<center><font class='ResultsLarge'>Your order has been saved.</font></center>";
	
	// Fade the Panel
	thePanel.opacity      = (theOpacity / 100); 
	thePanel.MozOpacity   = (theOpacity / 100); 
	thePanel.KhtmlOpacity = (theOpacity / 100); 
	thePanel.filter       = "alpha(opacity=" + theOpacity + ")";
	thePanel.visibility   = 'visible';
	thePanel.top          = windowHeight + 'px';
	thePanel.height		  = '85px';
	
	setTimeout('fadeOutPanel("SaveOrderPanel","0")', 2000);
	fade = 0;
	
	document.getElementById('SaveOrderSkirt').style.visibility = 'hidden';
	//document.getElementById('SaveOrderPanel').style.visibility = 'hidden';
	document.getElementById('SaveOrderSkirt').style.height     = '0px';
}
function loadOrder(whichAction,whichCartID,fromWhere) {
	if (whichAction == "LOAD") {
		// Load the Order into the Order Form
		if (fromWhere == "POPUP") {
			DWREngine._execute(_ajaxConfig._cfscriptLocation, null, 'loadAnOrder', whichCartID, whichAction, loadOrderfromWindowResults);
		} else {
			DWREngine._execute(_ajaxConfig._cfscriptLocation, null, 'loadAnOrder', whichCartID, whichAction, loadOrderResults);
		}
	}
	if (whichAction == "CANCEL") {
		document.getElementById('LoadOrderSkirt').style.visibility = 'hidden';
		document.getElementById('LoadOrderPanel').style.visibility = 'hidden';
		document.getElementById('LoadOrderSkirt').style.height     = '0px';
	}
}
function loadOrderResults(r) {
	if (r[0] > 0) {
		top.location.href = "?CHAPTER=PARTS&PAGE=ORDERFORM";
	} else {
		var windowHeight = getWindowHeight();
		document.getElementById('LoadOrderSkirt').style.visibility = 'visible';
		document.getElementById('LoadOrderPanel').style.visibility = 'visible';
		document.getElementById('LoadOrderSkirt').style.height     = '100%';
		document.getElementById("LoadOrderPanel").style.top        = windowHeight + 'px';
	}
}
function loadOrderfromWindowResults(r) {
	opener.location.href = "../index.cfm?CHAPTER=PARTS&PAGE=ORDERFORM";
	window['popWin'].close();
}

function updateListTotals(pricingView) {
	theCurrentCol3Total = 0;
	theCurrentCol2Total = 0;
	anyProblemItems     = "NO";
	
	for (i=0; i <= (currentPartsList.length-1); i++) {
		theDealerCost      = currentPartsList[i][0][1].dlrcost;
		theDistributorCost = currentPartsList[i][0][1].dstcost;
		
		if (currentPartsList[i][0][1].dlrfp > 0) { theDealerCost      = currentPartsList[i][0][1].dlrfp; }
		if (currentPartsList[i][0][1].dlrbb > 0) { theDealerCost      = currentPartsList[i][0][1].dlrbb; }
		if (currentPartsList[i][0][1].dlrrh > 0) { theDealerCost      = currentPartsList[i][0][1].dlrrh; }
		
		if (currentPartsList[i][0][1].dstfp > 0) { theDistributorCost = currentPartsList[i][0][1].dstfp; }
		if (currentPartsList[i][0][1].dstbb > 0) { theDistributorCost = currentPartsList[i][0][1].dstbb; }
		if (currentPartsList[i][0][1].dstrh > 0) { theDistributorCost = currentPartsList[i][0][1].dstrh; }
		
		// These columns change based on the Viewing Mode and Selected Pricing View ///////
		if (currentPartsList[i][0][0].resultcount == 1 && currentPartsList[i][0][0].searchmode == "EXACT") {
			switch(pricingView) {
				case "NONE":
					// Column Headers are: Empty. We don't show any pricing to the general public.
					theCurrentCol2Total = "";
					theCurrentCol3Total = "";
					break;
				case "LIST":
					// Column Headers are: Item, Core, List
					theCurrentCol2Total = (theCurrentCol2Total + (currentPartsList[i][0][1].core * currentPartsList[i][0][1].qty));
					theCurrentCol3Total = (theCurrentCol3Total + (currentPartsList[i][0][1].list * currentPartsList[i][0][1].qty));
					break;
				case "DEAL":
					// Column Headers are: Item, Core, Deal
					theCurrentCol2Total = (theCurrentCol2Total + (currentPartsList[i][0][1].core * currentPartsList[i][0][1].qty));
					theCurrentCol3Total = (theCurrentCol3Total + (theDealerCost * currentPartsList[i][0][1].qty));
					break;
				case "DIST":
					// Column Headers are: Item, Deal, Dist
					theCurrentCol2Total = (theCurrentCol2Total + (currentPartsList[i][0][1].core * currentPartsList[i][0][1].qty));
					theCurrentCol3Total = (theCurrentCol3Total + (theDistributorCost * currentPartsList[i][0][1].qty));
					break;
				default:
					var theCurrentCol2Total = "ERR";
					var theCurrentCol3Total = "ERR";
					break;
			}
		} else {
			anyProblemItems = "YES";
		}
	}
	
	// Update the Totals
	document.getElementById("PartsListDLRTotal").innerHTML  = "<font class='PL_SM_Bold'>" + outputMoney(theCurrentCol2Total) + "</font>";
	document.getElementById("PartsListDISTTotal").innerHTML = "<font class='PL_SM_Bold'>" + outputMoney(theCurrentCol3Total) + "</font>";
	
	// Update the Buttons
	var finalizeButtonsSection = document.getElementById("finalizeButtons");
	
	if (anyProblemItems == "YES") {	
		finalizeButtonsSection.innerHTML = "<a class='ViewAll' href='#' target='_self' onClick='resetPage(\"SHOW\");'>Reset</a>";
		finalizeButtonsSection.innerHTML = finalizeButtonsSection.innerHTML + "<font class='AddtoOrderDISABLED'>Finalize Order</font><br /><br />";
		finalizeButtonsSection.innerHTML = finalizeButtonsSection.innerHTML + "<img src='images/icon_alert.png' width='15' height='15' border='0'>";
		finalizeButtonsSection.innerHTML = finalizeButtonsSection.innerHTML + "<b>There are items in the order that<br />require your attention before finalizing</b><br /><br />";
	} else {
		if (currentPartsList.length == 0) {
			finalizeButtonsSection.innerHTML = "<font class='ViewAllDISABLED'>Reset</font>";
			finalizeButtonsSection.innerHTML = finalizeButtonsSection.innerHTML + "<font class='AddtoOrderDISABLED'>Finalize Order</font><br /><br />";
		} else {
			finalizeButtonsSection.innerHTML = "<a class='ViewAll' href='#' target='_self' onClick='resetPage(\"SHOW\");'>Reset</a>";
			finalizeButtonsSection.innerHTML = finalizeButtonsSection.innerHTML + "<a class='AddtoOrder' href='?chapter=PARTS&page=CHECKOUT&p=1' target='_self'>Finalize Order</a><br /><br />";
		}
	}
	document.PartListTableForm.deleteSelectAll.disabled = false;
	//updateYellowBar();
}

function updateYellowBar() {
	if (document.getElementById("YellowBarContent")) {
		DWREngine._execute(_ajaxConfig._cfscriptLocation, null, 'refreshYellowBar', updateYellowBarResult);
	}
}
function updateYellowBarResult(r) {
	theCode   = "";

	// Sara made change on 1/2/2009 to take care of IE error
	// UPDATE (Jeff: 04/08/09):
	// Set yellowBar to "" when there is not a active special.
	// UPDATE (Jeff: 10/08/09):
	// Added test for existence of element before defining variable.
	
	//yellowBar = "";
	if (document.getElementById("YellowBarContent")) {
		yellowBar = document.getElementById("YellowBarContent");
	} else {
		yellowBar = "";
	}
	
	//END change


	if (r[0] == "ELECTRICAL") {
		yellowBarNeeded = 500.00;
		
		if (r[1] < yellowBarNeeded) {
			theCode = theCode + "<font face='arial' size='2' color='#000000'>Add " + outputMoney(yellowBarNeeded - r[1]) + " in eligible parts to qualify for the electrical free shipping special.</font>";
		} else {
			theCode = theCode + "<font face='arial' size='2' color='#660000'><b>Congratulations, this order qualifies for electrical free shipping special!</b></font>";
		}
		yellowBar.innerHTML = theCode;
	}
	
	if (r[0] == "AGCOPARTSFAIR") {
		AGCOPartsFairNeed_LVL1	= 2000.00;
		AGCOPartsFairNeed_LVL2	= 3000.00;
		AGCOPartsFairNeed_LVL3	= 4000.00;
		AGCOPartsFairNeed_LVL4	= 5000.00;
		
		
		theCode = theCode + "<font face='arial' size='2' color='#000000'>";
		if (r[1] <  AGCOPartsFairNeed_LVL1)                                  { theCode = theCode + "Add "             + outputMoney(AGCOPartsFairNeed_LVL1 - r[1]) + " in parts to reach Level 1. Currently in Order: " + outputMoney(r[1]); }
		if (r[1] >= AGCOPartsFairNeed_LVL1 && r[1] < AGCOPartsFairNeed_LVL2) { theCode = theCode + "At Level 1. Add " + outputMoney(AGCOPartsFairNeed_LVL2 - r[1]) + " in parts to reach Level 2. Currently in Order: " + outputMoney(r[1]); }
		if (r[1] >= AGCOPartsFairNeed_LVL2 && r[1] < AGCOPartsFairNeed_LVL3) { theCode = theCode + "At Level 2. Add " + outputMoney(AGCOPartsFairNeed_LVL3 - r[1]) + " in parts to reach Level 3. Currently in Order: " + outputMoney(r[1]); }
		if (r[1] >= AGCOPartsFairNeed_LVL3 && r[1] < AGCOPartsFairNeed_LVL4) { theCode = theCode + "At Level 3. Add " + outputMoney(AGCOPartsFairNeed_LVL4 - r[1]) + " in parts to reach Level 4. Currently in Order: " + outputMoney(r[1]); }
		if (r[1] >= AGCOPartsFairNeed_LVL4)                                  { theCode = theCode + "<b>Congratulations, you have reached Level 4 of the Rewards Program.</b>"                                                              ; }
		theCode = theCode + "</font>";
		
		yellowBar.innerHTML = theCode;
	}
	
	if (r[0] == "WINTERSPECIAL") {
		WinterSpecialNeed_LVL1	= 2500.00;
		WinterSpecialNeed_LVL2	= 999999.00;
		WinterSpecialNeed_LVL3	= 999999.00;
		WinterSpecialNeed_LVL4	= 999999.00;
		
		
		theCode = theCode + "<font face='arial' size='2' color='#000000'>";
		if (r[1] <  WinterSpecialNeed_LVL1)                                  { theCode = theCode + "Add "             + outputMoney(WinterSpecialNeed_LVL1 - r[1]) + " in eligible parts to qualify. Currently in Order: " + outputMoney(r[1]); }
		if (r[1] >= WinterSpecialNeed_LVL1 && r[1] < WinterSpecialNeed_LVL2) { theCode = theCode + "Congratulations, this order qualifies for the promotion. Currently in Order: " + outputMoney(r[1]); }
		if (r[1] >= WinterSpecialNeed_LVL2 && r[1] < WinterSpecialNeed_LVL3) { theCode = theCode + "At Level 2. Add " + outputMoney(WinterSpecialNeed_LVL3 - r[1]) + " in parts to reach Level 3. Currently in Order: " + outputMoney(r[1]); }
		if (r[1] >= WinterSpecialNeed_LVL3 && r[1] < WinterSpecialNeed_LVL4) { theCode = theCode + "At Level 3. Add " + outputMoney(WinterSpecialNeed_LVL4 - r[1]) + " in parts to reach Level 4. Currently in Order: " + outputMoney(r[1]); }
		if (r[1] >= WinterSpecialNeed_LVL4)                                  { theCode = theCode + "<b>Congratulations, you have reached Level 4 of the Rewards Program.</b>"                                                              ; }
		theCode = theCode + "</font>";
		
		yellowBar.innerHTML = theCode;
	}
	
	if (r[0] == "ACSPECIAL") {
		ACSpecial_LVL1 = 800.00;
		ACSpecial_LVL2 = 1200.00;
		ACSpecial_LVL3 = 1600.00;
		
		theCode = theCode + "<font face='arial' size='2' color='#000000'>";
		if (r[1] < ACSpecial_LVL1) 							 { theCode = theCode + "Add " + outputMoney(ACSpecial_LVL1 - r[1]) + " in eligible parts to qualify. Currently in Order: " + outputMoney(r[1]); }
		if (r[1] >= ACSpecial_LVL1 && r[1] < ACSpecial_LVL2) { theCode = theCode + "This order qualifies for a 4% discount. Currently in Order: " + outputMoney(r[1]); }
		if (r[1] >= ACSpecial_LVL2 && r[1] < ACSpecial_LVL3) { theCode = theCode + "This order qualifies for a 6% discount. Currently in Order: " + outputMoney(r[1]); }
		if (r[1] >= ACSpecial_LVL3)							 { theCode = theCode + "This order qualifies for a 8% discount and free shipping on eligible parts. Currently in Order: " + outputMoney(r[1]); }
		theCode = theCode + "</font>";
		
		yellowBar.innerHTML = theCode;
	}
}

function setSpecialOption(whichOption) {
	DWREngine._execute(_ajaxConfig._cfscriptLocation, null, 'setSpecialOption', whichOption, setSpecialOptionResult);
}
function setSpecialOptionResult(r) {
	if (r == "FreeShipping") {
		document.getElementById("SelectedOffer_FreeShipping").innerHTML            = "Selected Special";
		document.getElementById("SelectedOffer_FreeShipping").className            = "AddtoOrder";
		document.getElementById("SelectedOffer_FreeShipping").href = "#";
		
		document.getElementById("SelectedOffer_ACSpecial").innerHTML            = "Select This Special Instead";
		document.getElementById("SelectedOffer_ACSpecial").className            = "ViewAll";
		document.getElementById("SelectedOffer_ACSpecial").href = "javascript:setSpecialOption('ACSpecial');";
	}
	if (r == "ACSpecial") {
		document.getElementById("SelectedOffer_FreeShipping").innerHTML            = "Select This Special Instead";
		document.getElementById("SelectedOffer_FreeShipping").className            = "ViewAll";
		document.getElementById("SelectedOffer_FreeShipping").href = "javascript:setSpecialOption('FreeShipping');";
		
		document.getElementById("SelectedOffer_ACSpecial").innerHTML            = "Selected Special";
		document.getElementById("SelectedOffer_ACSpecial").className            = "AddtoOrder";
		document.getElementById("SelectedOffer_ACSpecial").href = "#";
	}
}

/*
function updateAGCOPartsFair() {
	DWREngine._execute(_ajaxConfig._cfscriptLocation, null, 'refreshYellowBar', updateYellowBarResult);
	//DWREngine._execute(_ajaxConfig._cfscriptLocation, null, 'refreshAGCOPartsFair', updateYellowBarResult);
}

function updateAGCOPartsFairResult(r) {
	if (r) {
		yellowBar               = document.getElementById("YellowBarContent");
		AGCOPartsFairNeed_LVL1	= 2000.00;
		AGCOPartsFairNeed_LVL2	= 3000.00;
		AGCOPartsFairNeed_LVL3	= 4000.00;
		AGCOPartsFairNeed_LVL4	= 5000.00;
		
		theCode = "";
		theCode = theCode + "<font face='arial' size='2' color='#000000'>";
		if (r <  AGCOPartsFairNeed_LVL1)                               { theCode = theCode + "Add "             + outputMoney(AGCOPartsFairNeed_LVL1 - r) + " in parts to reach Level 1. Currently in Order: " + outputMoney(r); }
		if (r >= AGCOPartsFairNeed_LVL1 && r < AGCOPartsFairNeed_LVL2) { theCode = theCode + "At Level 1. Add " + outputMoney(AGCOPartsFairNeed_LVL2 - r) + " in parts to reach Level 2. Currently in Order: " + outputMoney(r); }
		if (r >= AGCOPartsFairNeed_LVL2 && r < AGCOPartsFairNeed_LVL3) { theCode = theCode + "At Level 2. Add " + outputMoney(AGCOPartsFairNeed_LVL3 - r) + " in parts to reach Level 3. Currently in Order: " + outputMoney(r); }
		if (r >= AGCOPartsFairNeed_LVL3 && r < AGCOPartsFairNeed_LVL4) { theCode = theCode + "At Level 3. Add " + outputMoney(AGCOPartsFairNeed_LVL4 - r) + " in parts to reach Level 4. Currently in Order: " + outputMoney(r); }
		if (r >= AGCOPartsFairNeed_LVL4)                               { theCode = theCode + "<b>Congratulations, you have reached Level 4 of the Rewards Program.</b>"                                   ; }
		theCode = theCode + "</font>";
		
		yellowBar.innerHTML = theCode;
	} else {
		theCode = "";
		theCode = theCode + "<font face='arial' size='2' color='#000000'>";
		theCode = theCode + "Add $2000.00 in parts to reach Level 1. Currently in Order: $0.00";
		theCode = theCode + "</font>";
		
		yellowBar.innerHTML = theCode;
	}
}
*/


// DESCRIPTION PANEL STUFF ////////////////////////////////////////////////////////////////////////
function showDescription(whichRow) {
	//Tip(currentPartsList[(whichRow-2)][0][1].desc);
}

// MULTIPLE FOUND PARTS STUFF /////////////////////////////////////////////////////////////////////
function openMultiple(enteredpartnum,whichPart,whichQty,whichAction) {
	if (whichAction == "DISPLAY") {
		DWREngine._execute(_ajaxConfig._cfscriptLocation, null, 'displayMultipleMatches', enteredpartnum, whichQty, displayMultipleResults);
	}
	if (whichAction == "DELETE") {
		// Delete Parts from the JavaScript Array
		currentPartsforDeletion.push(enteredpartnum);
		
		for (i = 0; i <= (currentPartsforDeletion.length - 1); i++) {
			partToDelete = currentPartsforDeletion[i];
				
			for (n = 0; n <= (currentPartsList.length - 1); n++) {
				if (currentPartsList[n][0][0].enterednum.toUpperCase() == partToDelete.toUpperCase()) {
					currentPartsList.splice(n,1);
				}
			}
		}
		
		// Send Deletion List to the ColdFusion Function to Remove from the CF Array
		DWREngine._execute(_ajaxConfig._cfscriptLocation, null, 'deletethePart', currentPartsforDeletion, deletethePartRESULT);
		thePanel.style.visibility = "hidden";
	}
	if (whichAction == "CANCEL") {
		thePanel.style.visibility = "hidden";
	}
	if (whichAction == "SELECT") {
		// Add the Selected Part
		DWREngine._execute(_ajaxConfig._cfscriptLocation, null, 'addPartFunction', 'USA', whichPart, whichQty, 'ADDPART', addPartResult);
		
		// Delete the incomplete entry from the Order
		openMultiple(enteredpartnum,whichPart,whichQty,"DELETE");
	}
}
function displayMultipleResults(r) {
	thePanel = document.getElementById("MultiplePanel");
	theBody  = document.getElementById("MultiBody");
	theFoot  = document.getElementById("MultiFoot");
	
	thePanel.style.visibility = "visible";
	
	// Draw the Contents
	theCode = "";
	theCode = theCode + "<font class='ResultsSmall'><b>Your Search for: " + r[0].enterednum.toUpperCase() + " found these possible matches.</b></font><br>";
	theCode = theCode + "<div id='MultiResults' style='padding:5px;height:240px;border:solid 1px;overflow-y:auto;'>";
	
	theCode = theCode + "<table width='325' cellspacing='0' cellpadding='0' border='0'>";
	
	for (i=1; i <= (r.length-1); i++) {
		if (i % 2 == 0) {
			var theColor = "#EEEEEE"
		} else {
			var theColor = "#FFFFFF";
		}
		
		//theCode = theCode + "<span style=''>";
		
		
		
		if (r[i].obsolete == "NO") {
			//theCode = theCode + "<span style='background-color:" + theColor + ";width:100px;height:15px;float:left;'>";
			theCode = theCode + "<tr><td width='100' align='left'>";
			theCode = theCode + "<a href='javascript:openMultiple(\"" + r[0].enterednum + "\",\"" + r[i].partnum.toUpperCase() + "\",\"" + r[0].enteredqty + "\",\"SELECT\");'>";
			theCode = theCode + "<font class='ResultSmall'><b>" + r[i].partnum.toUpperCase() + "</b></font>";
			theCode = theCode + "</a>";
			//theCode = theCode + "</span>";
			theCode = theCode + "</td><td width='225' align='left'>";
			//theCode = theCode + "<span style='background-color:" + theColor + ";width:225px;height:15px;float:left;'>"
			theCode = theCode + "<font class='ResultsSmall'>" + r[i].desc + "</font>";
			//theCode = theCOde + "</span>";
			theCode = theCode + "</td></tr>";
		} else {
			//theCode = theCode + "<span style='background-color:" + theColor + ";width:100px;height:15px;float:left;'>";
			theCode = theCode + "<tr><td width='100' align='left'>";
			theCode = theCode + "<font class='ResultsSmall'><font color='#666666'><b>" + r[i].partnum.toUpperCase() + "</b></font></font>";
			//theCode = theCode + "</span>";
			theCode = theCode + "</td><td width='225' align='left'>";
			//theCode = theCode + "<span style='background-color:" + theColor + ";width:225px;height:15px;float:left;'>";
			theCode = theCode + "<font class='ResultsSmall'><font color='#666666'>" + r[i].desc + "</font></font>";
			//theCode = theCode + "</span>";
			theCOde = theCode + "</td></tr>";
		}
		
		
		//theCode = theCode + "</span>";
	}
	
	theCode = theCode + "</table>";
	
	theCode = theCode + "</div>";
	theBody.innerHTML = theCode;
	
	// Draw the buttons
	theCode = "";
	theCode = theCode + "<div style='float:left;'><a href='javascript:openMultiple(\"" + r[0].enterednum + "\",\"\",\"\",\"DELETE\");' class='ViewAll'>Delete Result from the Order</a></div>";
	theCode = theCode + "<div style='float:right;'><a href='javascript:openMultiple(\"\",\"\",\"\",\"CANCEL\");' class='AddtoOrder'>Cancel</a></div>";
	
	theFoot.innerHTML = theCode;
}


// GET DATA AND LISTENER FUNCTIONS ////////////////////////////////////////////////////////////////
function showTYPs(whichMFG,whichLine,TYPList) {
	n     = navigator.userAgent.toLowerCase(),
	tt_ie = n.indexOf("msie") != -1 && document.all;
	if(tt_ie) {
		whichMultiplier = 16;
	} else {
		whichMultiplier = 17;
	}
	doMenu('PartsMenu_MODs','HIDE');
	var menuContents = "<ul class='MFGs'>";
	document.getElementById("PartsMenu_TYPs").innerHTML = "";
	
	TYPList = TYPList.split(",");
	
	for (i=0; i <= (TYPList.length-1); i++) {
		menuContents = menuContents + "<li id='MFGs' class='MFGs' title='" + TYPList[i] + "_TYP'>";
		
		if (TYPList[i] == "Show All") {
			menuContents = menuContents + "<a class='PartsMenu' style='display:block;background-color:#DD7711;color:#FFFFFF;' href='index.cfm?chapter=PARTS&page=SEARCH&MFG="+ whichMFG + "&TYP=" + TYPList[i] + "'";
		} else {
			menuContents = menuContents + "<a class='PartsMenu' href='index.cfm?chapter=PARTS&page=SEARCH&MFG="+ whichMFG + "&TYP=" + TYPList[i] + "'";
		}
		
		menuContents = menuContents + "onmouseover=\"showMODs('" + whichMFG + "',";
		menuContents = menuContents + "'" + TYPList[i] + "',";
		menuContents = menuContents + "'" + whichLine + "','" + i + "');\">";
		menuContents = menuContents + TYPList[i] + "</a></li>";
	}
	menuContents = menuContents + "</ul>";
	
	document.getElementById("PartsMenu_TYPs").innerHTML = menuContents;
	document.getElementById("PartsMenu_TYPs").style.top = (36 + (whichLine*whichMultiplier) + 'px');
	document.getElementById("PartsMenu_TYPs").style.visibility = 'visible';
}

function showMODs(whichMFG,whichTYP,whichMFGLine,whichTYPLine) {
	/*
	n     = navigator.userAgent.toLowerCase(),
	tt_ie = n.indexOf("msie") != -1 && document.all;
	if(tt_ie) {
		whichMultiplier = 16;
	} else {
		whichMultiplier = 17;
	}
	
	var menuContents = "<ul class='MFGs'>";
	document.getElementById("PartsMenu_MODs").innerHTML = "";
	
	MODList = MODList.split(",");
	
	for (i=0; i <= (MODList.length-1); i++) {
		menuContents = menuContents + "<li id='MFGs' class='MFGs' title='" + MODList[i] + "_MOD'>";
		menuContents = menuContents + "<a class='PartsMenu' href='?chapter=PARTS&page=SEARCH&MFG=" + whichMFG + "&TYP=" + whichTYP + "&MOD=" + MODList[i] + "'>" + MODList[i] + "</a></li>";
	}
	menuContents = menuContents + "</ul>";

	document.getElementById("PartsMenu_MODs").innerHTML = menuContents;
	document.getElementById("PartsMenu_MODs").style.top = (36 + ((whichMFGLine*whichMultiplier) + (whichTYPLine*whichMultiplier)) + 'px');
	document.getElementById("PartsMenu_MODs").style.visibility = 'visible';
	*/
}

/*
function showMODs(whichMFG,whichTYP) {
	DWREngine._execute(_ajaxConfig._cfscriptLocation, null, 'getMODs', whichMFG, whichTYP, showMODsResult);
}

function showMODsResult(r) {
	n     = navigator.userAgent.toLowerCase(),
	tt_ie = n.indexOf("msie") != -1 && document.all;
	if(tt_ie) {
		whichMultiplier = 16;
	} else {
		whichMultiplier = 17;
	}
	
	var menuContents = "<ul class='MFGs'>";
	document.getElementById("PartsMenu_MODs").innerHTML = "";
	
	for (i=2; i <= (r.length-1); i++) {
		menuContents = menuContents + "<li id='MFGs' class='MFGs' title='" + r[i] + "_MOD'><a class='PartsMenu' href=''>" + r[i] + "</a></li>";
		 //menuContents = menuContents + r[i] + "<br />";
	}
	menuContents = menuContents + "</ul>";
	
	document.getElementById("PartsMenu_MODs").innerHTML = menuContents;
	document.getElementById("PartsMenu_MODs").style.visibility='visible';
}
*/

// ADDRESS BOOK EDIT PANEL FUNCTIONS //////////////////////////////////////////////////////////////
function editOrderEmailAddress(whichDealer) {
	var theCode   = "";
	var editPanel = document.getElementById('ordersEmail');
	
	theCode = theCode + "<font face='arial' size='2' color='333333'><b>";
	theCode = theCode + "<form name='editEmailAddressForm'><input type='hidden' name='dealercode' value='" + whichDealer + "'>Change the e-mail address to: <input type='text' name='emailAddress1' value='' size='25' style='margin-right:10px;'>";
	theCode = theCode + " Verify: <input type='text' name='emailAddress2' value='' size='25'><a href='javascript:submitEditEmailForm();' target='_self' class='AddtoOrder' style='margin-left:10px;'>Change Address</a></form>";
	theCode = theCode + "</b></font>";
	
	editPanel.innerHTML = theCode;
	
	document.editEmailAddressForm.emailAddress1.focus();
}
function submitEditEmailForm(which,whichAction) {
	var email1  = document.editEmailAddressForm.emailAddress1.value;
	var email2  = document.editEmailAddressForm.emailAddress2.value;
	var readytogo = "YES";
	
	if (which == "REWARDS") {
		if (whichAction == "YES") {
			if (email1 == email2) {
				if (isblank(email1)) {
					alert("The fields cannot be empty.");
					document.editEmailAddressForm.emailAddress1.focus();
					readytogo = "NO";
				}
				if (!isEmail(email1)) {
					alert("The E-Mail Address does not appear to be valid.");
					document.editEmailAddressForm.emailAddress1.focus();
					readytogo = "NO";
				}
			} else {
				alert("The E-Mail Address fields do not match.");
				document.editEmailAddressForm.emailAddress1.focus();
				readytogo = "NO";
			}
		}
	} else {
		if (email1 == email2) {
			if (isblank(email1)) {
				alert("The fields cannot be empty.");
				document.editEmailAddressForm.emailAddress1.focus();
				readytogo = "NO";
			}
			if (!isEmail(email1)) {
				alert("The E-Mail Address does not appear to be valid.");
				document.editEmailAddressForm.emailAddress1.focus();
				readytogo = "NO";
			}
		} else {
			alert("The E-Mail Address fields do not match.");
			document.editEmailAddressForm.emailAddress1.focus();
			readytogo = "NO";
		}
	}
	
	if (readytogo == "YES") {
		var whichDealer  = document.editEmailAddressForm.dealercode.value;
		var whichAddress = document.editEmailAddressForm.emailAddress1.value;
		
		if (which == "REWARDS") {
			DWREngine._execute(_ajaxConfig._cfscriptLocation, null, 'updateOrderEmailAddress', whichDealer, whichAddress, whichAction, closePanel);
		} else if (which == "REGFORM") {
			DWREngine._execute(_ajaxConfig._cfscriptLocation, null, 'updateOrderEmailAddress', whichDealer, whichAddress, "REWARDSREG", regFormResults);
		} else {
			DWREngine._execute(_ajaxConfig._cfscriptLocation, null, 'updateOrderEmailAddress', whichDealer, whichAddress, editEmailResults);
		}
	}
}

function closePanel(r) {
	document.getElementById('EditEmailSkirt').style.visibility = 'hidden';
	document.getElementById('EditEmailPanel').style.visibility = 'hidden';
}

function editEmailResults(r) {
	if (r[0] != "ERROR") {
		var editPanel = document.getElementById('ordersEmail');
		var theCode   = "";
		
		theCode = theCode + "<font face='arial' size='2' color='333333'><b>";
		theCode = theCode + "Copies of your web site orders will be e-mailed to: " + r[0] + ".";
		theCode = theCode + "<a href='javascript:editOrderEmailAddress(\'" + r[1] +"\');' target='_self' class='ViewAll' style='margin-left:10px;'>Edit This</a>";
		theCode = theCode + "</b></font>";
		
		editPanel.innerHTML = theCode;
	}
}

function regFormResults(r) {
	if (r[0] != "ERROR") {
		var editPanel = document.getElementById('regFormContent');
		var theCode   = "";
		
		theCode = theCode + "<center><font face='arial' size='2' color='333333'><b>Congratulations!</b></font><br>";
		theCode = theCode + "<b>You are now enrolled in the Rewards program.</b></center>";
		
		editPanel.innerHTML = theCode;
	}
}

function doAddressPanel(whichAction,whichEdit,whichDealer,whichID) {
	if (whichAction == "SHOW") {
		if (whichEdit == "NEW") {
			// Make sure the fields are all empty
			for(i=0; i<document.editAddress.elements.length; i++) {
				document.editAddress.elements[i].value = "";
			}
			document.getElementById('addressEditTitle').innerHTML = "Entering a New Address";
			document.editAddress.theAddressID.value     = whichID;
			document.editAddress.theAddressAction.value = 'NEW';
		}
		if (whichEdit == "EDIT") {
			document.getElementById('addressEditTitle').innerHTML = "Editing an Address";
			document.editAddress.theAddressID.value     = whichID;
			document.editAddress.theAddressAction.value = 'EDIT';
			
			// Retrieve the address details using the Address ID
			DWREngine._execute(_ajaxConfig._cfscriptLocation, null, 'getAddress', whichDealer, whichID, populateAddressFields);
		}
		document.getElementById('AddressEditSkirt').style.visibility = 'visible';
		document.getElementById('AddressEditPanel').style.visibility = 'visible';
		document.getElementById('AddressEditSkirt').style.height     = '100%';
		document.getElementById('AddressEditSkirt').style.width      = '775px';
		
		var ns = (navigator.appName.indexOf("Netscape") != -1); 
		var pY = ns ? pageYOffset : document.documentElement && document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop; 
		document.getElementById('AddressEditPanel').style.top = (pY-50) + 'px';
		document.editAddress.firstname.focus();
	}
	if (whichAction == "HIDE") {
		document.getElementById('AddressEditSkirt').style.visibility = 'hidden';
		document.getElementById('AddressEditPanel').style.visibility = 'hidden';
		document.getElementById('AddressEditSkirt').style.height     = '0px';
	}
}
function populateAddressFields(r) {
	var form = document.editAddress;
	
	if (r[0].status != "ERROR" && r[0].status != 0) {
		form.firstname.value    = r[0].firstname;
		form.middlename.value   = r[0].middlename;
		form.lastname.value     = r[0].lastname;
		form.companyname.value  = r[0].custname;
		form.address1.value     = r[0].address1;
		form.address2.value     = r[0].address2;
		form.city.value         = r[0].city;
		form.state.value        = r[0].state;
		form.zipcode.value      = r[0].zipcode      != 0 ? r[0].zipcode      : "";
		form.zip4.value         = r[0].zip4         != 0 ? r[0].zip4         : "";
		form.dphonearea.value   = r[0].dphonearea   != 0 ? r[0].dphonearea   : "";
		form.dphonepre.value    = r[0].dphonepre    != 0 ? r[0].dphonepre    : "";
		form.dphonenumber.value = r[0].dphonenumber != 0 ? r[0].dphonenumber : "";
		form.dphoneext.value    = r[0].dphoneext    != 0 ? r[0].dphoneext    : "";
		form.nphonearea.value   = r[0].nphonearea   != 0 ? r[0].nphonearea   : "";
		form.nphonepre.value    = r[0].nphonepre    != 0 ? r[0].nphonepre    : "";
		form.nphonenumber.value = r[0].nphonenumber != 0 ? r[0].nphonenumber : "";
		form.nphoneext.value    = r[0].nphoneext    != 0 ? r[0].nphoneext    : "";
		form.faxarea.value      = r[0].faxarea      != 0 ? r[0].faxarea      : "";
		form.faxpre.value       = r[0].faxpre       != 0 ? r[0].faxpre       : "";
		form.faxnumber.value    = r[0].faxnumber    != 0 ? r[0].faxnumber    : "";
		form.email1.value       = r[0].email;
		form.email2.value       = r[0].email;
	}
}

function saveAddress(whichEditPanel,whichDealer) {
	if (whichEditPanel == "ADDRESSBOOK") { var form = document.editAddress; }
	if (whichEditPanel == "CHECKOUT")    { var form = document.CheckoutTableForm; }
	
	var newAddress = new Array();
	
	newAddress[0]  = form.firstname.value;
	newAddress[1]  = form.middlename.value;
	newAddress[2]  = form.lastname.value;
	newAddress[3]  = form.companyname.value;
	newAddress[4]  = form.address1.value;
	newAddress[5]  = form.address2.value;
	newAddress[6]  = form.city.value;
	newAddress[7]  = form.state.value;
	newAddress[8]  = form.zipcode.value;
	newAddress[9]  = form.zip4.value;
	newAddress[10]  = form.dphonearea.value;
	newAddress[11] = form.dphonepre.value;
	newAddress[12] = form.dphonenumber.value;
	newAddress[13] = form.dphoneext.value;
	
	if (whichEditPanel == "ADDRESSBOOK") {
		newAddress[14] = form.nphonearea.value;
		newAddress[15] = form.nphonepre.value;
		newAddress[16] = form.nphonenumber.value;
		newAddress[17] = form.nphoneext.value;
		newAddress[18] = form.faxarea.value;
		newAddress[19] = form.faxpre.value;
		newAddress[20] = form.faxnumber.value;
		newAddress[21] = form.email1.value;
	}
	if (whichEditPanel == "CHECKOUT") {
		newAddress[14] = 0;
		newAddress[15] = 0;
		newAddress[16] = 0;
		newAddress[17] = 0;
		newAddress[18] = 0;
		newAddress[19] = 0;
		newAddress[20] = 0;
		newAddress[21] = "NA";
	}
	
	if (whichEditPanel == "ADDRESSBOOK") {
		DWREngine._execute(_ajaxConfig._cfscriptLocation, null, 'saveAddress', whichDealer, form.theAddressID.value, newAddress, form.theAddressAction.value, saveAddressBookResult);
	}
	if (whichEditPanel == "CHECKOUT") {
		DWREngine._execute(_ajaxConfig._cfscriptLocation, null, 'saveAddress', whichDealer, form.theAddressID.value, newAddress, form.theAddressAction.value, saveAddressCheckoutResult);
	}
}
function saveAddressBookResult(r) {
	doAddressPanel("HIDE");
	location.reload(true);
}
function saveAddressCheckoutResult(r) {
	alert("The address has been saved to your Address Book.");
}
function doAddressDelete(whichAction,whichDealer,whichAddressID) {
	if (whichAction == "SHOW") {
		document.getElementById('AddressDeleteSkirt').style.visibility              = 'visible';
		document.getElementById('AddressDeleteConfirmationDialog').style.visibility = 'visible';
		document.getElementById('AddressDeleteSkirt').style.height                  = '100%';
		document.getElementById('AddressDeleteSkirt').style.width                   = '775px';
		
		var ns = (navigator.appName.indexOf("Netscape") != -1); 
		var pY = ns ? pageYOffset : document.documentElement && document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop; 
		document.getElementById('AddressDeleteConfirmationDialog').style.top = (pY-50) + 'px';
			
		document.deleteAddress.theDealerID.value  = whichDealer;
		document.deleteAddress.theAddressID.value = whichAddressID;
		
		// Retrieve the address details using the Address ID
		DWREngine._execute(_ajaxConfig._cfscriptLocation, null, 'getAddress', whichDealer, whichAddressID, doAddressDeleteResult);
	}
	if (whichAction == "HIDE") {
		document.getElementById('AddressDeleteSkirt').style.visibility = 'hidden';
		document.getElementById('AddressDeleteConfirmationDialog').style.visibility = 'hidden';
		document.getElementById('AddressDeleteSkirt').style.height     = '0px';
	}
	if (whichAction == "DELETE") {
		// Retrieve the address details using the Address ID
		DWREngine._execute(_ajaxConfig._cfscriptLocation, null, 'deleteAddress', document.deleteAddress.theDealerID.value, document.deleteAddress.theAddressID.value, saveAddressBookResult);
	}
}

function doAddressDeleteResult(r) {
	var theDayPhone   = "(" + r[0].dphonearea + ") " + r[0].dphonepre + "-" + r[0].dphonenumber + (r[0].dphoneext!=0?" ext. " + r[0].dphoneext:"");
	if (r[0].nphonearea == 0) {
		var theNightPhone = "";
	} else {
		var theNightPhone = "(" + r[0].nphonearea + ") " + r[0].nphonepre + "-" + r[0].nphonenumber + (r[0].nphoneext!=0?" ext. " + r[0].nphoneext:"");
	}
	if (r[0].faxarea == 0) {
		var theFax = "";
	} else {
		var theFax = "(" + r[0].faxarea    + ")"  + r[0].faxpre    + "-" + r[0].faxnumber;
	}
	if (r[0].zip4 == 0) {
		theZipCode = r[0].zipcode;
	} else {
		theZipCode = r[0].zipcode + "-" + r[0].zip4;
	}
	var theAddress    = "";
	
	theAddress =              "<font class='ResultsLarge'>" + r[0].firstname + " " + r[0].middlename + " " + r[0].lastname  + "</font><br>";
	theAddress = theAddress + "<font class='ResultsSmall'>" + r[0].custname                                                 + "</font><br>";
	theAddress = theAddress + "<font class='ResultsSmall'>" + r[0].address1                                                 + "</font><br>";
	theAddress = theAddress + "<font class='ResultsSmall'>" + r[0].address2                                                 + "</font><br>";
	theAddress = theAddress + "<font class='ResultsSmall'>" + r[0].city + ", " + r[0].state + " " + theZipCode              + "</font><br><br>";
	theAddress = theAddress + "<font class='ResultsSmall'>" + theDayPhone                                                   + "</font><br>";
	theAddress = theAddress + "<font class='ResultsSmall'>" + theNightPhone                                                 + "</font><br>";
	theAddress = theAddress + "<font class='ResultsSmall'>" + theFax                                                        + "</font><br>";
	theAddress = theAddress + "<font class='ResultsSmall'>" + r[0].email                                                    + "</font><br>";

	document.getElementById('addressDisplay').innerHTML = theAddress;
}

function doAddressSetDefault(whichDealer,whichAddressID) {
	DWREngine._execute(_ajaxConfig._cfscriptLocation, null, 'setDefaultAddress', whichDealer, whichAddressID, saveAddressResult);
}

function doSelectAddress(whichEditPanel,whichAction,whichAddressID,whichDealer) {
		if (whichAction == "SHOW") {
			document.getElementById('shippingCarrier').style.visibility    = "hidden"; 
			document.getElementById('SelectAddressSkirt').style.visibility = 'visible';
			document.getElementById('SelectAddressPanel').style.visibility = 'visible';
			document.getElementById('SelectAddressSkirt').style.height     = '100%';
			document.getElementById('SelectAddressSkirt').style.width      = '775px';
			
			var ns = (navigator.appName.indexOf("Netscape") != -1); 
			var pY = ns ? pageYOffset : document.documentElement && document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop; 
			document.getElementById('SelectAddressPanel').style.top = (pY-50) + 'px';
		
			// Retrieve the address details using the Address ID
			if (whichEditPanel == "ADDRESSBOOK") {
				DWREngine._execute(_ajaxConfig._cfscriptLocation, null, 'getAddress', whichDealer, whichAddressID, loadSelectAddressPanelADDRESSBOOK);
			}
			if (whichEditPanel == "CHECKOUT") {
				DWREngine._execute(_ajaxConfig._cfscriptLocation, null, 'getAddress', whichDealer, whichAddressID, loadSelectAddressPanelCHECKOUT);
			}
		}
		if (whichAction == "HIDE") {
			document.getElementById('shippingCarrier').style.visibility    = "visible"; 
			document.getElementById('SelectAddressSkirt').style.visibility = 'hidden';
			document.getElementById('SelectAddressPanel').style.visibility = 'hidden';
			document.getElementById('SelectAddressSkirt').style.height     = '0px';
		}
		if (whichAction == "SELECT") {
			document.getElementById('SelectAddressSkirt').style.visibility = 'hidden';
			document.getElementById('SelectAddressPanel').style.visibility = 'hidden';
			document.getElementById('SelectAddressSkirt').style.height     = '0px';
			
			// Set the session.SHIPTO variable to the selected address ID
			if (whichEditPanel == "ADDRESSBOOK") {
				DWREngine._execute(_ajaxConfig._cfscriptLocation, null, 'selectAddress', whichAddressID, closeAddressSelectResult);
			}
			if (whichEditPanel == "CHECKOUT") {
				DWREngine._execute(_ajaxConfig._cfscriptLocation, null, 'selectAddress', whichAddressID, loadCheckoutAddress);
			}
		}
		if (whichAction == "OPENBOOK") {
			document.getElementById('SelectAddressSkirt').style.visibility = 'hidden';
			document.getElementById('SelectAddressPanel').style.visibility = 'hidden';
			document.getElementById('SelectAddressSkirt').style.height     = '0px';
	
			top.location.href = "?CHAPTER=MYACCOUNT&PAGE=ADDRESSBOOK";
		}
}

function loadSelectAddressPanelADDRESSBOOK(r) {
	var theAddresses = "";
	
	for (i=0; i <= (r.length-1); i++) {
		var theDayPhone   = "(" + r[i].dphonearea + ") " + r[i].dphonepre + "-" + r[i].dphonenumber + (r[i].dphoneext!=0?" ext. " + r[i].dphoneext:"");
		if (r[i].nphonearea == 0) { 
			var theNightPhone = ""; 
		} else { 
			var theNightPhone = "(" + r[i].nphonearea + ") " + r[i].nphonepre + "-" + r[i].nphonenumber + (r[i].nphoneext!=0?" ext. " + r[i].nphoneext:""); 
		} 
		if (r[i].faxarea == 0) { 
			var theFax = ""; 
		} else { 
			var theFax = "(" + r[i].faxarea    + ")"  + r[i].faxpre    + "-" + r[i].faxnumber; 
		} 
		if (r[i].zip4 == 0) { 
			theZipCode = r[i].zipcode; 
		} else { 
			theZipCode = r[i].zipcode + "-" + r[i].zip4; 
		}
		
		if (i % 2 == 0) {
			var theColor = "#EEEEEE"
		} else {
			var theColor = "#FFFFFF";
		}
		
		var theAddress    = ""; 
		theAddress =              "<font class='ResultsLarge'>" + r[i].firstname + " " + r[i].middlename + " " + r[i].lastname  + "</font><br>"; 
		theAddress = theAddress + "<font class='ResultsSmall'>" + r[i].custname                                                 + "</font><br>"; 
		theAddress = theAddress + "<font class='ResultsSmall'>" + r[i].address1                                                 + "</font><br>"; 
		theAddress = theAddress + "<font class='ResultsSmall'>" + r[i].address2                                                 + "</font><br>"; 
		theAddress = theAddress + "<font class='ResultsSmall'>" + r[i].city + ", " + r[i].state + " " + theZipCode              + "</font><br><br>"; 
		theAddress = theAddress + "<font class='ResultsSmall'>" + theDayPhone                                                   + "</font><br>"; 
		theAddress = theAddress + "<font class='ResultsSmall'>" + theNightPhone                                                 + "</font><br>"; 
		theAddress = theAddress + "<font class='ResultsSmall'>" + theFax                                                        + "</font><br>"; 
		theAddress = theAddress + "<font class='ResultsSmall'>" + r[i].email                                                    + "</font><br>";
		
		theAddressRow = "";
		theAddressRow = "<div style='height:130px;'>";
		theAddressRow = theAddressRow + "<div style='width:273px;height:130px;padding:10px;float:left;text-align:left;background-color:" + theColor + "'>" + theAddress + "</div>";
		theAddressRow = theAddressRow + "<div style='width:50px;height:130px;padding:10px;float:right;text-align:right;background-color:" + theColor + "'><a href='javascript:doSelectAddress(\"ADDRESSBOOK\",\"SELECT\",\"" + r[i].addressid + "\");' class='AddtoOrder'>Select</a></div>";
		theAddressRow = theAddressRow + "</div><br>";
		
		theAddresses = theAddresses + theAddressRow;
	}
	document.getElementById('addresscontent').innerHTML = theAddresses;
}
function loadSelectAddressPanelCHECKOUT(r) {
	var theAddresses = "";
	
	for (i=0; i <= (r.length-1); i++) {
		var theDayPhone   = "(" + r[i].dphonearea + ") " + r[i].dphonepre + "-" + r[i].dphonenumber + (r[i].dphoneext!=0?" ext. " + r[i].dphoneext:"");
		if (r[i].nphonearea == 0) { 
			var theNightPhone = ""; 
		} else { 
			var theNightPhone = "(" + r[i].nphonearea + ") " + r[i].nphonepre + "-" + r[i].nphonenumber + (r[i].nphoneext!=0?" ext. " + r[i].nphoneext:""); 
		} 
		if (r[i].faxarea == 0) { 
			var theFax = ""; 
		} else { 
			var theFax = "(" + r[i].faxarea    + ")"  + r[i].faxpre    + "-" + r[i].faxnumber; 
		} 
		if (r[i].zip4 == 0) { 
			theZipCode = r[i].zipcode; 
		} else { 
			theZipCode = r[i].zipcode + "-" + r[i].zip4; 
		}
		
		if (i % 2 == 0) {
			var theColor = "#EEEEEE"
		} else {
			var theColor = "#FFFFFF";
		}
		
		var theAddress    = ""; 
		theAddress =              "<font class='ResultsLarge'>" + r[i].firstname + " " + r[i].middlename + " " + r[i].lastname  + "</font><br>"; 
		theAddress = theAddress + "<font class='ResultsSmall'>" + r[i].custname                                                 + "</font><br>"; 
		theAddress = theAddress + "<font class='ResultsSmall'>" + r[i].address1                                                 + "</font><br>"; 
		theAddress = theAddress + "<font class='ResultsSmall'>" + r[i].address2                                                 + "</font><br>"; 
		theAddress = theAddress + "<font class='ResultsSmall'>" + r[i].city + ", " + r[i].state + " " + theZipCode              + "</font><br><br>"; 
		theAddress = theAddress + "<font class='ResultsSmall'>" + theDayPhone                                                   + "</font><br>"; 
		theAddress = theAddress + "<font class='ResultsSmall'>" + theNightPhone                                                 + "</font><br>"; 
		theAddress = theAddress + "<font class='ResultsSmall'>" + theFax                                                        + "</font><br>"; 
		theAddress = theAddress + "<font class='ResultsSmall'>" + r[i].email                                                    + "</font><br>";
		
		theAddressRow = "";
		theAddressRow = "<div style='height:130px;'>";
		theAddressRow = theAddressRow + "<div style='width:273px;height:130px;padding:10px;float:left;text-align:left;background-color:" + theColor + "'>" + theAddress + "</div>";
		theAddressRow = theAddressRow + "<div style='width:50px;height:130px;padding:10px;float:right;text-align:right;background-color:" + theColor + "'><a href='javascript:doSelectAddress(\"CHECKOUT\",\"SELECT\",\"" + r[i].addressid + "\");' class='AddtoOrder'>Select</a></div>";
		theAddressRow = theAddressRow + "</div><br>";
		
		theAddresses = theAddresses + theAddressRow;
	}
	document.getElementById('addresscontent').innerHTML = theAddresses;
}
function closeAddressSelectResult(r) {
	doSelectAddress("HIDE");
	location.reload(true);
}
function loadCheckoutAddress(r) {
	doSelectAddress("HIDE");
	document.CheckoutTableForm.firstname.value    = r[0];
	document.CheckoutTableForm.middlename.value   = r[1];
	document.CheckoutTableForm.lastname.value     = r[2];
	document.CheckoutTableForm.companyname.value  = r[3];
	document.CheckoutTableForm.address1.value     = r[4];
	document.CheckoutTableForm.address2.value     = r[5];
	document.CheckoutTableForm.city.value         = r[6];
	document.CheckoutTableForm.state.value        = r[7];
	document.CheckoutTableForm.zipcode.value      = r[8];
	document.CheckoutTableForm.zip4.value         = r[9];
	document.CheckoutTableForm.dphonearea.value   = r[11];
	document.CheckoutTableForm.dphonepre.value    = r[12];
	document.CheckoutTableForm.dphonenumber.value = r[13];
	document.CheckoutTableForm.dphoneext.value    = r[14];
}
function emptyCheckoutAddressForm() {
	document.CheckoutTableForm.firstname.value    = "";
	document.CheckoutTableForm.middlename.value   = "";
	document.CheckoutTableForm.lastname.value     = "";
	document.CheckoutTableForm.companyname.value  = "";
	document.CheckoutTableForm.address1.value     = "";
	document.CheckoutTableForm.address2.value     = "";
	document.CheckoutTableForm.city.value         = "";
	document.CheckoutTableForm.state.value        = "";
	document.CheckoutTableForm.zipcode.value      = "";
	document.CheckoutTableForm.zip4.value         = "";
	document.CheckoutTableForm.dphonearea.value   = "";
	document.CheckoutTableForm.dphonepre.value    = "";
	document.CheckoutTableForm.dphonenumber.value = "";
	document.CheckoutTableForm.dphoneext.value    = "";
}

function validatePartRequestForm() {
	var form = document.PartRequestForm;
	
	// REQUIRED FIELDS
	if (incomplete(form.ContactName)) { return false; }
	if (incomplete(form.PhoneNumber)) { return false; }
	
	// SPECIAL CASES
	// E-Mail Address
	if (form.EMail.value != "NA" && form.EMail.value != "" && form.EMail.value != " ") {
		if (!isEmail(form.EMail.value)) {
			alert("The E-Mail Address does not appear to be valid.");
			form.EMail.focus();
			return false;
		}
	}
	return true;
}

function validateAddressPanel(whichEditPanel,whichDealer) {
	if (whichEditPanel == "ADDRESSBOOK") { var form = document.editAddress; }
	if (whichEditPanel == "CHECKOUT")    { var form = document.CheckoutTableForm; }
	
	// REQUIRED FIELDS									
	if (incomplete(form.firstname))			{return false;}
	if (incomplete(form.lastname))			{return false;}
	if (incomplete(form.address1))			{return false;}
	if (incomplete(form.city))				{return false;}
	if (incomplete(form.state))				{return false;}
	if (incomplete(form.zipcode))			{return false;}
	if (incomplete(form.dphonearea))		{return false;}
	if (incomplete(form.dphonepre))			{return false;}
	if (incomplete(form.dphonenumber))		{return false;}
	//if (incomplete(form.email1))     		{return false;}
	
	
	
	if (whichEditPanel == "ADDRESSBOOK") {
		// SPECIAL CASES
		// E-Mail Address
		var email1 = form.email1.value;
		var email2 = form.email2.value;
		
		if (isblank(email1) && isblank(email2)) {
			form.email1.value  = "NA";
			form.email2.value = "NA";
		} else {
			if (email1 == email2) {
				if (email1 != "NA" && email1 != "" && email1 != " ") {
					if (!isEmail(email1)) {
						alert("The E-Mail Address does not appear to be valid.");
						document.addressbook.email.focus();
						return false;
					}
				}
			} else {
				alert("The E-Mail Address fields do not match.");
				form.email.focus();
				return false;
			}
		}
	}
	//return true;
	//alert("Everything is ready to submit.");
	saveAddress(whichEditPanel,whichDealer);
}

function validateDealerManager(which) {
	if (which == "EDIT") { var form = document.DealerInfo; }
	if (which == "NEW")  { var form = document.NewDealer; }
	
	// Required Fields
	if (incomplete(form.DealerName))		{return false;}
	if (incomplete(form.ContactName))		{return false;}
	
	if (incomplete(form.DealerCode))		{return false;}
	if (incomplete(form.AgcoCode))			{return false;}
	if (incomplete(form.DistNum))			{return false;}
	if (incomplete(form.PriceRegion))		{return false;}
	if (incomplete(form.ProfitMargin))		{return false;}
	
	if (incomplete(form.SHIP_FirstName))	{return false;}
	if (incomplete(form.SHIP_LastName))		{return false;}
	if (incomplete(form.SHIP_CustName))		{return false;}
	if (incomplete(form.SHIP_Address1))		{return false;}
	if (incomplete(form.SHIP_City))			{return false;}
	if (incomplete(form.SHIP_State))		{return false;}
	if (incomplete(form.SHIP_Zip))			{return false;}
	if (incomplete(form.SHIP_Day_AreaCode))	{return false;}
	if (incomplete(form.SHIP_Day_Prefix))	{return false;}
	if (incomplete(form.SHIP_Day_Number))	{return false;}
	
	if (incomplete(form.BILL_FirstName))	{return false;}
	if (incomplete(form.BILL_LastName))		{return false;}
	if (incomplete(form.BILL_CustName))		{return false;}
	if (incomplete(form.BILL_Address1))		{return false;}
	if (incomplete(form.BILL_City))			{return false;}
	if (incomplete(form.BILL_State))		{return false;}
	if (incomplete(form.BILL_Zip))			{return false;}
	if (incomplete(form.BILL_Day_AreaCode))	{return false;}
	if (incomplete(form.BILL_Day_Prefix))	{return false;}
	if (incomplete(form.BILL_Day_Number))	{return false;}
	
	// SPECIAL CASES
	// Codes
		if (form.DealerCode.value == "N/A" || form.DealerCode.value == "NA") {
			alert("The Dealer Code must be a number.");
			form.DealerCode.focus();
			return false;
		}
		if (form.AgcoCode.value == "N/A" || form.AgcoCode.value == "NA") {
			alert("The AGCO Code must be a number. Use 0 if none.");
			form.AgcoCode.focus();
			return false;
		}
		if (form.DistNum.value == "N/A" || form.DistNum.value == "NA") {
			alert("The Distributor Code must be a number.");
			form.DistNum.focus();
			return false;
		}
		
	// E-Mail Address
		var email1 = form.OrderEmail1.value;
		var email2 = form.OrderEmail2.value;
		
		// Check Dealer's Order Email
		if ((email1 == "") && (email2 == "")) {
			form.OrderEmail1.value = "N/A";
			form.OrderEmail2.value = "N/A";
		} else {
			if (email1 == email2) {
				if (!isEmail(email1)) {
					alert("The Orders E-Mail does not appear to be valid.");
					form.OrderEmail1.focus();
					return false;
				}
			} else {
				alert("Oops! The Orders E-Mail fields do not match.");
				form.OrderEmail2.focus();
				return false;
			}
		}
	// Password
		var pass1 = form.Password1.value;
		var pass2 = form.Password2.value;
		
		if (isblank(pass1)) { alert("The Password field is empty!");			   form.Password1.focus(); return false; }
		if (isblank(pass2)) { alert("The Password Confirmation field is empty!"); form.Password2.focus(); return false; }

		if (pass1 == pass2) {
			if (pass1.length < 6) { alert("The password must be at least 6 characters long."); form.Password1.focus(); return false; }			
		} else {
			alert("Oops! The Password fields do not match.");
			form.Password1.focus();
			return false;
		}
		
	// Phone Numbers
		if (!allowedChars("NUMBER",form.SHIP_Day_AreaCode))   { alert("The Shipping Address Day Phone can only contain numbers.");   return false;}
		if (!allowedChars("NUMBER",form.SHIP_Day_Prefix))     { alert("The Shipping Address Day Phone can only contain numbers.");   return false;}
		if (!allowedChars("NUMBER",form.SHIP_Day_Number))     { alert("The Shipping Address Day Phone can only contain numbers.");   return false;}
		if (!allowedChars("NUMBER",form.SHIP_Day_Extension))  { alert("The Shipping Address Day Phone can only contain numbers.");   return false;}
		
		if (!allowedChars("NUMBER",form.SHIP_Night_AreaCode)) { alert("The Shipping Address Night Phone can only contain numbers."); return false;}
		if (!allowedChars("NUMBER",form.SHIP_Night_Prefix))   { alert("The Shipping Address Night Phone can only contain numbers."); return false;}
		if (!allowedChars("NUMBER",form.SHIP_Night_Number))   { alert("The Shipping Address Night Phone can only contain numbers."); return false;}
		if (!allowedChars("NUMBER",form.SHIP_Night_Extension)){ alert("The Shipping Address Night Phone can only contain numbers."); return false;}
		
		if (!allowedChars("NUMBER",form.SHIP_Fax_AreaCode))   { alert("The Shipping Address Fax can only contain numbers.");         return false;}
		if (!allowedChars("NUMBER",form.SHIP_Fax_Prefix))     { alert("The Shipping Address Fax can only contain numbers.");         return false;}
		if (!allowedChars("NUMBER",form.SHIP_Fax_Number))     { alert("The Shipping Address Fax can only contain numbers.");         return false;}
		
		if (!allowedChars("NUMBER",form.BILL_Day_AreaCode))   { alert("The Billing Address Day Phone can only contain numbers.");    return false;}
		if (!allowedChars("NUMBER",form.BILL_Day_Prefix))     { alert("The Billing Address Day Phone can only contain numbers.");    return false;}
		if (!allowedChars("NUMBER",form.BILL_Day_Number))     { alert("The Billing Address Day Phone can only contain numbers.");    return false;}
		if (!allowedChars("NUMBER",form.BILL_Day_Extension))  { alert("The Billing Address Day Phone can only contain numbers.");    return false;}
		
		if (!allowedChars("NUMBER",form.BILL_Night_AreaCode)) { alert("The Billing Address Night Phone can only contain numbers.");  return false;}
		if (!allowedChars("NUMBER",form.BILL_Night_Prefix))   { alert("The Billing Address Night Phone can only contain numbers.");  return false;}
		if (!allowedChars("NUMBER",form.BILL_Night_Number))   { alert("The Billing Address Night Phone can only contain numbers.");  return false;}
		if (!allowedChars("NUMBER",form.BILL_Night_Extension)){ alert("The Billing Address Night Phone can only contain numbers.");  return false;}
		
		if (!allowedChars("NUMBER",form.BILL_Fax_AreaCode))   { alert("The Billing Address Fax can only contain numbers.");          return false;}
		if (!allowedChars("NUMBER",form.BILL_Fax_Prefix))     { alert("The Billing Address Fax can only contain numbers.");          return false;}
		if (!allowedChars("NUMBER",form.BILL_Fax_Number))     { alert("The Billing Address Fax can only contain numbers.");          return false;}
	
	return true;
}

function allowedChars(which,field) {
	if (which == "ALPHA")    	 { var validChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuv";           		  	 }
	if (which == "NUMBER")   	 { var validChars = "0123456789";												  		  	 }
	if (which == "ALPHANUM") 	 { var validChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuv0123456789"; 		  	 }
	if (which == "ALPHANUMPUNC") { var validChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuv0123456789.?!,;:-/()$"; }
	if (which == "PRICE")   	 { var validChars = "0123456789$,.";												  		  	 }
	
	for (var i=0; i<field.value.length; i++) {
        if (validChars.indexOf(field.value.charAt(i)) < 0) {
            field.focus();
            return false;
        }
    }

    return true;
}
function incomplete(txtBox){
	if (txtBox.value == '') {
		txtBox.focus();
		alert(txtBox.name + " is empty.");
		return true;
	} else {
		return false;
	}
}
function isEmail(string) {
    	if (string.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) != -1) {
      	  	return true;
    	} else {
      	 	return false;
	}
}
function isblank(txtBox) {
	if (txtBox == null) { return false; }
	if (txtBox == "")   { return false; }
	
	for (var i = 0; i <= txtBox.length; i++) {
		var c = txtBox.charAt(i);
		if ((c != ' ') && (c != '\n') && (c != '\t')) {
			return false;
		}
	}
	return true;
}
///////////////////////////////////////////////////////////////////////////////////////////////////


function doNotesPanel(existingNotes,whichAction){
	if (whichAction == "SHOW") {
		if (existingNotes != "") {
			if (existingNotes == "NA") {
				document.CheckoutTableForm.notesfield.value = "";
			} else {
				document.CheckoutTableForm.notesfield.value = existingNotes;
			}
		}
		document.getElementById('shippingCarrier').style.visibility = "hidden"; 
		document.getElementById('editNotesSkirt').style.visibility = 'visible';
		document.getElementById('EditNotesPanel').style.visibility = 'visible';
		document.getElementById('editNotesSkirt').style.height = '800px';
		document.getElementById('EditNotesPanel').style.height = '200px';
		document.CheckoutTableForm.notesField.focus();
	}
	if (whichAction == "HIDE") {
		document.getElementById('shippingCarrier').style.visibility = "visible"; 
		document.getElementById('editNotesSkirt').style.visibility = 'hidden';
		document.getElementById('EditNotesPanel').style.visibility = 'hidden';
		document.getElementById('editNotesSkirt').style.height = '0px';
		document.getElementById('EditNotesPanel').style.height = '0px';
		
		if (escape(document.CheckoutTableForm.notesfield.value) == "") {
			var text2send = "NA";
		} else {
			var text2send = escape(document.CheckoutTableForm.notesfield.value);
		}
		JSordernotes = text2send;
		DWREngine._execute(_ajaxConfig._cfscriptLocation, null, 'setOrderNotes', text2send, setNotesResult);
	}
}
function setNotesResult(r) {
	var orderNotes = document.getElementById("orderNotes");
	var unescapedR = unescape(r.replace(/%0A/g,'<br />'));
	JSordernotes   = unescapedR;
	
	if (r == "NA") {
		orderNotes.innerHTML = "<div align='center'><font face='arial' size='1' color='#999999'><b>Click Edit to Add Notes</b></font></div><br /><br />";
	} else {
		var unescapedRsplit = unescapedR.split("<br />");
		
		if ((unescapedR.length > 100) || (unescapedRsplit.length > 3)) {
			if (unescapedRsplit.length > 3) {
				truncatedNotes = "<font face='arial' size='1' color='#000000'><b>" + unescapedRsplit[0] + "<br />";
				truncatedNotes = truncatedNotes + unescapedRsplit[1] + "<br />";
				if (unescapedRsplit[2].length > 40) {
					truncatedNotes = truncatedNotes + unescapedRsplit[2].substring(0,40);
				} else {
					truncatedNotes = truncatedNotes + unescapedRsplit[2];
				}
				truncatedNotes = truncatedNotes + "...</b></font><br /><br />";
				orderNotes.innerHTML = truncatedNotes;
			} else {
				orderNotes.innerHTML = "<font face='arial' size='1' color='#000000'><b>" + unescapedR.substring(0,100) + "...</b></font><br /><br />";
			}
		} else {
			orderNotes.innerHTML = "<font face='arial' size='1' color='#000000'><b>" + unescapedR + "</b></font><br /><br />";
		}
		
		document.getElementById("orderNotesField").value = unescapedR;
	}
}
function updateNotes() {
	DWREngine._execute(_ajaxConfig._cfscriptLocation, null, 'setOrderNotes', 'UPDATE', setNotesResult);
}
function initNotes() {
	JSordernotes  = "";
	existingNotes = "NA";
}

function showPromotion(which) {
	document.getElementById('shippingCarrier').style.visibility = "hidden";
	
	if (which == "AGCOPARTSFAIR") {
		document.getElementById("PartsFairPanel").style.visibility  = "visible";
	} else if (which == "WINTERSPECIAL") {
		document.getElementById("WinterSpecialPanel").style.visibility  = "visible";
	} else {
		document.getElementById("PromotionPanel").style.visibility  = "visible";
	}
}

function addPromotion(PromoPartNum,ShirtSizes,SelectedDiscount) {
	document.getElementById('shippingCarrier').style.visibility = "hidden";
	DWREngine._execute(_ajaxConfig._cfscriptLocation, null, 'addPromotion', PromoPartNum, ShirtSizes, SelectedDiscount, addPromotionResult);
}

function addPromotionResult(r) {
	if (r[0] != "ERROR") {
		PromoAlert = document.getElementById("PromotionAlert");
		
		if (r[2] == "PARTSFAIR") {
			PromoPanel = document.getElementById("PartsFairPanel");
		} else {
			PromoPanel = document.getElementById("PromotionPanel");
		}
		
		theCode = "";
		
		if (r[1] == "Both") {
			theCode = theCode + "<font class='ResultsLarge'>Promotion Added: </font><font class='ResultsSmall'><b>Massey Ferguson Print and 4 Wind Shirts</b></font>";
		} else {
			theCode = theCode + "<font class='ResultsLarge'>Promotion Added: </font><font class='ResultsSmall'><b>" + r[1] + "</b></font>";
		}
		
		if (r[2] == "PARTSFAIR") {
			theCode = theCode + "<font class='ResultsLarge'> Discount/Terms: </font><font class='ResultsSmall'><b>" + r[3] + "</b></font>";
			theCode = theCode + "<a href='javascript:showPromotion(\"AGCOPARTSFAIR\");' style='margin-left:10px;' class='ViewAll'>Change Selection</a>";
		}
		
		if (r[2] == "WINTERSPECIAL") {
			PromoPanel = document.getElementById("WinterSpecialPanel");
			
			theCode = "<font class='ResultsLarge'>Promotion Added: </font><font class='ResultsSmall'>Windshirt: " + r[0] + "</font>";
			theCode = theCode + "<font class='ResultsLarge'> Discount: </font>";
			if (r[1] == "OPTION1") {
				theCode = theCode + "<font class='ResultsSmall'> 10% Discount/Distributor Delivery</font>";
			}
			if (r[1] == "OPTION2") {
				theCode = theCode + "<font class='ResultsSmall'> 5% Discount/Free Ground Freight</font>";
			}
			theCode = theCode + "<a href='javascript:showPromotion(\"WINTERSPECIAL\");' style='margin-left:10px;' class='ViewAll'>Change Selection</a>";
		}
		 if (r[2] == "FREETSHIRT") {
		 	PromoPanel = document.getElementById("FreeTshirtPanel");
		 	theCode = theCode + "Your t-shirt has been added.";
		 }
		PromoAlert.innerHTML = theCode;
		document.getElementById('shippingCarrier').style.visibility = "visible"; 
		PromoAlert.style.visibility = "visible";
		PromoPanel.style.visibility = "hidden";
		
		//if (r[2] == "FREETSHIRT") { location.reload(true); }
	}
	
}

function checkKey(thefield,thekey) {
	var valid= /[0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ -]/g;
	
	if (!thekey) { var thekey = window.event; }
	
	if (thekey.keyCode) {
		code = thekey.keyCode;
	} else if (thekey.which) {
		code = thekey.which;
	}
	
	var character = String.fromCharCode(code);
	
	if (code==27)  { this.blur(); return false; }
	if (code==13)  { return true; }
	if (code==127) { return true; }
	
	//if (!thekey.ctrlKey && code!=9 && code!=8 && code!=36 && code!=37 && code!=38 && (code!=39 || (code==39 && character=="'")) && code!=40) {
		if (character.match(valid)) {
			return true;
		} else {
			return false;
		}
	//}
}

function doAddPart(part,region,quantity,row,rowPart) {
	if (!part) {
		var rgn = frm.SearchPriceRegion.value;
		var num = frm.SearchPartNum.value;
		var qty = frm.SearchPartQty.value;
	} else {
		var rgn = region;
		var num = part;
		var qty = quantity;
		
		setDeleteList(row,rowPart);
		deleteParts();
	}
	
	if (num != "" && qty != "" && qty != 0) {
		DWREngine._execute(_ajaxConfig._cfscriptLocation, null, 'addPartFunction', rgn, num, qty, 'ADDPART', addPartResult);
	}
	frm.SearchPartNum.value = "";
	frm.SearchPartQty.value = "1";
	frm.SearchPartNum.focus();
	
	if (region != "?") {
		return false;
	}
}
function addPartResult(r) {
	switch(r[0].searchmode) {
		case "EXACT":
			PartStatusImage  = "<img src='images/button_edit.png' width='20' height='10' border='0'>";
			AvailStatusImage = "pixel.gif";
			ShipStatusImage  = "pixel.gif";
			switch(r[1].salestatus) {
				case "ONSALE":
					SaleStatusImage         = "saleitem.png";
					theDealerPrice          = r[1].dlrcost;
					theDistributorPrice     = r[1].dstcost;
					
					if (r[1].dlrfp > 0) {
						theDealerSalePrice      = r[1].dlrfp;
						theDistributorSalePrice = r[1].dstfp;
					}
					if (r[1].dlrbb > 0) {
						theDealerSalePrice      = r[1].dlrbb;
						theDistributorSalePrice = r[1].dstbb;
					}
					if (r[1].dlrrh > 0) {
						theDealerSalePrice      = r[1].dlrrh;
						theDistributorSalePrice = r[1].dstrh;
					}
					break;
				case "ZEROITEM":
					if (r[1].obsolete != "YES") {
						SaleStatusImage = "callus.png";
					} else {
						SaleStatusImage = "pixel.gif";
					}
					break;
				case "REGULAR":
					SaleStatusImage = "pixel.gif";
					break;
			}
			switch(r[1].freeship) {
				case "NO":
					ShipStatusImage = "notfree.png";
					break;
			}
			switch(r[1].hazardstatus) {
				case "YES":
					HazardStatusImage = "hazardous.png";
					break;
				case "NO":
					HazardStatusImage = "pixel.gif";
					break;
			}
			
			if (r[1].salestatus == "ONSALE") {
				theDisplayDealerPrice          = theDealerSalePrice;
				theDisplayDistributorPrice     = theDistributorSalePrice;
			} else {
				theDisplayDealerPrice          = r[1].dlrcost;
				theDisplayDistributorPrice     = r[1].dstcost;
			}
			
			// AVAILABILITY
			data = r[1].availstatus.split(',');
			PARTNUMBER   = r[0].enterednum.toUpperCase();
			AVAILABILITY = data[0].toUpperCase();
			REPLACEMENT  = data[1].toUpperCase();
				
			if (AVAILABILITY != "1/1/2000" && AVAILABILITY != "OBSOLETE") {
				panel   = document.getElementById("AvailabilityPanel");
				theCode = "";
				
				theCode = theCode + "<font class='ResultsLarge'>The part number: " + PARTNUMBER + " is currently unavailable.</font><br>";
				if (AVAILABILITY != "1/1/3000" && AVAILABILITY != "1/1/2000") {
					theCode = theCode + "<font class='ResultsSmall'><b>Expected Availability:</b> " + AVAILABILITY + ".</font><br>";
				}
				theCode = theCode + "<br><font class='ResultsSmall'>Use Part Number: " + REPLACEMENT + ".</font><br>";
				theCode = theCode + "<br><br><br><br><br><br><br>";
				theCode = theCode + "<font class='ResultsLarge'>Add Part Number " + REPLACEMENT + " to the Order?</font>";
				theCode = theCode + "<hr><br>";
				theCode = theCode + "<div style='float:right;'><a href='javascript:AvailPanel(\"HIDE\");' class='ViewAll'>No</a><a href='javascript:AvailPanel(\"ADD\",\"" + REPLACEMENT + "\");' class='AddtoOrder' style='margin-left:15px;'>Yes</a></div>";
				
				panel.innerHTML = theCode;
				panel.style.visibility = 'visible';
			} else {
				// Check to see if part is already in the Current List
				// If it is, adjust its Quantity. If its not - add it.
				
				var existingPartsRowID      = "";
				var existingPartsArrayIndex = "";
				
				for (i=0; i <= (currentPartsList.length-1); i++) {
					if ((r[0].enterednum).toUpperCase() == (currentPartsList[i][0][0].enterednum).toUpperCase() && currentPartsList[i][0][0].searchmode != "DELETED") {
						existingPartsRowID      = currentPartsList[i][1];
						existingPartsArrayIndex = i;
						break;
					}
				}
				
				if (existingPartsRowID != "") {
					var curQty = currentPartsList[existingPartsArrayIndex][0][1].qty;
					var addQty = r[1].qty;
					var newQty = (Number(curQty) + Number(addQty));
					
					// Adjust the quantity value in the array
					currentPartsList[existingPartsArrayIndex][0][1].qty = newQty;
					
					// Adjust the quantity value in the display row
					theTable.rows[existingPartsRowID].cells[4].innerHTML = "<font class='PL_SM_Bold'>" + newQty + "</font>";
					
					// Adjust the Dealer and Distributor Line Totals
					// These columns change based on the Viewing Mode and Selected Pricing View ///////
					switch(r[0].priceview) {
						case "NONE":
							// Column Headers are: Empty. We don't show any pricing to the general public.
							theTable.rows[existingPartsRowID].cells[16].innerHTML = "<font class='PL_SM_Bold'></font>";
							theTable.rows[existingPartsRowID].cells[18].innerHTML = "<font class='PL_SM_Bold'></font>";
							break;
						case "LIST":
							// Column Headers are: Item, Core, List
							theTable.rows[existingPartsRowID].cells[16].innerHTML = "<font class='PL_SM_Bold'>" + outputMoney(currentPartsList[existingPartsArrayIndex][0][1].core * newQty) + "</font>";
							theTable.rows[existingPartsRowID].cells[18].innerHTML = "<font class='PL_SM_Bold'>" + outputMoney(currentPartsList[existingPartsArrayIndex][0][1].list * newQty) + "</font>";
							break;
						case "DEAL":
							// Column Headers are: Item, Core, Deal
							theTable.rows[existingPartsRowID].cells[16].innerHTML = "<font class='PL_SM_Bold'>" + outputMoney(currentPartsList[existingPartsArrayIndex][0][1].core * newQty) + "</font>";
							theTable.rows[existingPartsRowID].cells[18].innerHTML = "<font class='PL_SM_Bold'>" + outputMoney(theDisplayDealerPrice * newQty) + "</font>";
							
							break;
						case "DIST":
							// Column Headers are: Item, Deal, Dist
							theTable.rows[existingPartsRowID].cells[16].innerHTML = "<font class='PL_SM_Bold'>" + outputMoney(theDisplayDealerPrice* newQty) + "</font>";
							theTable.rows[existingPartsRowID].cells[18].innerHTML = "<font class='PL_SM_Bold'>" + outputMoney(theDisplayDistributorPrice * newQty) + "</font>";
							
							break;
						default:
							theTable.rows[existingPartsRowID].cells[16].innerHTML = "ERR";
							theTable.rows[existingPartsRowID].cells[18].innerHTML = "ERR";
							break;
					}
				} else {
					// Part Not in List - Add it.
					rowItemDetails = [r,theCurrentRow];
					currentPartsList.push(rowItemDetails);
					
					document.getElementById("SaveOrderButtonHolder").innerHTML = "<a class='ViewAll' href='javascript:saveOrder(\"SHOW\");' target='_self'>Save Order</a><br>";
					document.getElementById("PrintOrderButtonHolder").innerHTML = "<a class='ViewAll' href='javascript:self.print();' target='_self'>Print Order</a><br>";
					
					setInnerHTML(r[0].priceview,r[0].enterednum,r[1].qty,r[1].desc,theDisplayDistributorPrice,theDisplayDealerPrice,r[1].core,r[1].list,r[1].obsolete);
				}
				updateListTotals(r[0].priceview);
				updateYellowBar();
			}
			break;
		case "PARTIAL":
			// Check to see if part is already in the Current List
			// If it is, pop an alert. If its not - add it.
			var existingPartsRowID      = "";
			var existingPartsArrayIndex = "";
			
			if (currentPartsList.length > 0) {
				for (i=0; i <= (currentPartsList.length - 1); i++) {
					if (r[0].enterednum == currentPartsList[i][0][0].enterednum && currentPartsList[i][0][0].searchmode != "DELETED") {
						existingPartsRowID      = currentPartsList[i][1];
						existingPartsArrayIndex = i;
						break;
					}
				}
			}
			
			if (existingPartsRowID != "") {
				alert("This search is already in the Parts List.");
			} else {
				// Part Not in List - Add it.
				rowItemDetails = [r,theCurrentRow];
				currentPartsList.push(rowItemDetails);
				
				PartStatusImage   = "<img src='images/icon_alert.png' width='15' height='15' border='0'>";
				AvailStatusImage  = "pixel.gif";
				SaleStatusImage   = "pixel.gif";
				ShipStatusImage   = "pixel.gif";
				HazardStatusImage = "pixel.gif";
				setInnerHTML(r[0].priceview,r[0].enterednum,r[0].enteredqty,"Multiple Parts Found","-","-","-","-",r[1].obsolete);
			}
			
			updateListTotals(r[0].priceview);
			break;
		case "NORESULTS":
			alert("No results were found for the search.");
			break;
		default:
			alert("An unknown error has occured.");
			break;
	}
}

function AvailPanel(whichAction,whichPart) {
	if (whichAction == "ADD") {
		DWREngine._execute(_ajaxConfig._cfscriptLocation, null, 'addPartFunction', frm.SearchPriceRegion.value, whichPart, 1, 'ADDPART', addPartResult);
	}
		
	document.getElementById("AvailabilityPanel").style.visibility = "hidden";
	frm.SearchPartNum.value = "";
	frm.SearchPartQty.value = "1";
	frm.SearchPartNum.focus();

}

function rebuildOrder(partNum,partQty) {
	document.getElementById("PartListEmptyWarning").innerHTML  = "<td colspan=\"19\" align=\"center\"><br /><font face=\"arial\" size=\"3\" color=\"666666\"><b>Retrieving the Order Details...</b></font><br><font face=\"arial\" size=\"2\" color=\"999999\">This may take a few seconds.</font><br /><br /></td>";
	DWREngine._execute(_ajaxConfig._cfscriptLocation, null, 'rebuildOrderForm', partNum, partQty, rebuildOrderResult);
}

function rebuildOrderResult(r) {
	//dstcost,dlrcost,dlrfp,dstfp,dlrbb,dstbb,list,core
	
	PartStatusImage  = "<img src='images/button_edit.png' width='20' height='10' border='0'>";
	AvailStatusImage = "pixel.gif";
	ShipStatusImage  = "pixel.gif";
	rowItemDetails   = [r,theCurrentRow];
	
	switch(r[1].salestatus) {
		case "ONSALE":
			SaleStatusImage         = "saleitem.png";
			theDealerPrice          = r[1].dlrcost;
			theDistributorPrice     = r[1].dstcost;
			
			theDealerSalePrice      = 0;
			theDistributorSalePrice = 0;
				
			// Dealer Sale Price?
			if (r[1].dlrfp > 0) { theDealerSalePrice      = r[1].dlrfp; }
			if (r[1].dlrbb > 0) { theDealerSalePrice      = r[1].dlrbb; }
			if (r[1].dlrrh > 0) { theDealerSalePrice      = r[1].dlrrh; }
			
			// Distributor Sale Price?
			if (r[1].dstfp > 0) { theDistributorSalePrice = r[1].dstfp; }
			if (r[1].dstbb > 0) { theDistributorSalePrice = r[1].dstbb; }
			if (r[1].dstrh > 0) { theDistributorSalePrice = r[1].dstrh; }
			break;
		case "ZEROITEM":
			if (r[1].obsolete != "YES") {
				SaleStatusImage = "callus.png";
			} else {
				SaleStatusImage = "pixel.gif";
			}
			break;
		case "REGULAR":
			SaleStatusImage = "pixel.gif";
			break;
	}
	switch(r[1].freeship) {
		case "NO":
			ShipStatusImage = "notfree.png";
			break;
	}
	switch(r[1].hazardstatus) {
		case "YES":
			HazardStatusImage = "hazardous.png";
			break;
		case "NO":
			HazardStatusImage = "pixel.gif";
			break;
	}
	
	if (r[0].enterednum == "1013TS-M") {
		AvailStatusImage  = "pixel.gif";
		SaleStatusImage   = "pixel.gif";
		ShipStatusImage   = "pixel.gif";
		HazardStatusImage = "pixel.gif";
	}
	if (r[0].enterednum == "1013TS-L") {
		AvailStatusImage  = "pixel.gif";
		SaleStatusImage   = "pixel.gif";
		ShipStatusImage   = "pixel.gif";
		HazardStatusImage = "pixel.gif";
	}
	if (r[0].enterednum == "1013TS-XL") {
		AvailStatusImage  = "pixel.gif";
		SaleStatusImage   = "pixel.gif";
		ShipStatusImage   = "pixel.gif";
		HazardStatusImage = "pixel.gif";
	}
	if (r[0].enterednum == "1013TS-XXL") {
		AvailStatusImage  = "pixel.gif";
		SaleStatusImage   = "pixel.gif";
		ShipStatusImage   = "pixel.gif";
		HazardStatusImage = "pixel.gif";
	}
	if (r[0].enterednum == "1013TS-XXXL") {
		AvailStatusImage  = "pixel.gif";
		SaleStatusImage   = "pixel.gif";
		ShipStatusImage   = "pixel.gif";
		HazardStatusImage = "pixel.gif";
	}
	
	if (r[1].salestatus == "ONSALE") {
		theDisplayDealerPrice          = theDealerSalePrice;
		theDisplayDistributorPrice     = theDistributorSalePrice;
	} else {
		theDisplayDealerPrice          = r[1].dlrcost;
		theDisplayDistributorPrice     = r[1].dstcost;
	}
			
	currentPartsList.push(rowItemDetails);
	if (r[0].searchmode == "PARTIAL") {
		PartStatusImage   = "<img src='images/icon_alert.png' width='15' height='15' border='0'>";
		AvailStatusImage  = "pixel.gif";
		SaleStatusImage   = "pixel.gif";
		ShipStatusImage   = "pixel.gif";
		HazardStatusImage = "pixel.gif";
		setInnerHTML(r[0].priceview,r[0].enterednum,r[0].enteredqty,"Multiple Parts Found","-","-","-","-");
		document.getElementById("finalizeButtons").innerHTML = "<a class='ViewAll' href='#' target='_self' onClick='resetPage(\"SHOW\");'>Reset</a>";
		document.getElementById("finalizeButtons").innerHTML = document.getElementById("finalizeButtons").innerHTML + "<font class='AddtoOrderDISABLED'>Finalize Order</font><br /><br />";
		document.getElementById("finalizeButtons").innerHTML = document.getElementById("finalizeButtons").innerHTML + "<img src='images/icon_alert.png' width='15' height='15' border='0'>";
		document.getElementById("finalizeButtons").innerHTML = document.getElementById("finalizeButtons").innerHTML + "<b>There are items in the order that<br />require your attention before finalizing</b><br /><br />";
	} else {
		theDealerCost      = r[1].dlrcost;
		theDistributorCost = r[1].dstcost;
		
		setInnerHTML(r[0].priceview,r[0].enterednum,r[1].qty,r[1].desc,theDisplayDistributorPrice,theDisplayDealerPrice,r[1].core,r[1].list,r[1].obsolete);
		
		document.getElementById("finalizeButtons").innerHTML = "<a class='ViewAll' href='#' target='_self' onClick='resetPage(\"SHOW\");'>Reset</a>";
		document.getElementById("finalizeButtons").innerHTML = document.getElementById("finalizeButtons").innerHTML + "<a class='AddtoOrder' href='?chapter=PARTS&page=CHECKOUT&p=1' target='_self'>Finalize Order</a><br /><br />";
	}
	updateListTotals(r[0].priceview);
}

function addAPartFromRESULTS(rgn,num,qty) {
	DWREngine._execute(_ajaxConfig._cfscriptLocation, null, 'addPartFunction', rgn, num, qty, 'ADDPART', addAPartFromRESULTSResult);
}
function addAPartFromRESULTSResult(r){	
	var windowHeight              = getWindowHeight();
	thePanel                      = document.getElementById("PartAddedAlert").style;
	var theOpacity                = 80;
	
	// Alert Stuff
	document.getElementById("partInfo").innerHTML = "<font class='ResultsLarge'><font size='3' color='#FFFFFF'>" + trim(r[0].enterednum) + "</font></font>";
	
	thePanel.opacity      = (theOpacity / 100); 
	thePanel.MozOpacity   = (theOpacity / 100); 
	thePanel.KhtmlOpacity = (theOpacity / 100); 
	thePanel.filter       = "alpha(opacity=" + theOpacity + ")";
	thePanel.visibility   = 'visible';
	thePanel.top          = (windowHeight) + 'px';
	thePanel.height		  = '85px';
	
	setTimeout('fadeOutPanel("PartAddedAlert","0")', 2000);
	fade = 0;
	
	rowItemDetails = [r,theCurrentRow];
	currentPartsList.push(rowItemDetails);
				
	refreshMiniCart();
	updateYellowBar();
}

function addAPartFromHOMEPAGE(rgn,num,qty) {
	DWREngine._execute(_ajaxConfig._cfscriptLocation, null, 'addPartFunction', rgn, num, qty, 'ADDPART', addAPartFromHOMEPAGEResult);
}


function addAPartFromHOMEPAGEResult(r) {
	if ((r[0].enterednum == "PROMOCK1")||(r[0].enterednum == "PROMOCK2")||(r[0].enterednum == "SAMPLE LU10063")||(r[0].enterednum == "SAMPLE LU10130")||(r[0].enterednum == "SAMPLE LU10001")||(r[0].enterednum == "PROMO750")) {
		window.location = "?chapter=PARTS&page=CHECKOUT&p=1&tshirt=1";
	} else {
	var windowHeight  = getWindowHeight();
	thePanel          = document.getElementById("PartAddedAlert").style;
	var theOpacity    = 80;
	
	if (windowHeight < 0) { windowHeight = 200; }
	
	document.getElementById("partInfo").innerHTML = "<font class='ResultsLarge'><font size='3' color='#FFFFFF'>" + trim(r[0].enterednum) + "</font></font>";
	
	thePanel.opacity      = (theOpacity / 100); 
	thePanel.MozOpacity   = (theOpacity / 100); 
	thePanel.KhtmlOpacity = (theOpacity / 100); 
	thePanel.filter       = "alpha(opacity=" + theOpacity + ")";
	thePanel.visibility   = 'visible';
	thePanel.top          = (windowHeight - 100) + 'px';
	thePanel.height		  = '85px';
	
	setTimeout('fadeOutPanel("PartAddedAlert","0")', 2000);
	fade = 0;
	}
}

// TechXperts Functions
function updateSymptom(symptomID) {
	DWREngine._execute(_ajaxConfig._cfscriptLocation, null, 'getSymptom', symptomID, updateSymptomResult);
}
function updateSymptomResult(r) {
	theCause = "";
	
	for (n=1; n < r.length; n++) {
		theCause = theCause + "<table><tr>";
		theCause = theCause + "<td valign='top'><font class='ResultsLarge' style='color:#333333;'>Cause </font></td><td valign='top'><font class='ResultsLarge' style='color:#666666;'>" + r[n].cause + "</font></td><br></tr><tr>";
		theCause = theCause + "<td valign='top'><font class='ResultsLarge' style='color:#009900;'>Solution </font></td><td valign='top'><font class='ResultsSmall' style='font-size:9pt;'>" + r[n].solution + "</font></td></tr></table>";
		theCause = theCause + "</div><br><br>";
	}
	document.getElementById("symptomDisplay").innerHTML = theCause;
}
function showAnswer(QuestionID) {
	DWREngine._execute(_ajaxConfig._cfscriptLocation, null, 'getAnswer', QuestionID, showAnswerResult);
}
function showAnswerResult(r) {
	answerCount   = r[3];
	theAnswer     = "";
	theShowButton = "<a href='javascript:showAnswerImage(\"" + r[2] + "\",\"" + r[0] + "\",\"" + r[1] + "\");' class='ViewAll' style='margin-left:10px;'>View</a>";
	
	for (x=1; x <= answerCount; x++) { document.getElementById("Answer_" + x).innerHTML = ""; }
	theAnswer = theAnswer + "<font class='ResultsSmall' style='font-size:9pt;'>" + r[1] + "</font>";
	if (r[2] != "") {
		//theAnswer = theAnswer + "<a href='CustomerService/AnswerImages/" + r[2] + "' class='ViewAll' style='margin-left:10px;'>View</a>";
		theAnswer = theAnswer + theShowButton;
	}
	document.getElementById("Answer_" + r[0]).innerHTML = theAnswer;
}
function showAnswerImage(imageName,divName,answerText) {
	theImage      = "<div align='center' style='margin-top:10px;'><img src='CustomerService/AnswerImages/" + imageName + "'></div>";
	theHideButton = "<a href='javascript:hideAnswerImage(\"" + imageName + "\",\"" + divName + "\",\"" + answerText + "\");' class='ViewAll' style='margin-left:10px;'>Hide</a>";

	document.getElementById("Answer_" + divName).innerHTML = "<font class='ResultsSmall' style='font-size:9pt;'>" + answerText + "</font>" + theHideButton + theImage;
}
function hideAnswerImage(imageName,divName,answerText) {
	theImage      = "<div align='center' style='margin-top:10px;'><img src='CustomerService/AnswerImages/" + imageName + "'></div>";
	theShowButton = "<a href='javascript:showAnswerImage(\"" + imageName + "\",\"" + divName + "\",\"" + answerText + "\");' class='ViewAll' style='margin-left:10px;'>View</a>";

	document.getElementById("Answer_" + divName).innerHTML = "<font class='ResultsSmall' style='font-size:9pt;'>" + answerText + "</font>" + theShowButton;
}
function openQuestionPanel() {
	document.getElementById("TechXpertsQuestionPanel").style.visibility = "visible";
	document.getElementById("TechXpertsQuestionPanel").style.height     = "500px";
	document.getElementById("TechXpertsQuestionPanel").style.width      = "400px";
}
function closeQuestionPanel() {
	document.getElementById("TechXpertsQuestionPanel").style.visibility = "hidden";
	document.getElementById("TechXpertsQuestionPanel").style.height     = "0px";
	document.getElementById("TechXpertsQuestionPanel").style.width      = "0px";
}
function sendQuestion() {
	theQuestionForm = new Array();
	theQuestionForm[0]  = document.questionform.name.value;
	theQuestionForm[1]  = document.questionform.email.value;
	theQuestionForm[2]  = document.questionform.phone.value;
	theQuestionForm[3]  = document.questionform.method.value;
	theQuestionForm[4]  = document.questionform.urgency.value;
	theQuestionForm[5]  = document.questionform.mfg.value;
	theQuestionForm[6]  = document.questionform.typ.value;
	theQuestionForm[7]  = document.questionform.mod.value;
	theQuestionForm[8]  = document.questionform.part.value;
	theQuestionForm[9]  = document.questionform.description.value;
	theQuestionForm[10] = document.questionform.question.value;
	
	DWREngine._execute(_ajaxConfig._cfscriptLocation, null, 'sendQuestion', theQuestionForm, sendQuestionResult);
}
function sendQuestionResult(r) {
	if (r == true || r == "true") {
		theResult = "";
		theResult = theResult + "<font class='ResultsLarge'>You're Question Has Been Sent.</font><br>";
		theResult = theResult + "<font class='ResultsSmall'>We will be in contact as soon as we have your answer.</font><br>";
		theResult = theResult + "<font class='ResultsSmall'><b>If you need immediate assistance please call 1-800-247-1824</b></font><br><br>";
		theResult = theResult + "<font class='ResultsSmall'><b>Thank You</b></font><br><br>";
	} else {
		theResult = "";
		theResult = theResult + "<font class='ResultsLarge'>Something Went Wrong.</font><br>";
		theResult = theResult + "<font class='ResultsSmall'><b>Please call us for immediate assistance at 1-800-247-1824</b></font><br><br>";
		theResult = theResult + "<font class='ResultsSmall'><b>We apologize for the inconvenience</b></font><br><br>";
	}
	theResult = theResult + "<a href='javascript:closeQuestionPanel();' class='ViewAll'>Close Panel</a>";
	
	document.getElementById("TechXpertsQuestionPanel").innerHTML = theResult;
	setTimeout('fadeOutPanel("TechXpertsQuestionPanel","0")', 10000);
	fade = 0;
}





function fadeOutPanel(whichPanel,start) {
	thePanel = document.getElementById(whichPanel);
	if (start == 0) {
		fade     = setInterval('fadeOutPanel("' + whichPanel + '","1")', 75);
	}

	var currentOpacity = (thePanel.style.opacity * 100);
	var theOpacity     = (currentOpacity - 5);
	
	thePanel.style.opacity      = (theOpacity / 100); 
	thePanel.style.MozOpacity   = (theOpacity / 100); 
	thePanel.style.KhtmlOpacity = (theOpacity / 100); 
	thePanel.style.filter       = "alpha(opacity=" + theOpacity + ")";
	
	
	if (currentOpacity <= 0) {
		thePanel.height = '0px';
		clearInterval(fade);
	}
}

function refreshMiniCart() {
	DWREngine._execute(_ajaxConfig._cfscriptLocation, null, 'refreshMiniCart', refreshMiniCartResults);
	return false;
}
	
function refreshMiniCartResults(r) {
	// r[0] = The Last Added Part
	// r[1] = Array of the other Parts in the order
	//        Each part has these keys: partnum, partqty, description, partcost
	
	var miniCart_JustAdded_object = document.getElementById("MiniCart_JustAdded");
	var miniCart_Others_object    = document.getElementById("MiniCart_Others");
	var miniCart_Totals_object    = document.getElementById("MiniCart_Totals");
	var freeshipNeeded			  = 750.00;
	var freeshipTotal			  = 0.00;
	var theJustAddedTotal         = 0.00;
	var theOtherPartsTotal        = 0.00;
	var theMiniCartTotal          = 0.00;
	
	if (r[0] && r[0] != "NOTHINGINORDER") {
		// Write the Just Added Section
		thecode = "<font face='arial' size='1' color='#666666'><b>Just Added</b></font><br /></b>";
		thecode = thecode + "<div id='MC_JA_Left' style='width:90px;float:left;text-align:left;'>";
		thecode = thecode + "<font face='arial' size='1' color='#000000'><b>";
		thecode = thecode + "( " + r[0].partqty + " ) " + trim(r[0].partnum);
		thecode = thecode + "</b></font>";
		thecode = thecode + "</div><div id='MC_JA_Right' style='width:70px;float:left;text-align:right;'>";
		thecode = thecode + "<font face='arial' size='1' color='#000000'><b>";
		thecode = thecode + outputMoney(r[0].partcost * r[0].partqty);
		thecode = thecode + "</b></font>";
		thecode = thecode + "</div><br />";
		
		theDescription = r[0].description.replace(/\"\"/g,"~");
		theDescription = theDescription.replace(/\"/g,"");
		theDescription = theDescription.replace(/~/g,"\"");
		
		thecode = thecode + trim(theDescription);
		miniCart_JustAdded_object.innerHTML = thecode;
		
		
		// Write the Also in Order Section
		if (r[1].length > 0) {
			thecode = "<font face='arial' size='1' color='#666666'><b>Other Items in Order</b></font><br />";
			
			for (n=0; n <= (r[1].length - 1); n++) {
				thecode = thecode + "<div id='MC_O_Left" + n + "' style='width:90px;float:left;text-align:left;'>";
				thecode = thecode + "<font face='arial' size='1' color='#000000'><b>";
				thecode = thecode + "( " + r[1][n].partqty + " ) " + r[1][n].partnum;
				thecode = thecode + "</b></font>";
				thecode = thecode + "</div><div id='MC_O_Right" + n + "' style='width:70px;float:left;text-align:right;'>";
				thecode = thecode + "<font face='arial' size='1' color='#000000'><b>";
				thecode = thecode + outputMoney((r[1][n].partcost * r[1][n].partqty));
				thecode = thecode + "</b></font>";
				thecode = thecode + "</div><br />";	
			}
			miniCart_Others_object.innerHTML = thecode;
		}
		
		
		// Write the Order Totals Section
		//if (r[1].length > 0) {
			// Total the Just Added Section
			theJustAddedTotal = (parseFloat(r[0].partcost) * r[0].partqty);
			if (r[0].freeship == "YES") { freeshipTotal = (freeshipTotal + theJustAddedTotal); }
			
			// Total the Other Parts Section
			if (r[1].length > 0) {
				for (i=0; i <= (r[1].length - 1); i++) {
					theOtherPartsTotal = theOtherPartsTotal + (parseFloat(r[1][i].partcost) * r[1][i].partqty);
					if (r[1][i].freeship == "YES") { freeshipTotal = (freeshipTotal + (parseFloat(r[1][i].partcost) * r[1][i].partqty)); }
				}
			}
			
			// Total the Entire Order
			theMiniCartTotal = (theJustAddedTotal + theOtherPartsTotal);
			
			// Calculate the Free Shipping Amount
			var FSstillNeeded = (freeshipNeeded - freeshipTotal);
			
			thecode = "<br /><div id='MC_T_Left' style='width:70px;float:left;text-align:left;'>";
			thecode = thecode + "<font face='arial' size='1' color='#000000'><b>Order Total</b><font>";
			thecode = thecode + "</div><div id='MC_T_Right' style='width:90px;float:left;text-align:right;'>";
			thecode = thecode + "<font face='arial' size='1' color='#000000'><b>";
			thecode = thecode + outputMoney(theMiniCartTotal);
			thecode = thecode + "</b></font></div><br /><br />";
			
			if (theSessionPriceView == "DEAL") {
				if (freeshipTotal < freeshipNeeded) {
					thecode = thecode + "<div id='MC_T_Bottom' style='width:150px;height:auto;padding:2px;float:center;text-align:center;background-color:#EFEFEF;'>";
					thecode = thecode + "<font face='arial' color='#000000' style='font-size:7pt;'>Add: " + outputMoney(FSstillNeeded) + " in qualifying parts<br />";
					thecode = thecode + "to get standard free shipping.<font><br /></div><br />";
				} else {
					thecode = thecode + "<div id='MC_T_Bottom' style='width:150px;height:auto;padding:2px;float:center;text-align:center;background-color:#FFCC33;'>";
					thecode = thecode + "<font face='arial' color='#000000' style='font-size:7pt;'>Congratulations! This order<br />";
					thecode = thecode + "qualifies for standard free shipping.<font><br /></div><br />";
				}
			}
			miniCart_Totals_object.innerHTML = thecode;
		//}
		
	}
}

function updateShipping(whichCarrier,whichService,freeship) {
	var UPSList   = "Ground,2nd Day,3rd Day Select,Next Day,Next Day - Sat.";
	var FedExList = "Ground,2nd Day,Priority Overnight,Next Day - Sat.";
	var DHLList   = "Ground, 2nd Day, Next Day";
	var options_object = document.getElementById("shippingOptions");
	
	switch(whichCarrier) {
		case "UPS":
			var selectedList = UPSList.split(",");
			break;
		case "FedEx":
			var selectedList = FedExList.split(",");
			break;
		case "DHL":
			var selectedList = DHLList.split(",");
			break;
		default:
			var selectedList = "";
	}
	
	if (selectedList.length > 0) {
		options_object.innerHTML = "";
		anySelected              = "NO";
		
		// Check if any will be selected
		for (var n=0; n<= (selectedList.length-1); n++) {
			if (whichService == selectedList[n]) {
				anySelected = "YES";
				break;
			}
		}
				
		for (var i=0; i<= (selectedList.length-1); i++) {
			if (i <= (selectedList.length-1)) {
				if (selectedList[i] == "Ground" && freeship == "YES") {
					var displayLabel = "Ground (FREE)";
				} else {
					var displayLabel = selectedList[i];
				}
				if (whichService == selectedList[i]) {
					options_object.innerHTML = options_object.innerHTML + "<div style='position:relative;width:115px;height:15px;padding-bottom:3px;float:left;text-align:left;'><input type='radio' name='serviceoption' checked='CHECKED' value='" + displayLabel + "'> " + displayLabel + "</div>";
				} else {
					if (anySelected == "NO" && selectedList[i] == "Ground") {
						options_object.innerHTML = options_object.innerHTML + "<div style='position:relative;width:115px;height:15px;padding-bottom:3px;float:left;text-align:left;'><input type='radio' name='serviceoption' checked='CHECKED' value='" + displayLabel + "'> " + displayLabel + "</div>";
					} else {
						options_object.innerHTML = options_object.innerHTML + "<div style='position:relative;width:115px;height:15px;padding-bottom:3px;float:left;text-align:left;'><input type='radio' name='serviceoption' value='" + displayLabel + "'> " + displayLabel + "</div>";
					}
				}
			}
			if ((i+1) <= (selectedList.length-1)) {
				if (whichService == selectedList[i+1]) {
					options_object.innerHTML = options_object.innerHTML + "<div style='position:relative;width:auto;height:15px;min-width:115px;padding-bottom:3px;float:left;text-align:left;'><input type='radio' name='serviceoption' checked='CHECKED' value='" + selectedList[i+1] + "'> " + selectedList[i+1] + "</div>";
				} else {
					if (anySelected == "NO" && selectedList[i+1] == "Ground") {
						options_object.innerHTML = options_object.innerHTML + "<div style='position:relative;width:auto;height:15px;min-width:115px;padding-bottom:3px;float:left;text-align:left;'><input type='radio' name='serviceoption' checked='CHECKED' value='" + selectedList[i+1] + "'> " + selectedList[i+1] + "</div>";
					} else {
						options_object.innerHTML = options_object.innerHTML + "<div style='position:relative;width:auto;height:15px;min-width:115px;padding-bottom:3px;float:left;text-align:left;'><input type='radio' name='serviceoption' value='" + selectedList[i+1] + "'> " + selectedList[i+1] + "</div>";
					}
				}
			}
			options_object.innerHTML = options_object.innerHTML + "<br />";
			i++;
		}
		options_object.innerHTML = options_object.innerHTML + "<br />";
	} else {
		if (whichCarrier == "SpeeDee" && freeship == "YES") {
			options_object.innerHTML = "Free standard ground shipping.<input type='hidden' name='serviceoption' value='(FREE)'>";
		} else if (whichCarrier == "USPS" && freeship == "YES") {
			options_object.innerHTML = "Free standard ground shipping.<input type='hidden' name='serviceoption' value='(FREE)'>";
		} else {
			options_object.innerHTML = "";
		}
	}
}

function doBearingsForm(whichPart,theQty,theCat,whichAction) {
	if (whichAction == "SHOW") {
		var panelContents       = document.getElementById('bearingscontent');
		var bearingsfield       = "";
		var pistonfield         = "";
		var buildnumfield       = "";
		var cplnumfield         = "";
		var serialnumfield      = "";
		var arrangementnumfield = "";
		var partRows            = "";
	
		panelContents.innerHTML = "";
	
		BearingsFormActivePart = whichPart;
		BearingsFormActiveQty  = theQty;
		
		document.getElementById('BearingsSkirt').style.visibility = 'visible';
		document.getElementById('BearingsPanel').style.visibility = 'visible';
		document.getElementById('BearingsSkirt').style.height = '100%';
		document.getElementById('BearingsPanel').style.height = '400px';
		
		var ns = (navigator.appName.indexOf("Netscape") != -1); 
		var pY = ns ? pageYOffset : document.documentElement && document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop; 
		document.getElementById('BearingsPanel').style.top = (pY-50) + 'px';
		
		for (i=1; i<=theQty; i++) {
			// Which Fields Does This Part Need?
			// Everything needs the Bearings Field
			bearingsfield = "<td><input type='text' id='" + whichPart + "_" + i + "_Bearings' name='" + whichPart + "_" + i + "_Bea' value=''></td>";

			// Parts that start with these codes need extra fields
			switch(theCat) {
				case "HCFOR":
					pistonfield = "<td><input type='text' id='" + whichPart + "_" + i + "_Piston' name='" + whichPart + "_" + i + "_Pis' value=''></td>";
					break;
				case "HCPER":
					buildnumfield = "<td><input type='text' id='" + whichPart + "_" + i + "_Build' name='" + whichPart + "_" + i + "_Bui' value=''></td>";
					break;
				case "HCCUM":
					cplnumfield = "<td><input type='text' id='" + whichPart + "_" + i + "_CPLNum' name='" + whichPart + "_" + i + "_CPL' value=''></td>";
					break;
				case "HCCAT":
					serialnumfield      = "<td><input type='text' id='" + whichPart + "_" + i + "_Serial' name='"      + whichPart + "_" + i + "_Ser' value=''></td>";
					arrangementnumfield = "<td><input type='text' id='" + whichPart + "_" + i + "_Arrangement' name='" + whichPart + "_" + i + "_Arr' value=''></td>";
					break;
				case "HCDET":
					serialnumfield = "<td><input type='text' id='" + whichPart + "_" + i + "_Serial' name='" + whichPart + "_" + i + "_Ser' value=''></td>";
					break;
			}
			
			if (i==1) {
				// Load the headers
				var headers = "<tr>";
				
				headers = headers + "<td><br></td>";
				
				if (bearingsfield != "")       { headers = headers + "<td><b>Bearings</b></td>"; }
				if (pistonfield != "")         { headers = headers + "<td><b>Piston Size</b></td>"; }
				if (buildnumfield != "")       { headers = headers + "<td><b>Build Number</b></td>"; }
				if (cplnumfield != "")         { headers = headers + "<td><b>CPL Number</b></td>"; }
				if (serialnumfield != "")      { headers = headers + "<td><b>Serial Number</b></td>"; }
				if (arrangementnumfield != "") { headers = headers + "<td><b>Arrangement Number</b></td>"; }
			
				headers = headers + "</tr>";
			}
			
			// Load the line of fields
			partRows = partRows + "<tr>";
			partRows = partRows + "<td><b>" + whichPart + ": </b></td>";
			partRows = partRows + bearingsfield + pistonfield + buildnumfield + cplnumfield + serialnumfield + arrangementnumfield;
			partRows = partRows + "</tr>";	
		}
		
		panelContents.innerHTML = "<table border='0'>" + headers + partRows + "</table>";
	}
	if (whichAction == "CANCEL") {
		document.getElementById('BearingsSkirt').style.visibility = 'hidden';
		document.getElementById('BearingsPanel').style.visibility = 'hidden';
		document.getElementById('BearingsSkirt').style.height = '0px';
		document.getElementById('BearingsPanel').style.height = '0px';
		
		BearingsFormActivePart = "";
		BearingsFormActiveQty  = "";
	}
	if (whichAction == "DONE") {
		var BearingsFormReady = "YES";
		
		for (i=1 ;i<=BearingsFormActiveQty; i++) {
			var bearings    = document.getElementById(BearingsFormActivePart + "_" + i + "_Bearings");
			var pistons     = document.getElementById(BearingsFormActivePart + "_" + i + "_Piston");
			var buildnum    = document.getElementById(BearingsFormActivePart + "_" + i + "_Build");
			var cplnum      = document.getElementById(BearingsFormActivePart + "_" + i + "_CPLNum");
			var serialnum   = document.getElementById(BearingsFormActivePart + "_" + i + "_Serial");
			var arrangement = document.getElementById(BearingsFormActivePart + "_" + i + "_Arrangement");
			
			if (bearings != null) {
			if (bearings.value == "") {
				alert("Please enter a bearings size."); BearingsFormReady = "NO"; bearings.focus(); break;
			} else {
				document.getElementById("BEARING_" + BearingsFormActivePart + "_" + i + "0").value = bearings.value;
			}
			}
			if (pistons != null) {
			if (pistons.value == "") {
				alert("Please enter a pistons size."); BearingsFormReady = "NO"; pistons.focus(); break;
			} else {
				document.getElementById("PISTON_" + BearingsFormActivePart + "_" + i + "0").value = pistons.value;
			}
			}
			if (buildnum != null) {
			if (buildnum.value == "") {
				alert("Please enter a build number."); BearingsFormReady = "NO"; buildnum.focus(); break;
			} else {
				document.getElementById("BUILDNUM_" + BearingsFormActivePart + "_" + i + "0").value = buildnum.value;
			}
			}
			if (cplnum != null) {
			if (cplnum.value == "") {
				alert("Please enter a CPL number."); BearingsFormReady = "NO"; cplnum.focus(); break;
			} else {
				document.getElementById("CPLNUM_" + BearingsFormActivePart + "_" + i + "0").value = cplnum.value;
			}
			}
			if (serialnum != null) {
			if (serialnum.value == "") {
				alert("Please enter a serial number."); BearingsFormReady = "NO"; serialnum.focus(); break;
			} else {
				document.getElementById("SERIAL_" + BearingsFormActivePart + "_" + i + "0").value = serialnum.value;
			}
			}
			if (arrangement != null) {
			if (arrangement.value == "") {
				alert("Please enter an arrangement number."); BearingsFormReady = "NO"; arrangement.focus(); break;
			} else {
				document.getElementById("ARRANGEMENT_" + BearingsFormActivePart + "_" + i + "0").value = arrangement.value;
			}
			}
		}
		
		if (BearingsFormReady == "YES") {
			document.getElementById('BearingsSkirt').style.visibility = 'hidden';
			document.getElementById('BearingsPanel').style.visibility = 'hidden';
			document.getElementById('BearingsSkirt').style.height = '0px';
			document.getElementById('BearingsPanel').style.height = '0px';
			document.getElementById('OverhaulKitAlert_' + BearingsFormActivePart).innerHTML = "<img src='images/icon_check.png' width='15' height='15' border='0'>";
			
			DWREngine._execute(_ajaxConfig._cfscriptLocation, null, 'adjustBearingsFormsQTY', BearingsFormActiveQty, adjustBearingsFormsQTYResults);
			
			BearingsFormActivePart = "";
			BearingsFormActiveQty  = "";
		}
	}
}
function adjustBearingsFormsQTYResults(r) {
	if (r=="HIDE") {
		document.getElementById('sendOrderButton').innerHTML = "<a class='AddtoOrder' href='javascript:validateCheckout();' target='_self'>Send Order</a>";
		
		theCode = "";
		theCode = theCode + "<img src='images/icon_check.png' width='15' height='15' border='0'>";
		theCode = theCode + "<b>Bearing info has been added<br>";
		document.getElementById('OverhaulKitBearingsAlert').innerHTML = theCode;
	} else {
		document.getElementById('sendOrderButton').innerHTML = "<font class='AddtoOrderDISABLED'>Send Order</font>";
		
		theCode = "";
		theCode = theCode + "<img src='images/icon_alert.png' width='15' height='15' border='0'>";
		theCode = theCode + "<b>There are Overhaul Kit(s) in the order<br>";
		theCode = theCode + "Please enter a Bearings Size for these<br>";
		theCode = theCode + "by clicking on the alert icon.</b><br>";
		document.getElementById('OverhaulKitBearingsAlert').innerHTML = theCode;
	}
}

function validateCheckout() {
	document.getElementById('sendOrderButton').innerHTML = "<font class='AddtoOrderDISABLED'>Send Order</font>";
	
	if (document.CheckoutTableForm.username.value=="" || document.CheckoutTableForm.username.value==" ") {
		alert("Please Enter Your Name\nWe may have questions about the order.");
		document.CheckoutTableForm.username.focus();
		document.getElementByID('sendorderbutton').innerHTML = "<a class='AddtoOrder' href='javascript:validateCheckout();' target='_self'>Send Order</a>";
	} else {
		document.CheckoutTableForm.submit();
	}
}

function getOBSData(partNum,pricingView) {
	DWREngine._execute(_ajaxConfig._cfscriptLocation, null, 'getOBSPartData', partNum, pricingView, returnOBSDesc);
}

function returnOBSDesc(r) {
	if (r[0] != "ERROR") {
		var theDiv = r[1].partnum + "_OBS";
		document.getElementById(theDiv).innerHTML  = "Click to Add: " + r[1].partnum + "<br>" + r[1].partdesc + "<br>$" + r[1].partprice;
		document.getElementById(theDiv).style.visibility = "visible";
	} else {
		alert(r[0] + ": " + r[1]);
	}
}

function hideOBSDesc(which) {
	var theDiv = which + "_OBS";
	document.getElementById(theDiv).innerHTML  = "";
	document.getElementById(theDiv).style.visibility = "hidden";
}

function setInnerHTML(pricingView,partNum,partQty,partDes,partDST,partDLR,partCOR,partLST,partOBS) {
	// Create Row ////////////////////////////////////////////////////////////////////
	var tableRow = theTable.insertRow(theCurrentRow);
	tableRow.id  = "Row_" + partNum;

	if (theCurrentRow % 2 == 0) {
		tableRow.className = "light";
	} else {
		tableRow.className = "dark";
	}
	
	// Create Cells //////////////////////////////////////////////////////////////////
	var tableCell1 = tableRow.insertCell(0);
	var tableCell2 = tableRow.insertCell(1);
	var tableCell3 = tableRow.insertCell(2);
	var tableCell4 = tableRow.insertCell(3);
	var tableCell5 = tableRow.insertCell(4);
	var tableCell6 = tableRow.insertCell(5);
	var tableCell7 = tableRow.insertCell(6);
	var tableCell8 = tableRow.insertCell(7);
	var tableCell9 = tableRow.insertCell(8);
	var tableCell10 = tableRow.insertCell(9);
	var tableCell11 = tableRow.insertCell(10);
	var tableCell12 = tableRow.insertCell(11);
	var tableCell13 = tableRow.insertCell(12);
	var tableCell14 = tableRow.insertCell(13);
	var tableCell15 = tableRow.insertCell(14);
	var tableCell16 = tableRow.insertCell(15);
	var tableCell17 = tableRow.insertCell(16);
	var tableCell18 = tableRow.insertCell(17);
	var tableCell19 = tableRow.insertCell(18);
	var tableCell20 = tableRow.insertCell(19);
	
	// Format Cells //////////////////////////////////////////////////////////////////
	// Height
	tableCell1.height = "22px";
	
	// Aignment
	tableCell1.align  = "center";  // Spacer
	tableCell2.align  = "center";  // Delete
	tableCell3.align  = "center";  // Spacer
	tableCell4.align  = "center";  // Part Status
	tableCell5.align  = "center";  // Quantity
	tableCell6.align  = "center";  // Availability Status
	tableCell7.align  = "center";  // Sale Status
	tableCell8.align  = "center";  // Free Shipping Status
	tableCell9.align  = "center";  // Hazard Status
	tableCell10.align = "center";  // Spacer
	tableCell11.align = "left";   // Part Number
	tableCell12.align = "center"; // Spacer
	tableCell13.align = "left";   // Description
	tableCell14.align = "center"; // Spacer
	tableCell15.align = "right";  // Item
	tableCell16.align = "center"; // Spacer
	tableCell17.align = "right";  // Dealer
	tableCell18.align = "center"; // Spacer
	tableCell19.align = "right";   // Distributor
	tableCell20.align = "center"; // Spacer
	
	// Load Cells Content ////////////////////////////////////////////////////////////
	if (theCurrentRow % 2 == 0) {
		tableCell1.innerHTML  = "<img src=\"images/orderformSide_L_light.png\" width=\"10\" height=\"22\" valign=\"top\">";	// Spacer
	} else {
		tableCell1.innerHTML  = "<img src=\"images/orderformSide_L_dark.png\" width=\"10\" height=\"22\" valign=\"top\">";	// Spacer
	}
	
	if (partOBS == "YES") {
		tableCell2.innerHTML  = "<input type='checkbox' CHECKED name='" + partNum+ "_del' id='" + partNum + "_del' onClick=\"javascript:setDeleteList(" + theCurrentRow + ",'" + partNum + "');\"/>";  // Delete
		setDeleteList(theCurrentRow,partNum);
		//var obsoleteNoteText = "<br><img src='images/icon_obsolete.png' width='15' height='15' border='0'>";
		//obsoleteNoteText = obsoleteNoteText + "<b> These will be removed when the order is finalized.</b>";
		var obsoleteNoteText = "";
	} else {
		tableCell2.innerHTML  = "<input type='checkbox' name='" + partNum+ "_del' id='" + partNum + "_del' onClick=\"javascript:setDeleteList(" + theCurrentRow + ",'" + partNum + "');\"/>";  // Delete
		var obsoleteNoteText = "";
	}
	
	document.getElementById("obsoleteNote").innerHTML = obsoleteNoteText;
	
	tableCell3.innerHTML  = "<br />";  // Spacer
	
	if (partDes == "Multiple Parts Found") {
		tableCell4.innerHTML  = PartStatusImage;     // Edit
	} else if (partOBS == "YES") {
		tableCell4.innerHTML  = "<img src='images/icon_obsolete.png' border='0'>";     // Edit
	} else {
		if (partOBS != "YES") {
			tableCell4.innerHTML  = "<a href='#' onClick=\"javascript:openEdit('" + pricingView + "'," + theCurrentRow + ");\">" + PartStatusImage + "</a>";     // Edit
		}
	}
	
	if (partOBS == "YES") {
		tableCell5.innerHTML  = "<font class='PL_SM_Bold'><font color='#999999'>--</font></font>";   // Quantity
	} else {
		tableCell5.innerHTML  = "<font class='PL_SM_Bold'>" + partQty + "</font>";   // Quantity
	}
	
	tableCell6.innerHTML  = "<img src='images/icon_" + AvailStatusImage  + "' id='Availability'   width='15' height='15' border='0'>";  // Availability Status
	tableCell7.innerHTML  = "<img src='images/icon_" + SaleStatusImage   + "' id='SaleStatus'     width='15' height='15' border='0'>";  // Sale Status
	tableCell8.innerHTML  = "<img src='images/icon_" + ShipStatusImage   + "' id='ShippingStatus' width='15' height='15' border='0'>";  // Free Shipping Status
	tableCell9.innerHTML  = "<img src='images/icon_" + HazardStatusImage + "' id='Hazardous'      width='15' height='15' border='0'>";  // Hazard Status
	tableCell10.innerHTML  = "<br />";  // Spacer
	
	if (partOBS == "YES") {
		tableCell11.innerHTML  = "<font class='PL_SM_Bold'><font color='#990000'>" + partNum.toUpperCase() + "</font></font>";   // Part Number
	} else {
		tableCell11.innerHTML  = "<font class='PL_SM_Bold'>" + partNum.toUpperCase() + "</font>";   // Part Number
	}
	
	tableCell12.innerHTML  = "<br />";  // Spacer
	
	partDes = partDes.replace(/\"\"/g,"~");
	partDes = partDes.replace(/\"/g,"");
	partDes = partDes.replace(/~/g,"\"");
	
	if (partDes == "Multiple Parts Found") {
		tableCell13.innerHTML  = "<a class='PL_DescRed' href='javascript:openMultiple(\"" + partNum + "\",\"\",\"" + partQty + "\",\"DISPLAY\");'>" + partDes + "</a>";   // Description
	} else {
		if (partOBS == "YES") {
			document.getElementById('button_delete').src = "images/button_delete_DIM.png";
			
			if (partDes == "** NO LONGER AVAILABLE **") {
				tableCell13.innerHTML = "<font color='#990000'><b>" + partDes + "</b></font>";   // Description
			} else {
				// Strip the Asterisks and USE
				descTemp = partDes.replace(/\x2a/g, "");
				descTemp = descTemp.replace(/USE/g, "");
				 
				// Extract the Part Numbers
				descPartNums = descTemp.split(" OR ");
				
				// Rebuild the Description
				var newDesc = "";
				newDesc = newDesc + "<div id='descriptionHolder' style='position:relative;'>";
				newDesc = newDesc + "USE ";
				
				for (i=0 ; i<descPartNums.length; i++) {
					newDesc = newDesc + "<a class='ViewAll'";
					newDesc = newDesc + " href='javascript:doAddPart(\"" + trim(descPartNums[i]) + "\",\"?\",1," + theCurrentRow + ",\"" + partNum + "\");'";
					newDesc = newDesc + " onmouseover='getOBSData(\"" + trim(descPartNums[i]) + "\",\"" + pricingView + "\");'";
					newDesc = newDesc + " onmouseout='hideOBSDesc(\"" + trim(descPartNums[i]) + "\");'>";
					newDesc = newDesc + trim(descPartNums[i]) + "</a>";
					newDesc = newDesc + "<div id='" + trim(descPartNums[i]) + "_OBS' style='position:absolute;top:-40px;left:0px;padding:2px;color:#000000;background-color:#FFFFFF;border:1px solid #000000;visibility:hidden'></div>";
					
					if (i != descPartNums.length-1) { newDesc = newDesc + "  OR "; }
				}
				newDesc = newDesc + "</div>";
				tableCell13.innerHTML = "<font color='#990000'><b>" + newDesc + "</b></font>";   // Description
			}			
		} else {
			var theLink = "<a class='PL_Desc' href='#' onMouseOver=\"javascript:showDescription(" + theCurrentRow + ");\">";
		
			if (partDes.length > 50) {
				var theDescription = partDes.substring(0,50) + "...";
			} else {
				var theDescription = partDes;
			}
		
			tableCell13.innerHTML = theLink + theDescription + "</a>";   // Description
		}
	}
	
	tableCell14.innerHTML  = "<br />";  // Spacer
	
	// These columns change based on the Viewing Mode and Selected Pricing View ///////
	if (partDes != "Multiple Parts Found"){
		switch(pricingView) {
			case "NONE":
				// Column Headers are: Empty. We don't show any pricing to the general public.
				var column1price = "";
				var column2price = "";
				var column3price = "";
				break;
			case "LIST":
				// Column Headers are: Item, Core, List
				var column1price = outputMoney(partLST);
				var column2price = outputMoney(partCOR);
				var column3price = outputMoney(partLST * partQty);
				break;
			case "DEAL":
				// Column Headers are: Item, Core, Deal
				var column1price = outputMoney(partDLR);
				var column2price = outputMoney(partCOR);
				var column3price = outputMoney(partDLR * partQty);
				break;
			case "DIST":
				// Column Headers are: Item, Deal, Dist
				var column1price = outputMoney(partDST);
				var column2price = outputMoney(partCOR);
				var column3price = outputMoney(partDST * partQty);
				break;
			default:
				var column1price = "ERR";
				var column2price = "ERR";
				var column3price = "ERR";
				break;
		}
		
		if (partOBS == "YES") {
			tableCell15.innerHTML = "<font class='PL_SM_Bold'><font color='#999999'>---.--</font></font>";   // Column 1
			tableCell16.innerHTML = "<br />";  												  // Spacer
			tableCell17.innerHTML = "<font class='PL_SM_Bold'><font color='#999999'>---.--</font></font>";   // Column 2
			tableCell18.innerHTML = "<br />";  												  // Spacer
			tableCell19.innerHTML = "<font class='PL_SM_Bold'><font color='#999999'>---.--</font></font>";   // Column 3
		} else {
			tableCell15.innerHTML = "<font class='PL_SM_Bold'>" + column1price + "</font>";   // Column 1
			tableCell16.innerHTML = "<br />";  												  // Spacer
			tableCell17.innerHTML = "<font class='PL_SM_Bold'>" + column2price + "</font>";   // Column 2
			tableCell18.innerHTML = "<br />";  												  // Spacer
			tableCell19.innerHTML = "<font class='PL_SM_Bold'>" + column3price + "</font>";   // Column 3
		}
	} else {
		tableCell15.innerHTML = "<font class='PL_SM_Bold'></font>";   // Column 1
		tableCell16.innerHTML = "<br />";  												  // Spacer
		tableCell17.innerHTML = "<font class='PL_SM_Bold'></font>";   // Column 2
		tableCell18.innerHTML = "<br />";  												  // Spacer
		tableCell19.innerHTML = "<font class='PL_SM_Bold'></font>";   // Column 3
	}
	///////////////////////////////////////////////////////////////////////////////////
	
	if (theCurrentRow % 2 == 0) {
		tableCell20.innerHTML  = "<img src=\"images/orderformSide_R_light.png\" width=\"10\" height=\"22\" valign=\"top\">";	// Spacer
	} else {
		tableCell20.innerHTML  = "<img src=\"images/orderformSide_R_dark.png\" width=\"10\" height=\"22\" valign=\"top\">";	// Spacer
	}
	
	if (theCurrentRow == 2) {
		document.getElementById("PartListEmptyWarning").innerHTML  = "";
	}
	theCurrentRow = (theCurrentRow + 1);
}

// MISCELLANEOUS FUNCTIONS ////////////////////////////////////////////////////////////////////////
function disableEnterKey(e) {
	var key;
	if(window.event) {
		key = window.event.keyCode;   //IE
	} else {
		key = e.which;   //firefox
	}
	if(key == 13) {
		return false;
	} else {
		return true;
	}
}
function outputMoney(number) {
	return "$ " + outputDollars(Math.floor(number-0) + '') + outputCents(number - 0);
}
function outputDollars(number) {
	if (number.length <= 3) {
		return (number == '' ? '0' : number);
	} else {
		var mod = number.length%3;
		var output = (mod == 0 ? '' : (number.substring(0,mod)));
		
		for (i=0 ; i < Math.floor(number.length/3) ; i++) {
			if ((mod ==0) && (i ==0)) {
				output+= number.substring(mod+3*i,mod+3*i+3);
			} else {
				output+= ',' + number.substring(mod+3*i,mod+3*i+3);
			}
		}
		return (output);
	}
}
function outputCents(amount) {
   	amount = Math.round( ( (amount) - Math.floor(amount) ) *100);
	return (amount < 10 ? '.0' + amount : '.' + amount);
}

function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}
function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}
