/*		configurator.js
	JavaScript for the Vode Configurator application
	Created 28 March 2006 by Paul Novitski
	Last revised:
*/

//-------------------------
// set initializer to execute on page load
//-------------------------
//alert("hi");
/*
var loadCF = window.onload;

window.onload = function()
{
		if (loadCF) loadCF();
	jsConfiguratorInit();
}
*/

//-------------------------
// global variables
//-------------------------


var sBodyClass = "";
var regOptionClass = /((^|.* )group_[a-z]_option_)(\d+)( .*|$)/;
	// [0] = whole string
	// [1] = prefix
	// [2] = group_x_option
	// [3] = option#
	// [4] = suffix

var regDisabledClass = /(^| )disabled( |$)/;

var aRailLengthInputs = new Array();
var aRails = new Array();
var iZeroRailCount = 0;
var aRailLengthOptions = new Array(2, 3, 4, 5, 8);
var iLastSelectedLayoutSegment = 0;
var iLayoutLength;
var iInputTotal;

jsConfiguratorInit();


//=========================
function jsConfiguratorInit()
//=========================
{

//alert("hello");

		// ensure DOM support
		if (!document.getElementById) return;
		if (!document.getElementsByTagName) return;

	//jsConfiguratorNext();
	
	jsConfiguratorVoltageSubmitInit();
	jsConfiguratorRollovers();
	jsConfiguratorFormSubmitInit();
	
	jsConfiguratorLayoutSubmitInit();
	
	jsConfiguratorEditButtonsInit();
	
	jsConfiguratorLayoutSelectInit();
	
	jsConfiguratorCustomLayoutSubmitInit();
	
	jsConfiguratorVoltageEval()
	
	jsConfiguratorOptionsEval();
	
	jsConfiguratorEmergencyEval();
	
	//jsConfiguratorShowHideDetails();

}


//=========================
function jsConfiguratorRollovers()
//=========================
{
	
	//-------------------------
	// validate page
	//-------------------------
	var sRegExp = new RegExp("(^| )step_switches( |$)");
	
	// this must be the right page
	if (sRegExp.test(document.body.className)) return;
	
	// apply rollover behavior to option buttons
	//alert("document.body.className = " + document.body.className);
	sBodyClass = document.body.className;

	//alert("regOptionClass = " + regOptionClass.source);
		
	// get container
	var oInputBlock = document.getElementById("inputblock");
		if (!oInputBlock) return;
	
	// get array of option list items
	var aListItems = oInputBlock.getElementsByTagName("LI");
	//alert("typeof(aListItems) = " + typeof(aListItems));
	
	for (var iLI=0; iLI < aListItems.length; iLI++)
	{
		//var sClass = new String(aListItems[iLI].className);
		var sClass = aListItems[iLI].className;
		//alert("sClass = " + sClass);
		
			if (sClass && sClass > "")
			{
				var aMatches = regOptionClass.exec(sClass);
				var bDisabled = regDisabledClass.test(sClass);
				var bRadio = (aListItems[iLI].getAttribute("type") == "radio");

				//alertMatches(regOptionClass, sClass);

				//alert("typeof(aMatches) = " + typeof(aMatches));
					//if (bDisabled) alert("option " + iLI + " is disabled");

					if (!bDisabled && aMatches && aMatches.length && aMatches.length>0)
					{
						//alert(aMatches.join("\n"));
						aListItems[iLI].onmouseover = jsConfiguratorMouseover;
						aListItems[iLI].onmouseout = jsConfiguratorMouseout;
						
							if (bRadio)
							{
								aListItems[iLI].onclick = jsConfiguratorMouseClickSubmit;
							}else{
								aListItems[iLI].onclick = jsConfiguratorMouseClick;
							}
					}
			}
	}
//alert("OK so far");
//alert("END FUNCTION: document.body.className = " + document.body.className);
}



//=========================
function jsConfiguratorMouseClickSubmit(evt)
//=========================
{
	jsConfiguratorMouseClick(evt);
	
	this.form.submit();
}



//=========================
function jsConfiguratorMouseClick(evt)
//=========================
{
	// cancel event-bubbling
		if (evt) { event = evt; }
	event.cancelBubble = true;

	jsConfiguratorSetBodyClass(this.className);
	//alert("sBodyClassNew = " + document.body.className);
/*
//alertMatches(regOptionClass, this.className);

	// get current group & option number
	var aMatches = regOptionClass.exec(this.className);
		
	var sOptionClass = aMatches[3];
//alert("sOptionClass = " + sOptionClass);

	var regBodyClass = new RegExp("((^|.* )" + aMatches[1] + ")(\\d+)( .*|$)");
//alert("regBodyClass.source = " + regBodyClass.source);

//alertMatches(regBodyClass, document.body.className);

	var aMatches = regBodyClass.exec(document.body.className);

	var sBodyClassNew = document.body.className.replace(regBodyClass, "$1" + sOptionClass + " $4");
/ *
alert("R: '" + regBodyClass.source + "'\n" +
	  "B: '" + document.body.className + "'\n" +
	  "A:  '" + sBodyClassNew + "'");
return false;
* /	
	document.body.className = sBodyClassNew;
	//alert("sBodyClassNew = " + sBodyClassNew);
*/
	// make this one stick
	sBodyClass = document.body.className;
	
	// get the option value from the link
	
	// drill down to the anchor
	oLink = this;
//alert(oLink.tagName + ".getAttribute('href') = " + oLink.getAttribute("href"));

	while (!oLink.getAttribute("href"))
	{
		var aAnchors = oLink.getElementsByTagName("A");
//alert("aAnchors.length = " + aAnchors.length );
			if (!aAnchors || aAnchors.length == 0) return;
		oLink = aAnchors[0];
//alert(oLink.tagName + ".getAttribute('href') = " + oLink.getAttribute("href"));
	}
	
	var sHref = oLink.getAttribute("href");
//alert("sHref = " + sHref );
	
	var regOptionHref = /\?.*option=([^&]+)(\&|$)/;
	var aMatches = regOptionHref.exec(sHref);
	//alert("aMatches = " + aMatches[0] + ", " + aMatches[1] + ", " + aMatches[2]);
	//alert("option = " + aMatches[1]);

	var oHidden = document.getElementById("hiddenOption");
		if (oHidden)
		{
			oHidden.setAttribute("value", aMatches[1]);
		}
//alert(oHidden.parentNode.innerHTML);

	// suppress hyperlink
	//return false;
}

//=========================
function jsConfiguratorMouseover(evt)
//=========================
{
	// cancel event-bubbling
		if (evt) { event = evt; }
	event.cancelBubble = true;

	jsConfiguratorSetBodyClass(this.className);
/*
	//alert("document.body.className = " + document.body.className);
	var aMatches = regOptionClass.exec(this.className);
	//alert(aMatches.join("\n"));
	//alert("this.className = " + this.tagName + "." + this.className + "\n'" + aMatches.join("'\n'"));
	document.body.className = document.body.className.replace(regOptionClass, "$1 " + aMatches[0] + " $3");
*/
	//alert("BEFORE: '" + sBodyClass + "'\n" + "AFTER: '" + document.body.className + "'");
/*
*/	
	return false;
}


//=========================
function jsConfiguratorSetBodyClass(sClassName)
//=========================
{
//alertMatches(regOptionClass, this.className);

	// get current group & option number
	var aMatches = regOptionClass.exec(sClassName);
		
	var sOptionClass = aMatches[3];
//alert("sOptionClass = " + sOptionClass);

	var regBodyClass = new RegExp("((^|.* )" + aMatches[1] + ")(\\d+)( .*|$)");
//alert("regBodyClass.source = " + regBodyClass.source);

//alertMatches(regBodyClass, document.body.className);

	var aMatches = regBodyClass.exec(document.body.className);

	var sBodyClassNew = document.body.className.replace(regBodyClass, "$1" + sOptionClass + " $4");

/*
alert("R: '" + regBodyClass.source + "'\n" +
	  "B: '" + document.body.className + "'\n" +
	  "A:  '" + sBodyClassNew + "'");
return false;
*/	

	document.body.className = sBodyClassNew;
	//alert("sBodyClassNew = " + sBodyClassNew);

	jsConfiguratorDisplayBodyClass();
	
}


//=========================
function jsConfiguratorMouseout(evt)
//=========================
{
	// cancel event-bubbling
		if (evt) { event = evt; }
	event.cancelBubble = true;

	if (sBodyClass && sBodyClass > "") document.body.className = sBodyClass;

	jsConfiguratorDisplayBodyClass();
	
}


//=========================
function jsConfiguratorDisplayBodyClass()
//=========================
{
	window.status = document.body.className;
	//alert(document.body.className);
}


//=========================
function jsConfiguratorNext()
//=========================
{
	var oButton = document.getElementById("buttonNextA");
		if (!oButton) return;

	//var aAnchors = oButton.getElementsByTagName("A");

	//alert(aAnchors[0].innerHTML);
	oButton.onclick = function()
	{
		document.forms[0].submit();
		return false;
	}
	//alert(oButton.onclick);
}


//=========================
function jsConfiguratorShowHideDetails()
//=========================
{
	// get container
	var oShowHide = document.getElementById("showdetails");
		if (!oShowHide) return;
	
	var aAnchors = oShowHide.getElementsByTagName("A");

		if (aAnchors[0]) aAnchors[0].onclick = jsConfiguratorShowHideDetailsClick;
//alert("OK");
}


//=========================
function jsConfiguratorShowHideDetailsClick(evt)
//=========================
{
	// cancel event-bubbling
		if (evt) { event = evt; }
	event.cancelBubble = true;
	
	// remove unsightly dotted line
	this.blur();

	// change body class
	document.body.className = jsConfiguratorShowHideDetailsToggle(document.body.className, "lower");
	
	// change display text
	var aSpans = this.getElementsByTagName("span");
		if (!aSpans[0]) return;	// alert("Can't find span");
		
	var sText = aSpans[0].firstChild.nodeValue;
	//alert("sText = " + sText);
	sText = jsConfiguratorShowHideDetailsToggle(sText, "Initial");
	//alert("sText = " + sText);
	aSpans[0].firstChild.nodeValue = sText;

	// change link href
	sText = this.getAttribute("href");
	sText = jsConfiguratorShowHideDetailsToggle(sText, "lower");
	this.setAttribute("href", sText);

	// change hidden field
	var oShowHide = document.getElementById("hiddenShowHide");
		if (!oShowHide) return;
	sText = oShowHide.getAttribute("value");
	sText = jsConfiguratorShowHideDetailsToggle(sText, "lower");
	oShowHide.setAttribute("value", sText);
	//alert(oShowHide.parentNode.innerHTML);

	return true;
}


//=========================
function jsConfiguratorShowHideDetailsToggle(sString, sCase)
//=========================
{
	//alert("function jsConfiguratorShowHideDetailsToggle(" + sString + ", " + sCase + ")");

		if (sCase == "lower")
		{
			sShow = "show";
			sHide = "hide";
			sDetails = "details";
			var regShowHide = /(show|hide)(details)/;
		}else{
			sShow = "Show";
			sHide = "Hide";
			sDetails = " Details";
			var regShowHide = /(Show|Hide)( Details)/i;
		}

	//var regShowHide = new RegExp("(" + sShow + "|" + sHide + ")(" + sDetails + ")");
	//alert("regShowHide.source = " + regShowHide.source);
	var aMatches = regShowHide.exec(sString);
	//alert("aMatches.length = " + aMatches.length);
	
	sMsg = "Matches:";
	for (var i = 0; i < aMatches.length; i++)
	{
		sMsg += "\n" + i + ":" + aMatches[i];
	}
	//alert(sMsg);
	
		if (aMatches[1] == sShow)
		{
			sReplacement = sHide;
		}else{
			sReplacement = sShow;
		}

	// toggle body class
	var sText = sString.replace(regShowHide, sReplacement + "$2");
	//alert("BEFORE: " + sString + "\nAFTER: " + sText);
	
	return sText;
}


//=========================
function alertMatches(rRegExp, sClass)
//=========================
{
//alert("function alertMatches(\n'" + rRegExp.source + "', \n'" + sClass + "')");
	var aMatches = rRegExp.exec(sClass);

		if (!aMatches)
		{
			return;	//alert("alertMatches():  aMatches is null");
		}

	var sMsg = "REGEXP: '" + rRegExp.source + "'\n" +
		   "Class: '" + sClass + "'\n" +
		   "Matches: '" + aMatches.length + "'\n\n";

	//alert(sMsg);

	for (iMatch=0; iMatch < aMatches.length; iMatch++)
	{
		sMsg += "\n" + iMatch + ": '" + aMatches[iMatch] + "'";
	}
	//alert(sMsg);
}


//=========================
function jsConfiguratorFormSubmitInit()
//=========================
// add submit() behavior to the SELECT list
{
	//alert("function jsConfiguratorFormSubmitInit()");

	// step 5, pick up custom select box input
	var oObj20 = document.getElementById("select_a_20");
	var oObj12 = document.getElementById("select_a_12");
	var oObj10 = document.getElementById("select_a_10");
	if (!oObj20 && !oObj12 && !oObj10) return;
	
	if (oObj20) { oObj20.onchange = jsConfiguratorSubmit; }
	if (oObj12) { oObj12.onchange = jsConfiguratorSubmit; }
	if (oObj10){ oObj10.onchange = jsConfiguratorSubmit; }
	//alert("oObj.onchange = jsConfiguratorSubmit;");
}


//=========================
function jsConfiguratorVoltageSubmitInit()
//=========================
// add submit() behavior to the Voltage radio buttons
{

	//-------------------------
	// validate page
	//-------------------------
	var sRegExp = new RegExp("(^| )step_ballast( |$)");
	
		// this must be the right page
		if (!sRegExp.test(document.body.className)) return;

	var oPanel = document.getElementById("inputblock");
		if (!oPanel) return;

	var aULs = oPanel.getElementsByTagName("UL");
		if (!aULs || aULs.length == 0) return;

	// look for radio list
	var bFoundIt = false;
	sRegExp = new RegExp("(^| )options_radio( |$)");
	
	for (var iUL = 0; iUL < aULs.length; iUL++)
	{
		var oUL = aULs[iUL];
			if (sRegExp.test(oUL.className))
			{
				bFoundIt = true;
				break;
			}
	}	
//alert('bFoundIt = ' + bFoundIt);
		// can't find it?
		if (!bFoundIt) return;

	//alert(oUL.innerHTML);

	// get all the INPUT fields
	var aEls = oUL.getElementsByTagName("INPUT");

		if (!aEls || aEls.length == 0) return alert('No INPUT elements found');

	// apply behavior
	for (var iEl = 0; iEl < aEls.length; iEl++)
	{
		aEls[iEl].onclick = jsConfiguratorSubmit;
		//alert(aEls[iEl].parentNode.innerHTML);
	}
}


//=========================
function jsConfiguratorLayoutSubmitInit()
//=========================
// add submit() behavior to the SELECT list
// remove the Enter button from display
{
	//alert("function jsConfiguratorLayoutSubmitInit()");

	//-------------------------
	// validate page
	//-------------------------
	var sRegExp = new RegExp("(^| )step_layout( |$)");
	//alert("sRegExp.source = " + sRegExp.source);
	
	
	//alert("document.body.className = " + document.body.className);
	//alert("sRegExp.test(document.body.className) = " + sRegExp.test(document.body.className));
	
		// this must be the layout page
		if (!sRegExp.test(document.body.className)) return; //alert("body class doesn't contain 'step_layout'");

	var oPanel = document.getElementById("inputblock");
		if (!oPanel) return; //alert("Can't find 'inputblock'");
	//alert("Found 'inputblock'");

	var aEls = oPanel.getElementsByTagName("SELECT");
	//alert("Found " + aEls.length + " SELECT elements");
		if (!aEls || aEls.length != 1) return;

	//aEls[0].onChange = jsConfiguratorSubmit;
	
	//-------------------------
	// add submit() behavior to layout length SELECT
	//-------------------------
	var oObj = document.getElementById("select_length_0");
		if (!oObj) return;
	
	oObj.onchange = jsConfiguratorSubmit;
//alert("OK so far");
	

	//-------------------------
	// remove the Enter button from display
	//-------------------------
	var aEls = oPanel.getElementsByTagName("INPUT");
		if (!aEls || aEls.length != 1) return; //alert("Can't find 'INPUT elements");

	//aEls[0].style.visibility = "hidden";
	aEls[0].style.display = "none";
	aEls[0].parentNode.style.display = "none";
}

//=========================
function jsConfiguratorCustomLayoutSubmitInit()
//=========================
// add submit() behavior to the Custom SELECT list items
// remove the Enter button from display
{
	//alert("function jsConfiguratorCustomLayoutSubmitInit()");

	//-------------------------
	// validate page
	//-------------------------
	var sRegExp = new RegExp("(^| )step_layout( |$)");
	//alert("sRegExp.source = " + sRegExp.source);
	
	
	//alert("document.body.className = " + document.body.className);
	//alert("sRegExp.test(document.body.className) = " + sRegExp.test(document.body.className));
	
		// this must be the layout page
		if (!sRegExp.test(document.body.className)) return; //alert("body class doesn't contain 'step_layout'");

	var oPanel = document.getElementById("inputblock");
		if (!oPanel) { 
		
			alert("Can't find 'inputblock'");
			return; 
		}
	//alert("Found 'inputblock'");

	var aEls = oPanel.getElementsByTagName("SELECT");
	//alert("Found " + aEls.length + " SELECT elements");
		if (!aEls || aEls.length != 1) {
		
			alert("Error: aE1s is not 1");
			return;
		}
	//aEls[0].onChange = jsConfiguratorSubmit;
	
	// appended code
	
	var sRegExp = new RegExp("(^| )step_layout( |$)");
		if (!sRegExp.test(document.body.className)) {
		alert("body class isn't step_layout");
		return; 
	}
	//alert("Found " + sRegExp + " elements");
	// get total layout length
	var oLength = document.getElementById("select_length_0"); // that's the select box that determines the feet length 
		if (!oLength) return alert("Error: Can't find select_length_0");
	//alert("Found oLength=" + oLength);
	iLayoutLength = parseInt(oLength.options[oLength.selectedIndex].value);
		if (!iLayoutLength || iLayoutLength < 1) {
			//alert("Error: not a valid layout length");
			return;
		}
	//alert("Found iLayoutLength=" + iLayoutLength);
	// find the right section
	var oDetailsBlock = document.getElementById("choiceDetail");
		if (!oDetailsBlock) {
			alert("Error: can't find choiceDetail element");
			return;
			}
	
	// grab ordered lists	
	var cs = document.getElementById("customSelect");
	//var aLists = cs.getElementsByTagName("UL");
	var aLists = cs.getElementsByTagName("SELECT");
		if (!aLists || aLists.length == 0) {
		
			alert("Error: aLists is 0");
			return;
		}
	//alert("Found aLists=" + aLists);
	// get the first list
	var oList = aLists[0];
	var oList1 = aLists[1];
	//alert("Found first list item=" + oList.options[oList.selectedIndex].value + "\n\n" + "second list item = " + oList1.options[oList1.selectedIndex].value);
	// make sure it's the right list
	/*
	sRegExp = new RegExp("(^| )layout( |$)");
		if (!sRegExp.test(oList.className)) {
		
			alert("Error: sRegExp doesn't equal oList.className");
			return;
		}
	// get all descendant SELECT elements
	aRailLengthInputs = oList.getElementsByTagName("SELECT");
	var test = aRailLengthInputs[0];
	*/
	
	//alert("aLists first element, selected index=" + oList.options[oList.selectedIndex].text);
	/*
		if (!aRailLengthInputs || aRailLengthInputs.length == 0){
			alert("Error: aRailLengthInputs is 0");
		 	return;
		}
	*/
	// create an array of rail lengths & apply behavior
	//alert("aLists.size()="+aLists.length);
	var totalLength=0;
	for (var iRail=0; iRail < aLists.length; iRail++)
	{
		var onerail = aLists[iRail];
		var oRailSelect = onerail.options[onerail.selectedIndex].text;
		//alert("oRailSelect="+oRailSelect);
		railLength = parseInt(oRailSelect);
		if (railLength > 0) {
			//alert("railLength="+railLength);
			totalLength = totalLength + railLength;
			//alert("totalLength="+totalLength);
		}
	}


	//alert("iLayoutLength = " + iLayoutLength + "\n\n" +
	//	  "number of rails = " + aLists.length + "\n\n" +
	//	  "total selected length = " + totalLength);

	if (totalLength == iLayoutLength) {
		//alert("Total length must equal " + iLayoutLength);
		//return;
		var oControl = document.getElementById("chooseAndContinue");
		if (oControl)
		{
			oControl.disabled = false; 

		}
		
	} else {
		var oControl = document.getElementById("chooseAndContinue");
		if (oControl)
		{
			oControl.disabled = true; 

		}
		// CR: 09-16-2009 updating the running total display 
		if (document.getElementById('layout_running_total'))
			document.getElementById('layout_running_total').innerHTML = String(totalLength);
		/*
		 * CR: 09-16-2009 we don't want to attempt trying to fix the overload
		if (false && totalLength > iLayoutLength) { // here we're trying to fix stuff
			for (var iRail=aLists.length-1; iRail > 0; iRail--)
			{
				
				if (totalLength > iLayoutLength) {
					var onerail = aLists[iRail];
					var oRailSelect = onerail.options[onerail.selectedIndex].text;
					//alert("oRailSelect="+oRailSelect);
					railLength = parseInt(oRailSelect);
					diff = totalLength - iLayoutLength;
					if (railLength > 0) {
						//alert("railLength="+railLength);
						setAmount = railLength - diff;
						
							onerail.options[onerail.selectedIndex].text = railLength - setAmount;

					}
					totalLength = 0;
					for (var x=0; x < aLists.length; x++)
					{
						var onerail = aLists[x];
						var oSelect = onerail.options[onerail.selectedIndex].text;
						//alert("oRailSelect="+oRailSelect);
						oLength = parseInt(oSelect);
						if (oLength > 0) {
							//alert("railLength="+railLength);
							totalLength = totalLength + oLength;
							//alert("totalLength="+totalLength);
						}
					}
				}
			}
			
			*/
			
			
			
			
			/*
			
			var onerail = aLists[aLists.length-1];
			var oRailSelect = onerail.options[onerail.selectedIndex].text;
			//alert("oRailSelect="+oRailSelect);
			railLength = parseInt(oRailSelect);
			diff = totalLength - iLayoutLength;
			if (railLength > 0) {
				//alert("railLength="+railLength);
				setAmount = railLength - diff;
				if (setAmount == 0) {
					onerail.options[onerail.selectedIndex].text = "";
				} else {
					onerail.options[onerail.selectedIndex].text = setAmount;
				}
				
				
				//onerail.disabled = true;
				//alert("totalLength="+totalLength);
			} else {
				//onerail.disabled = true;
				var anotherrail = aLists[aLists.length-2];
				var oARailSelect = anotherrail.options[anotherrail.selectedIndex].text;
				alert("oARailSelect="+oARailSelect);
				aLength = parseInt(oARailSelect);
				anotherrail.options[anotherrail.selectedIndex].text = aLength - diff;
			}
			*/
			//alert("The total length must equal " + iLayoutLength);
		//}
		
	} 
	for (var iRail=0; iRail < aLists.length; iRail++)
	{
		aLists[iRail].onchange = jsConfiguratorSubmit;
	}
	
	//appended code
	
	
	//-------------------------
	// add submit() behavior to layout length SELECT
	//-------------------------
	//var oObj = document.getElementById("array_layout_a_layout_1");
	//	if (!oObj) return;
	
	//oObj.onchange = jsConfiguratorSubmit;
//alert("OK so far");
	


}

//=========================
function jsConfiguratorVoltageEval()
//=========================
// evalutate user input voltage choices for step 7
// 
{
	
	//-------------------------
	// validate page
	//-------------------------
	var sRegExp = new RegExp("(^| )step_ballast( |$)");
	
	// this must be the ballast/voltage page
	if (!sRegExp.test(document.body.className)) return; //alert("body class doesn't contain 'step_layout'");

	var oPanel = document.getElementById("inputblock");
		if (!oPanel) { 
		
			alert("jsConfiguratorVoltageEval() - Can't find 'inputblock'");
			return; 
		}
	
	var aEls = oPanel.getElementsByTagName("input");
	//alert("Found " + aEls.length + " SELECT elements");
		if (!aEls) {
		
			alert("Error: can't find aE1s");
			return;
		}
	
	//alert("jsConfiguratorVoltageEval:aEls.length="+ aEls.length);
		
	for (var iNum=0; iNum < aEls.length; iNum++)
	{
				
		// addEvent works for IE and FF, while onchange only works with FF
		addEvent0(aEls[iNum], 'click', jsConfiguratorSubmit);
	}
	
	
}




//=========================
function jsConfiguratorOptionsEval()
//=========================
// evalutate user input choices for step 12
// 
{
	
	//-------------------------
	// validate page
	//-------------------------
	var sRegExp = new RegExp("(^| )step_switches( |$)");
	
	// this must be the switches page
	if (!sRegExp.test(document.body.className)) return; //alert("body class doesn't contain 'step_layout'");

	var oPanel = document.getElementById("inputblock");
		if (!oPanel) { 
		
			//alert("Can't find 'inputblock'");
			return; 
		}
	//alert("Found 'inputblock'");

		var aEls = oPanel.getElementsByTagName("input");
		//alert("Found " + aEls.length + " SELECT elements");
			if (!aEls) {
			
				alert("Error: can't find aE1s");
				return;
			}
		
			///made to handle the BRAND A autosubmit
			var oPanelSelect = document.getElementById("choiceDetail");
			if (!oPanelSelect) { 
			
				//alert("Can't find 'inputblock'");
				return; 
			}

			var aElsSelect = oPanelSelect.getElementsByTagName("option");
			//alert("Found " + aEls.length + " SELECT elements");
				if (!aElsSelect) {
				
					alert("Error: can't find aE1s");
					return;
				}
				///
			
	//for (var iLoop=0; iLoop < aEls.length; iLoop++)
	//{
	//	aEls[iLoop].onchange = jsConfiguratorSubmit;
	//}
	// get checkbox 0 ("None") checked status - returns "true" if checked
	var oCB = document.getElementById("checkboxa_0");
	
	if (!oCB) return alert("Error: Can't find checkboxa_0");

	var oChildren = oPanel.childNodes;
	for (var iLoop=0; iLoop < aEls.length; iLoop++)
	{
		var el = aEls[iLoop];
			
		if (iLoop != 0) {
			el.onmousedown = function() { document.getElementById("checkboxa_0").checked = false; } ;
		} 
	}
	
	//alert("checkbox 0, checked attribute:" + oCB.hasAttribute("checked"));
	if (oCB.checked == true) {
	//if (oCB.hasAttribute("checked")) {
		// gray-out all-other options
		/*
		 * client doesn't want to disable options anymore, but uncheck "none" when checking another box
		var oChildren = oPanel.childNodes;
		for (var iLoop=0; iLoop < aEls.length; iLoop++)
		{
			var el = aEls[iLoop];
			
			if (iLoop != 0) {
				el.checked = false;
				el.disabled=true;
			} 
		}
		*/
	} else {
		
		var oChildren = oPanel.childNodes;
		for (var iLoop=0; iLoop < aEls.length; iLoop++)
		{
			var el = aEls[iLoop];
			//alert("looping oPanel children: el="+el);
			if (iLoop != 0) {
				
				el.disabled=false;
			} 
		}
	}
	//alert("jsConfiguratorOptionsEval:aEls.length="+ aEls.length);
		
	for (var iNum=0; iNum < aEls.length; iNum++)
	{
		//alert("jsConfiguratorOptionsEval:aEls[iNum]="+aEls[iNum].onchange);
		//aEls[iNum].onchange = jsConfiguratorSubmit;
		//addEvent0(aEls[iNum], 'change', jsConfiguratorSubmit);
		
		// addEvent works for IE and FF, while onchange only works with FF
		addEvent0(aEls[iNum], 'click', jsConfiguratorSubmit);
	}
	
	///made to handle BRAND A autosubmit
	for (var iNum=0; iNum < aElsSelect.length; iNum++)
	{
		//alert("jsConfiguratorOptionsEval:aEls[iNum]="+aEls[iNum].onchange);
		//aEls[iNum].onchange = jsConfiguratorSubmit;
		//addEvent0(aEls[iNum], 'change', jsConfiguratorSubmit);
		
		// addEvent works for IE and FF, while onchange only works with FF
		addEvent0(aElsSelect[iNum], 'click', jsConfiguratorSubmit);
	}
	///
	
	//oCB.onchange = jsConfiguratorSubmit;
	


}






//=========================
function jsConfiguratorEmergencyEval()
//=========================
//evalutate user input choices for step 8
//
{

	
	//-------------------------
	// validate page
	//-------------------------
	var sRegExp = new RegExp("(^| )step_emergency( |$)");
	
	// this must be the switches page
	if (!sRegExp.test(document.body.className)) return; //alert("body class doesn't contain 'step_layout'");
	///else


	var oPanel = document.getElementById("choiceDetail");

	var oPanelInput = document.getElementById("inputblock");

	if (!oPanel) { 
		
			//alert("Can't find 'inputblock'");
			return; 
		}

	//alert("Found 'inputblock'");

	var aEls = oPanel.getElementsByTagName("input");

	var aElsInput = oPanelInput.getElementsByTagName("li");

		if (!aEls) {
		
			alert("Error: can't find aE1s");
			return;
		}

var totalChecked = 0;


for(var iLoop=0; iLoop < aElsInput.length; iLoop++)
{
	
	//alert(aElsInput[iLoop].className);
	
	if(aElsInput[iLoop].className=="group_a_option_1 options block selected")
	{
		totalChecked=1;
	}
}

		for(var iLoop=0; iLoop < aEls.length; iLoop++)
		{



			if(aEls[iLoop].name!="input_emergency_a_otherType" && aEls[iLoop].type=="checkbox" && aEls[iLoop].type!="image" && aEls[iLoop].type!="hidden")
			{


				if(aEls[iLoop].getAttribute("checked")!=null && aEls[iLoop].getAttribute("checked")!=false)
				{
					//alert("CHECKED");
				totalChecked=1;
				}


			}


		}


		if (totalChecked>0) {
			//alert("Total length must equal " + iLayoutLength);
			//return;
			var oControl = document.getElementById("chooseAndContinue");
			if (oControl)
			{
				oControl.disabled = false;  

			}

			
		} else {
			var oControl = document.getElementById("chooseAndContinue");
			if (oControl)
			{
				//alert("oControl.disabled=true");
				oControl.disabled = true; 

			}
				
			var classes = document.body.className.split(" ");
			

			//AE: This stops this message from coming up if Step 8 has "none" selected. Otherwise
			//show the message.
			if(classes[2]=="group_a_option_2")
			{
				//alert("Please choose at least 1 emergency ballast location,\n or select None");
			}
			
		} 


		
		

		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		for (var iNum=0; iNum < aEls.length; iNum++)
	{
		//alert("jsConfiguratorOptionsEval:aEls[iNum]="+aEls[iNum].type);
		//aEls[iNum].onchange = jsConfiguratorSubmit;
		//addEvent0(aEls[iNum], 'change', jsConfiguratorSubmit);
		
		// addEvent works for IE and FF, while onchange only works with FF
		if(aEls[iNum].type=="checkbox")
		addEvent0(aEls[iNum], 'click', jsConfiguratorSubmit);
	}
	
	//oCB.onchange = jsConfiguratorSubmit;
	
}




















// Single handler method
function addEvent0(el, evt, fn){
el['on'+evt] = fn;
}

//=========================
function jsConfiguratorSubmit(evt)
//=========================
{
	// cancel event-bubbling
		if (evt) { event = evt; }
	event.cancelBubble = true;

	//alert(this.form.nodeName);		//parentNode.innerHTML);
	this.form.submit();
}

//=========================
function jsConfiguratorEditButtonsInit()
//=========================
{
//alert("function jsConfiguratorEditButtonsInit()");



	var oControl = document.getElementById("chooseAndContinue");
		if (oControl)
		{
			oControl.onmouseover = jsConfiguratorButtonOn;
			oControl.onmouseout = jsConfiguratorButtonOff;
		}
	
	var oControl = document.getElementById("buttonClear");
		if (oControl)
		{
			oControl.onmouseover = jsConfiguratorButtonOn;
			oControl.onmouseout = jsConfiguratorButtonOff;
		}

	var oControl = document.getElementById("verb_begin");
		if (oControl)
		{
			oControl.onclick = jsConfiguratorDesignBegin;
			oControl.onmouseover = jsConfiguratorButtonOn;
			oControl.onmouseout = jsConfiguratorButtonOff;
		}


	oControl = document.getElementById("designNameNew");
		if (oControl)
		{
			oControl.onfocus = jsConfiguratorNewnameFocus;
			oControl.onblur = jsConfiguratorNewnameBlur;
		}


	oControl = document.getElementById("verb_editDesign");
		if (oControl)
		{
			oControl.onclick = jsConfiguratorDesignEdit;
			oControl.onmouseover = jsConfiguratorButtonOn;
			oControl.onmouseout = jsConfiguratorButtonOff;
		}


	oControl = document.getElementById("verb_renameDesign");
		if (oControl)
		{
			oControl.onclick = jsConfiguratorDesignRename;
			oControl.onmouseover = jsConfiguratorButtonOn;
			oControl.onmouseout = jsConfiguratorButtonOff;
		}


	oControl = document.getElementById("verb_deleteDesign");
		if (oControl)
		{
			oControl.onclick = jsConfiguratorDesignDelete;
		}


	oControl = document.getElementById("verb_copyDesign");
		if (oControl)
		{
			oControl.onclick = jsConfiguratorDesignCopy;
		}
}


//=========================
function jsConfiguratorButtonOn(evt)
//=========================
{
	// cancel event-bubbling
		if (evt) { event = evt; }
	event.cancelBubble = true;
	
	var regRollover = /([^\.]+)(\.jpg)/;

	var sSrc = this.getAttribute("src");
	if (sSrc) this.setAttribute("src", sSrc.replace(regRollover, "$1_r$2"));
}


//=========================
function jsConfiguratorButtonOff(evt)
//=========================
{
	// cancel event-bubbling
		if (evt) { event = evt; }
	event.cancelBubble = true;
	
	var regRollover = /([^\.]+)_r(\.jpg)/;

	var sSrc = this.getAttribute("src");
	if (sSrc) this.setAttribute("src", sSrc.replace(regRollover, "$1$2"));
}


//=========================
function jsConfiguratorNewnameFocus(evt)
//=========================
{
	// cancel event-bubbling
		if (evt) { event = evt; }
	event.cancelBubble = true;

		if (this.value == "Enter project name") this.value = "";
}


//=========================
function jsConfiguratorNewnameBlur(evt)
//=========================
{
	// cancel event-bubbling
		if (evt) { event = evt; }
	event.cancelBubble = true;

		if (this.value == "") this.value = "Enter project name";
}


//=========================
function jsConfiguratorDesignBegin(evt)
//=========================
{
	// cancel event-bubbling
		if (evt) { event = evt; }
	event.cancelBubble = true;


	//-------------------------
	// get new design name
	//-------------------------

	var oNewName = document.getElementById("designNameNew");

		if (!oNewName)
		{
			alert("Can't find INPUT field oNewName");
			return false;
		}

	var sNewName = oNewName.value;
		
		if (!sNewName || sNewName == "Enter project name") {
			alert("Please enter the project name");
			oNewName.focus();
			return false;
		}

	var oNewSeries = document.getElementById("designSeriesNew");
	var sNewSeries = oNewSeries.options[oNewSeries.selectedIndex].value;
		if (!sNewSeries || sNewSeries == "0") {
			alert("Please select a series");
			oNewSeries.focus();
			return false;
		}
	
	//-------------------------
	// get old design selection
	//-------------------------
/* copy from existing spec removed by request of the client, 7/7/06:

	var oSelect = document.getElementById("designNameCopy");

		if (!oSelect)
		{
			alert("Can't find SELECT list designNameCopy");
			return false;
		}

	var sDesignRecno = oSelect.options[oSelect.selectedIndex].value;
	//-------------------------
	// create or copy
	//-------------------------
		// copy
		if (sDesignRecno && sDesignRecno != "" && sDesignRecno > 0)
		{
			document.location.href = "?verb_copyDesign=Copy"
									+ "&"
									+ "designRecnoCopy=" + sDesignRecno
									+ "&"
									+ "designNameCopy=" + sNewName;
			return false;
		}
		// create - just use form values
		else
		{
*/		

	// make sure they aren't using an existing spec name
	var oSelect = document.getElementById("designRecnoEdit");

		if (oSelect)
		{
			for (var iSpec = 0; iSpec < oSelect.options.length; iSpec++)
			{
				//alert(oSelect.options[iSpec].text);
				if (oSelect.options[iSpec].text == sNewName)
				{
					alert("You've already got a spec with that name.\n\nPlease enter a unique name for this spec.");
					oNewName.focus();
					return false;
				}
			}
		}
		
	// OK to create -- just use form values
	return true;
}


//=========================
function jsConfiguratorDesignEdit(evt)
//=========================
{
	// cancel event-bubbling
		if (evt) { event = evt; }
	event.cancelBubble = true;

	//-------------------------
	// get currently-selected design
	//-------------------------
	var oSelect = document.getElementById("designRecnoEdit");

		if (oSelect)
		{
			var sDesignRecno = oSelect.options[oSelect.selectedIndex].value;
			var sDesignName = oSelect.options[oSelect.selectedIndex].text;
		}
		else
		{
			alert("Can't find SELECT list designRecnoEdit");
			return false;
		}
		
		if (!sDesignRecno || sDesignRecno == "" || sDesignRecno == 0)
		{
			alert("Please select a spec to edit");
			return false;
		}
	

	return true;
}


//=========================
function jsConfiguratorDesignRename(evt)
//=========================
{
	// cancel event-bubbling
	if (evt) { event = evt; }
	event.cancelBubble = true;

	//-------------------------
	// get currently-selected design
	//-------------------------
	var oSelect = document.getElementById("designRecnoEdit");
	if (oSelect) {
		var sDesignRecno = oSelect.options[oSelect.selectedIndex].value;
		var sDesignName = oSelect.options[oSelect.selectedIndex].text;
	} else {
		alert("Can't find SELECT list designRecnoEdit");
		return false;
	}
	
	if (!sDesignRecno || sDesignRecno == "" || sDesignRecno == 0) {
		alert("Please select a spec to rename");
		return false;
	}
	
	//-------------------------
	// rename
	//-------------------------
	var sMsg = "Rename this spec?\n\n[" + sDesignName + " ]\n\nEnter the new name for your spec, then click OK.\n\nOr click CANCEL to keep the current name.";
	var bAsk = true;
	var sNewName = sDesignName;

	while (bAsk)
	{
		sNewName = window.prompt(sMsg, sNewName);
	
			if (!sNewName) {
				alert("The spec was not renamed.");
				return false;
			}
		
		// make sure the new name doesn't duplicate an existing name
		var bFoundMatch = false;
		
		for (var iOption = 0; iOption < oSelect.options.length; iOption++) {
			//alert("Comparing:\n" + oSelect.options[iOption].text + "\n" + sNewName);
			
			if (oSelect.options[iOption].text == sNewName)
			{
				alert("You've already got a spec named '" + sNewName + "'.\n\nPlease enter a unique spec name, or edit existing spec.");
				bFoundMatch = true;
				break;
			}
		}
		bAsk = bFoundMatch;
	}
		
	document.location.href = "?verb_renameDesign=Rename"
							+ "&"
							+ "designRecnoEdit=" + sDesignRecno
							+ "&"
							+ "designNameNew=" + sNewName;
		
	return false;
}


//=========================
function jsConfiguratorDesignDelete(evt)
//=========================
{
	// cancel event-bubbling
		if (evt) { event = evt; }
	event.cancelBubble = true;

	//-------------------------
	// get currently-selected design
	//-------------------------
	var oSelect = document.getElementById("designRecnoEdit");

		if (oSelect)
		{
			var sDesignRecno = oSelect.options[oSelect.selectedIndex].value;
			var sDesignName = oSelect.options[oSelect.selectedIndex].text;
		}
	
		if (!sDesignRecno || sDesignRecno == "" || sDesignRecno == 0)
		{
			alert("Please select a spec to delete");
			return false;
		}
	
	//-------------------------
	// delete
	//-------------------------
	sMsg = "Delete this spec?\n\n[" + sDesignName + " ]\n\nClick OK to delete, or CANCEL.";

		if (window.confirm(sMsg))
		{
			document.location.href = "?verb_deleteDesign=Delete"
									+ "&"
									+ "designRecnoEdit=" + sDesignRecno;
		}	
		else
		{
			alert("The spec was not deleted.");
		}
		
	return false;
}


//=========================
function jsConfiguratorDesignCopy(evt)
//=========================
{
	// cancel event-bubbling
		if (evt) { event = evt; }
	event.cancelBubble = true;

	//-------------------------
	// get currently-selected design
	//-------------------------
	var oSelect = document.getElementById("designRecnoCopy");

		if (oSelect)
		{
			var sDesignRecno = oSelect.options[oSelect.selectedIndex].value;
			var sDesignName = oSelect.options[oSelect.selectedIndex].text;
		}
		else
		{
			alert("Can't find SELECT list designRecnoCopy");
			return false;
		}
		
		if (!sDesignRecno || sDesignRecno == "" || sDesignRecno == 0)
		{
			alert("Please select a spec to copy");
			return false;
		}
	
	//-------------------------
	// copy
	//-------------------------
	sMsg = "Copy this spec?\n\n[" + sDesignName + " ]\n\nEnter the new name for your spec, then click OK.\n\nOr click CANCEL to do nothing.";

	sNewName = window.prompt(sMsg, sDesignName);
	
		if (sNewName)
		{
			document.location.href = "?verb_copyDesign=Copy"
									+ "&"
									+ "designRecnoCopy=" + sDesignRecno
									+ "&"
									+ "designNameCopy=" + sNewName;
		}
		else
		{
			alert("The spec was not copied.");
		}
		
	return false;
}


//=========================
function jsConfiguratorSaveAs(evt)
//=========================
{
	//-------------------------
	// get currently-selected design
	//-------------------------
	var oSelect = $("designRecnoEdit");
	if (oSelect) {
		var sDesignRecno = oSelect.options[oSelect.selectedIndex].value;
		var sDesignName  = oSelect.options[oSelect.selectedIndex].text;
	} else {
		alert("Can't find SELECT list designRecnoEdit");
		return false;
	}
	
	if (!sDesignRecno || sDesignRecno == "" || sDesignRecno == 0) {
		alert("Please select a spec to duplicate");
		return false;
	}
	
	//-------------------------
	// rename
	//-------------------------
	var sMsg = "Duplicate this project?\n\n[" + sDesignName + " ]\n\nEnter the new name, then click OK.\n\nOr click CANCEL.";
	var bAsk = true;
	var sNewName = sDesignName;

	while (bAsk)
	{
		sNewName = window.prompt(sMsg, sNewName);
	
		if (!sNewName) {
			alert("The spec was not renamed.");
			return false;
		}
		
		// make sure the new name doesn't duplicate an existing name
		var bFoundMatch = false;
		
		for (var iOption = 0; iOption < oSelect.options.length; iOption++) {
			//alert("Comparing:\n" + oSelect.options[iOption].text + "\n" + sNewName);
			
			if (oSelect.options[iOption].text == sNewName)
			{
				alert("You've already got a project named '" + sNewName + "'.\n\nPlease enter a different name.");
				bFoundMatch = true;
				break;
			}
		}
		bAsk = bFoundMatch;
	}
		
	send_xmlHttpRequest("recno="+sDesignRecno + "&newName="+encodeURIComponent(sNewName), "xmlConfiguratorProjectSaveAs.php", true, '');
		
	return false;
}


//=========================
function jsConfiguratorLayoutSelectInit()
//=========================
// Automate the selection of rail lengths, limiting the total selectable to the total layout length
/*
Logic:

	A) if layout length == input length
		no action

	B) if input length > layout length
		subtract length:
		- remove from rails working right to left
			skip just-selected rail if exists
		- minimum length = 0
		- if necessary, decrement just-selected rail

	C) if input length < layout length
		add length:

		1) if any zero rails
		
			a) if filling in zero rails can solve it (diff <= zeroRailCount * maxRailLength)
				- add identical length to zero rails until success or max
				- skip just-selected rail if exists
				- rail length = intval(diff / zero rail count)
				- dump remainder on the last rail, e.g.:  2 2 2 2 3

			b) increment rails, starting with zero rails, then 2 rails, then 3... until solved
				- skip just-selected rail if exists
	
		2) if no zero rails
			add length to rails, working right to left
				- skip just-selected rail if exists
*/
{
	//alert("function jsConfiguratorLayoutSelectInit()");
	
	//-------------------------
	// initialize, set global variables
	//-------------------------
	// this must be the layout page
	var sRegExp = new RegExp("(^| )step_layout( |$)");
		if (!sRegExp.test(document.body.className)) return; // alert("body class isn't step_layout");

	// get total layout length
	var oLength = document.getElementById("select_length_0");
		if (!oLength) return alert("Error: Can't find select_length_0");

	iLayoutLength = parseInt(oLength.options[oLength.selectedIndex].value);
		if (!iLayoutLength || iLayoutLength < 1) return; // alert("Error: not a valid layout length");
	
	// find the right section
	var oDetailsBlock = document.getElementById("choiceDetail");
		if (!oDetailsBlock) return;

	// grab ordered lists	
	var aLists = oDetailsBlock.getElementsByTagName("OL");
		if (!aLists || aLists.length == 0) return;
	
	// get the first list
	var oList = aLists[0];
	
	// make sure it's the right list
	sRegExp = new RegExp("(^| )customInput( |$)");
		if (!sRegExp.test(oList.className)) return;
	
	// get all descendant SELECT elements
	aRailLengthInputs = oList.getElementsByTagName("SELECT");
		if (!aRailLengthInputs || aRailLengthInputs.length == 0) return;

	// create an array of rail lengths & apply behavior
	for (var iRail=0; iRail < aRailLengthInputs.length; iRail++)
	{
		var oRailSelect = aRailLengthInputs[iRail];
		oRailSelect.onchange = jsRailLengthChange;
	}

/*
	alert("iLayoutLength = " + iLayoutLength + "\n\n" +
		  "number of rails = " + aRailLengthInputs.length + "\n\n" +
		  "iLastSelectedLayoutSegment = " + iLastSelectedLayoutSegment);
*/

	jsExamineRailLengths();
	
		// too much input -- subtract rail length
		if (iInputTotal > iLayoutLength)
		{
			jsSubtractRailLengths();
		}
		// not enough input length -- add rail length		
		else if (iInputTotal < iLayoutLength)
		{
			jsAddRailLengths();
		}
		// already good?
		else				// if (iInputTotal == iLayoutLength)
		{
			//alert("iInputTotal == iLayoutLength");
		}
}


//=========================
function jsFillZeroRails(iLayoutLength, iInputTotal, iZeroRailCount)
//=========================
{
/*
			a) if filling in zero rails can solve it (diff <= zeroRailCount * maxRailLength)
				- add identical length to zero rails until success or max
				- skip just-selected rail if exists
				- rail length = intval(diff / zero rail count)
				- dump remainder on the last rail, e.g.:  2 2 2 2 3

			b) increment rails, starting with zero rails, then 2 rails, then 3... until solved
				- skip just-selected rail if exists
*/
	//alert("function jsFillZeroRails(" + iLayoutLength + ", " + iInputTotal + ", " + iZeroRailCount + ")");
	
	var iBase = Math.ceil((iLayoutLength - iInputTotal) / iZeroRailCount);
	
	
/*

	jsExamineRailLengths();
	iLoopCount = 0;

	while (iInputTotal != iLayoutLength)
	{
		
			if (iInputTotal > iLayoutLength)
			{
				jsSubtractRailLengths();
			}
		
			if (iInputTotal < iLayoutLength)
			{
				jsAddRailLengths(iLayoutLength);
			}
			
			// guard against endless loop
			if (++iLoopCount > 10)
			{
				//alert("Too many loops in function jsFillZeroRails()");
				break;
			}

		iInputTotal = jsExamineRailLengths();
	}//while
	
	return;
*/
}


//=========================
function jsSubtractRailLengths()
//=========================
/*
subtract length:
- remove from rails working right to left
	skip just-selected rail if exists
- minimum length = 0
- if necessary, decrement just-selected rail
*/
{
	//alert("function jsSubtractRailLengths()");
	
/*
	alert("jsSubtractRailLengths():\n" + 
	"\n" + "iInputTotal = " + iInputTotal + 
	"\n" + "iLayoutLength = " + iLayoutLength);
*/	
	// work from right to left (last rail first)
	var ixRail = aRails.length;
	var iRemaining = 0;
	
	while (iInputTotal > iLayoutLength && ixRail > 0)
	{
		iRemaining = iInputTotal - iLayoutLength;

/*
		alert("jsSubtractRailLengths() LOOP:\n" + 
		"\n" + "ixRail = " + ixRail + 
		"\n" + "aRails[" + ixRail + "] = " + aRails[ixRail] + 
		"\n" + "iRemaining = " + iRemaining);
*/		
			// skip the last rail changed by the user
			if (ixRail == iLastSelectedLayoutSegment)
			{
				//alert("Bypassing last-selected rail #" + ixRail);
			}
			// if we need to subtract more than the last rail's length, zero it out & loop
			else if (aRails[ixRail] == 0)
			{
				//alert("Bypassing zero-length rail #" + ixRail);
			}
			else
			{
					if (iRemaining > aRails[ixRail])
					{
						//alert("Zeroing out rail #" + ixRail);
						// zero out the rail
						aRailLengthInputs[ixRail-1].value = 0;
					}
					// subtract from the last rail
					else
					{
						//alert("Subtracting " + iRemaining + " from rail #" + ixRail);
						aRailLengthInputs[ixRail-1].value = aRailLengthInputs[ixRail-1].value - iRemaining;
					}
				//alert("aRailLengthInputs[" + ixRail + "].value = " + aRailLengthInputs[ixRail].value);
			}
		
		// examine the previous rail next loop
		ixRail--;

		// add up the total input length again
		jsExamineRailLengths();
	}//while
}	
	
	
//=========================
function jsAddRailLengths()
//=========================
/*
		1) if any zero rails
		
			a) if filling in zero rails can solve it (diff <= zeroRailCount * maxRailLength)
				- add identical length to zero rails until success or max
				- skip just-selected rail if exists
				- rail length = intval(diff / zero rail count)
				- dump remainder on the last rail, e.g.:  2 2 2 2 3

			b) increment rails, starting with zero rails, then 2 rails, then 3... until solved
				- skip just-selected rail if exists
	
		2) if no zero rails
			add length to rails, working right to left
				- skip just-selected rail if exists
*/
/* Logic:
1) See if we can supply enough values by replacing zero-length rails with numbers.

	iTry = int(iRemainingLength / iNumberOfZeroLengthRails)

*/
{
				if (iZeroRailCount > 0)
				{
					jsFillZeroRails(iLayoutLength, iInputTotal, iZeroRailCount);
				}
}	
	
	

//=========================
function xxxxxxxxxxxxxx()
//=========================
{
/*
	var sSelectIndex = "23458";

	var iTotalLengthToAdd = iLayoutLength - iInputTotal;
	//var iLengthToAdd = floor(iInputTotal / iZeroRailCount);
	
	// determine amount to add to each zero rail
	var oRailSelect = aRailLengthInputs[0];
	var iHighOptionValue = oRailSelect.options[oRailSelect.options.length - 1].value;
	
	for (var iOption=0; iOption < oRailSelect.options.length; iOption++)
	{
		iOptionValue = oRailSelect.options[iOption].value;
		iGuess = iZeroRailCount * iOptionValue;
		
			// stop when the current option value works
			if (iTotalLengthToAdd - (iZeroRailCount * iOptionValue) <= iHighOptionValue) break;
	}

	alert("iOptionValue = " + iOptionValue + "\n" + "iHighOptionValue = " + iHighOptionValue);
	
	// get the index into the array of options
	var iIndex = sSelectIndex.indexOf(iOptionValue);
	
	// fill the zero rails
	var iLastLength = iLayoutLength - (iLengthToAdd * iZeroRailCount);

	for (var iRail=0; iRail < aRails.length; iRail++)
	{
			if (aRails[iRail] == 0)
			{
				aRailLengthInputs[iRail].value = iOptionValue;
				var iLastRail = iRail;
			}
	}
	aRailLengthInputs[iLastRail].value = iLastLength;
*/
}



//=========================
function jsExamineRailLengths()
//=========================
{
	// init global variables
	iInputTotal = 0;
	iZeroRailCount = 0;
	aRails = new Array();
	
	//-------------------------
	// loop through rails, getting lengths
	//-------------------------
	var sDebug = "jsExamineRailLengths():\n\nRail lengths:\n";
	
	for (var iRail=0; iRail < aRailLengthInputs.length; iRail++)
	{
		var oRailSelect = aRailLengthInputs[iRail];
		var iRailNo = oRailSelect.getAttribute("tabindex");
		
		// get input rail length
		var iRailLength = parseInt(oRailSelect.options[oRailSelect.selectedIndex].value);
			if (isNaN(iRailLength)) iRailLength = 0;
		
		// build array
		aRails[iRailNo] = iRailLength;
			
			// count zero-length rails
			if (iRailLength == 0) iZeroRailCount++;
			
		iInputTotal = iInputTotal + iRailLength;

		sDebug += "\n" + "aRails[" + iRailNo + "] = " + iRailLength;
	}

/*
	alert(sDebug + 
	"\n--------------------\n" + "iLayoutLength = " + iLayoutLength +
	"\n\n" + "iInputTotal = " + iInputTotal +
	 "\n\n" + "number of rails (aRailLengthInputs.length) = " + aRailLengthInputs.length + 
	  "\n\n" + "iZeroRailCount = " + iZeroRailCount);
*/
}



//=========================
function jsRailLengthChange(evt)
//=========================
{
	// cancel event-bubbling
		if (evt) { event = evt; }
	event.cancelBubble = true;

	//-------------------------
	// 
	//-------------------------
	iLastSelectedLayoutSegment = this.getAttribute("tabindex");
	//alert("iLastSelectedLayoutSegment = " + iLastSelectedLayoutSegment);

	jsExamineRailLengths();
}

//
//
//
//
// ===============================================================================================================






// key press listener
//=======================
function keyDown(e)
//=======================
{
	var evt=(e)?e:(window.event)?window.event:null;
	if(evt) {
		var key=(evt.charCode)?evt.charCode: ((evt.keyCode)?evt.keyCode:((evt.which)?evt.which:0));
		if(key=="13") submitFormAtEnter();
		else if (key=="37") jumpStepBackwards();
		else if (key=="39") jumpStepForward();

		else if (key=="27") close_infobox_window();
	}
}
document.onkeydown=keyDown;
if(!document.all) document.captureEvents(Event.KEYDOWN);

document.onscroll=scrollEvent;
//=======================
function scrollEvent(e)
//=======================
{
	var topX = document.body.scrollTop;

	if (topX == 0)
	{
		if (window.pageYOffset)
			topX = window.pageYOffset;
		else
			topX = (document.body.parentElement) ? document.body.parentElement.scrollTop : 0;
	}
	document.getElementById('floating_info').style.top = String(topX+30) + "px";
}

// CR 10-15-2009
// submitting at [ENTER]
//=======================
function submitFormAtEnter()
//=======================
{
	// is the submit button enabled? Only if so, we can submit at ENTER
	var oControl = document.getElementById("chooseAndContinue");
	if (oControl)
	{
		if (!oControl.disabled)
			document.getElementById("chooseAndContinue").click();
	}
}


//=======================
function jumpStepBackwards()
//=======================
{
	var thenStep = parseInt(currentStep) - 1;
	if (thenStep >= 0) location.href = 'configurator.php?recno='+recNo+'&stepNo='+thenStep;
}
//=======================
function jumpStepForward()
//=======================
{
	var thenStep = parseInt(currentStep) + 1;
	if (thenStep <= lastStep) location.href = 'configurator.php?recno='+recNo+'&stepNo='+thenStep;
}

//
//
//
//
// ===============================================================================================================
//
//
//


//=======================
function setCookie(name, value, days) {
//=======================
	if (days) {
		var date = new Date();
		date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
		var expires = "; expires="+date.toGMTString();
	} else {
		var expires = "";
	}
	document.cookie = name + "=" + value + expires + "; path=/";
}
//
//
//
//=======================
function readCookie(name) {
//=======================
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for (var i=0; i<ca.length; i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
	}
	return null;
}

//=======================
function unsetCookie(name) {
//=======================
	setCookie(name, "", -1);
}





// ===============================================================================================================





// -----------------------------------------------------------------------
//                          popup info window
var infobox_step_cookie_name = "infobox_open_stepNo";
//=======================
function init_infobox_window(stepNo) {
//=======================
	document.getElementById('floating_info').style.display = 'block';
	setCookie(infobox_step_cookie_name, stepNo, 2);
}
//=======================
function close_infobox_window() {
//=======================
	document.getElementById('floating_info').style.display = 'none';
	unsetCookie(infobox_step_cookie_name);
}
//=======================
function reload_infobox_atcookiematch(stepNo) {
//=======================
	var cookie_val = readCookie(infobox_step_cookie_name);
	if (cookie_val == null || cookie_val == 'undefined')
		return;
	if (stepNo == null || stepNo == 'undefined')
		return;
	if (cookie_val == stepNo)
		init_infobox_window(stepNo);
}


//
// ===============================================================================================================
//
//
//
//
//
// validating the checkbox associated with "View SpecSheet"
// and forwarding to the pdf generator
//=======================
function generateSpecSheet(series, recno, isChecked_long_specsheet)
//=======================
{
	var forward = "specPrint.php?series="+encodeURIComponent(series)+"&recno="+recno
		+(isChecked_long_specsheet ? "&isLongSpecsheet" : "");

	location.href = forward;
}


// ===============================================================================================================



var hasEnteredPersonalInfo = false;
//=======================
function preLoad_personalInfo(recno)
//=======================
{
	if (hasEnteredPersonalInfo) {
		if (!confirm("Fill OPTIONAL INFORMATION form with the saved data?\nYou will loose the current input!" )) {
			hasEnteredPersonalInfo = false;
			return;
		}
	}
	hasEnteredPersonalInfo = false;
	send_xmlHttpRequest("recno="+recno, "xmlConfiguratorPersInfoLoad.php", true, "preFill_personalInfo");
}
//=======================
function preFill_personalInfo()
//=======================
{
	if (xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200) {
		var error_id = interpret_query_string(xmlHttpRequest.responseText, "error_id");
		if (error_id != "0")
			return;

		$('designNameNew').value =  interpret_query_string(xmlHttpRequest.responseText, "project");
		$('fd_created_by').value =  interpret_query_string(xmlHttpRequest.responseText, "created_by");
		$('fd_company').value    =  interpret_query_string(xmlHttpRequest.responseText, "company");
		$('fd_location').value   =  interpret_query_string(xmlHttpRequest.responseText, "location");
		$('fd_type').value       =  interpret_query_string(xmlHttpRequest.responseText, "type");
		$('fd_notes').value      =  interpret_query_string(xmlHttpRequest.responseText, "notes");
	}
}







// ===============================================================================================================




//=======================
function show_specification_information()
//=======================
{
	$('specification_information').style.display = "block";
}








// ====================================================================================================================================================================
//             XMLHTTPREQUEST
// -----------------------------------------------------------------------------------------------------------------------------
var xmlHttpRequest = null;

function createRequest()
{
	try { xmlHttpRequest = new XMLHttpRequest();  } // This line tries to create a new request-object (by its type)
	catch (trymicrosoft) {
		try { xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP"); } // Here we try to create instance for IE 
		catch (othermicrosoft) {
			try { xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP"); 	} // Here we try to create instance for IE
			catch (failed) { xmlHttpRequest = null;  } // totally doomed
		}
	}
	return xmlHttpRequest != null;
}
// -----------------------------------------------------------------------------------------------------------------------------
//
//
//
// this function is only useful for synchronic communication 
// --- xmlHttpRequest ...  -----------------------------------------------------------------------------------------------------
function send_xmlHttpRequest(send_data, url, isAsync, func_call)
{
      if (createRequest())
      {

	    if (isAsync && func_call != '') { 
		xmlHttpRequest.onreadystatechange = function() {
			switch (func_call)
			{
				case "preFill_personalInfo":
					preFill_personalInfo();
					break;
			}
		}
	    }// func_call; } // new Function('fx', func_call);
	    xmlHttpRequest.open("POST", url, isAsync);
	    xmlHttpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	    xmlHttpRequest.send(send_data);

      }
      else alert('Please upgrade to a newer browser (use Firefox) in order to run this program');
}
// -----------------------------------------------------------------------------------------------------------------------------
//
//
//
// ---- this next function can crop values that a script outputs by a key
function interpret_query_string(query_string, key)
{
	var pos = query_string.indexOf(key);
	if (pos == -1)
		return false;

	if (key.charAt(key.length-1) != '=') // this is what makes it the var name -- if the = isn't already included, we append it
		key += '=';

	var aftermath = query_string.substring(pos+key.length);
	var pos_next_var = aftermath.indexOf("&"); // where does the next var begin
	if (pos_next_var == -1)
		return decodeURIComponent(aftermath.replace(/\+/g, " ")); // then, that's all we need

	return decodeURIComponent(aftermath.substring(0, pos_next_var).replace(/\+/g, " "));
}
// =======================
function $() {
// =======================
	if (arguments.length == 1) return get$(arguments[0]);
	var elements = [];
	$c(arguments).each(function(el){
		elements.push(get$(el));
	});
	return elements;

	function get$(el){
		if (typeof el == 'string') el = document.getElementById(el);
		return el;
	}
}
//             END
//             XMLHTTPREQUEST
// ====================================================================================================================================================================

