//Scripts.js
//Created: a long time ago
//NOTE: ATTENTION: QUIDADO:  Add more eval() calls to this file under penalty of death, unless absolutely neccesary.


//******************************
// All toplevel pages.

//try
//{
//	var sWidth = screen.width;
//	var sHeight = screen.height;
//	resolutionSampler = new Image(1,1);
//	resolutionSampler.src="/xtol/images/blankdot.gif?x="+sWidth+"?y="+sHeight;
//}
//catch (ignoreit){}

function resizeCheck()
{
	if (oldWidth < window.innerWidth || oldWidth > window.innerWidth || oldHeight > window.innerHeight || oldHeight < window.innerHeight )
	{
		if (document.f)
		{
			document.f.randnocache.value=(new Date()).getTime();
		}
		//document.f.submit();
	}
}

function doOnFocus()
{
}

function doOnBlur()
{
}

function doOnload()
{
	//overwrite this function in main component if necessary.
}

function doOnUnload()
{
	//overwrite this function in main component if necessary.
}

function doNothing()
{
	//Function designed for links that should do nothing.
	//alert("doNothing() called.");
}

var cellHeight = "100%";
function saveWindowDimensions()
{
	if(navigator.appName == 'Netscape')// && !window.oldWidth)
	{
		cellHeight = window.innerHeight-153; //144 = header height + footer height
		window.onresize = resizeCheck;
		window.oldWidth = window.innerWidth;
		window.oldHeight = window.innerHeight;
	}
}

function savePopupWindowDimensions()
{
	if(navigator.appName == 'Netscape')// && !window.oldWidth)
	{
		cellHeight = window.innerHeight-67; //67 = popup header height + popup footer height
		window.onresize = resizeCheck;
		window.oldWidth = window.innerWidth;
		window.oldHeight = window.innerHeight;
	}
}

//*********************//
//* Auto Calc Scripts *//
//*********************//

var ZEROVAL = "";

function adjustBedroomCounts()
{
	var currCount = parseFloat(document.xtolform['SINGLE_BEDROOM_MEDIUM'].value);
    if (isNaN(currCount) || currCount < 0)
	{
		currCount = 0;
	}

	var smallCount = parseFloat(document.xtolform['ROOM_BEDROOM_SMALL'].value);
    if (isNaN(smallCount) || smallCount < 0)
	{
		smallCount = 0;
	}
	var medCount = parseFloat(document.xtolform['ROOM_BEDROOM_MEDIUM'].value);
    if (isNaN(medCount) || medCount < 0)
	{
		medCount = 0;
	}
	var largeCount = parseFloat(document.xtolform['ROOM_BEDROOM_LARGE'].value);
    if (isNaN(largeCount) || largeCount < 0)
	{
		largeCount = 0;
	}
	var xlargeCount = parseFloat(document.xtolform['ROOM_BEDROOM_XLARGE'].value);
    if (isNaN(xlargeCount) || xlargeCount < 0)
	{
		xlargeCount = 0;
	}

	var bedTotal = smallCount + medCount + largeCount + xlargeCount;
	var diff = currCount - bedTotal;

	//alert ("curr:"+currCount+"  -  total:"+bedTotal+"  =  diff:"+diff);

	if (diff >= 0)  //need to add
	{
		//alert("setting ROOM_BEDROOM_MEDIUM to "+(medCount+diff));
		//alert(document.xtolform.ROOM_BEDROOM_MEDIUM.value);
		document.xtolform.ROOM_BEDROOM_MEDIUM.value = ""+(medCount+diff);
		//alert(document.xtolform.ROOM_BEDROOM_MEDIUM.value);
	}
	else //need to subtract
	{
		while (diff < 0)
		{
			if (medCount > 0)
			{
				medCount--;
				document.xtolform['ROOM_BEDROOM_MEDIUM'].value = medCount;
				diff++;
			}
			else if (smallCount > 0)
			{
				smallCount--;
				document.xtolform['ROOM_BEDROOM_SMALL'].value = smallCount;
				diff++;
			}
			else if (xlargeCount > 0)
			{
				xlargeCount--;
				document.xtolform['ROOM_BEDROOM_XLARGE'].value = xlargeCount;
				diff++;
			}
			else if (largeCount > 0)
			{
				largeCount--;
				document.xtolform['ROOM_BEDROOM_LARGE'].value = largeCount;
				diff++;
			}
			else diff = 0;
		}
	}

}

function singleBedroomUp()
{
	adjustone('SINGLE_BEDROOM_MEDIUM', 'up', false,1);
	adjustBedroomCounts();
}

function singleBedroomDown()
{
	adjustone('SINGLE_BEDROOM_MEDIUM', 'down', false,1);
	adjustBedroomCounts();
}

function singleBedroomOnChange(obj)
{
	adjustcheck('SINGLE_BEDROOM_MEDIUM',false);
	adjustBedroomCounts();
}

function singleBedroomOnKeyDown(obj)
{
	if(incrementDecrement(obj, false,1))
	{
		adjustBedroomCounts();
	}
}

function mouseOnOff(img,onoff)
{
	//alert("MouseOnOff image="+img);
	document[img].src = preloads[img+"_"+onoff].src;
}

function mouseOnOffSrc(img, src)
{
	document[img].src = src;
}

function toStringArray(ids)
{
	if (ids == null)
	{
		return null;
	}

	var list = new Array();

	var inx = ids.indexOf("~");
	var arrinx = 0;



	while (inx != -1 && ids.length > 0)
	{
		if (inx > 0)
		{
			list[arrinx++] = ids.substring(0,inx);
		}
		ids = ids.substring(inx+1);
		inx = ids.indexOf("~");
	}

	if (ids.length > 0)
	{
		list[arrinx++] = ids;
	}

//	for (i = 0 ; i < list.length; i++)
//	{
//		alert(list[i]);
//	}

	return list;

}

function setComboWidgetGroup(type, group, idlistStr, valuelistStr, openBy, isDefault)
{
	idlist = toStringArray(idlistStr);
	//alert("idlistStr = " + idlistStr);
	valuelist = toStringArray(valuelistStr);
	//alert("valuelistStr = " + valuelistStr);
	//alert(group+":openBy = " + openBy);
	eval('array_max = '+group+'_COMBO_MAX');

	var minOpen = idlist.length;
	if (minOpen == 0) minOpen = 1;
	//alert("idlist.length = " + idlist.length);
	if (minOpen%openBy > 0)
	{
		minOpen += (openBy - (minOpen%openBy));
	}
	//any nalert("setComboWidgetGroup: minOpen = " + minOpen);
	if(minOpen < array_max)
	{
		ensureMinimumOpen(group, minOpen, openBy);
	}
	else
	{
		ensureMinimumOpen(group, array_max, openBy);
	}


	var selectPrefix = "SELECT_XTOLCOMBO_";
	var valuePrefix = "XTOLCOMBO_";
	if (type == "count")
	{
		selectPrefix = "SELECT_XTOLCCOMBO_";
		valuePrefix = "XTOLCCOMBO_";
	}


	for (i=0; i<array_max; i++)
	{
		if (i < idlist.length)
		{
			if (typeof document.xtolform[selectPrefix+group+i] != 'undefined')
			{
				document.xtolform[selectPrefix+group+i].value =  idlist[i];
				document.xtolform[valuePrefix+group+i].value = valuelist[i];
			}
		}
		else if(typeof document.xtolform[selectPrefix+group+i] != 'undefined')
		{
			document.xtolform[selectPrefix+group+i].value = "";
			document.xtolform[valuePrefix+group+i].value = ZEROVAL;
		}
	}

}

function ensureMinimumOpen(group, min, openBy)
{
	eval('var curropen = '+group+'_COMBO_LENGTH');
	var count = min - curropen;
	if(count > 0)
	{
		//find if there are 2 columns or not
		for(var i =0; i < count; i+=openBy)
		{
			addDivRows(curropen+i, '', group, openBy, false);
		}
	}
}


//Used to find the first visible input in a node or subnodes
function findFirstVisFormElement(node)
{
	if(node.tagName &&
	   ((node.tagName.toUpperCase() == "INPUT" && node.type.toUpperCase() != "HIDDEN" && node.type.toUpperCase() != "CHECKBOX") ||
	    node.tagName.toUpperCase() == "SELECT"
	   )
	  )
	{
		return node;
	}

	for(var i=0; i < node.childNodes.length; i++)
	{
		var child = findFirstVisFormElement(node.childNodes[i]);
		if(child != null)
		{
			return child;
		}
	}
	return null;
}

//Used to get the element with the lowest tab index in this node and its subnodes
function findTabExtremeMin(node)
{
	var min = null;
	if(node.tabIndex && node.tabIndex >= 0)
	{
		min = node.tabIndex;
	}
	for(var i = 0; i < node.childNodes.length; i++)
	{
		var potentialMin = findTabExtremeMin(node.childNodes[i]);
		if(potentialMin != null && (min == null || potentialMin < min))
		{
			min = potentialMin;
		}
	}
	return min;
}

//Used to get the element with the highest tab index in this node and its subnodes
function findTabExtremeMax(node)
{
	var max = null;
	if(node.tabIndex && node.tabIndex >= 0)
	{
		max = node.tabIndex;
	}
	for(var i = 0; i < node.childNodes.length; i++)
	{
		var potentialMax = findTabExtremeMax(node.childNodes[i]);
		if(potentialMax != null && (max == null || potentialMax > max))
		{
			max = potentialMax;
		}
	}
	return max;
}

//Used by add div rows to copy the rows but change the names and ID appropriate to that new row.
function copyNodeExceptID(oldNode, linknum, group, count, max, tabInc, showAddedRowLabel)
{
	//Label only found on first line, we are adding after the first line so should discard label.
	if(oldNode.id && oldNode.id.search("label_") != -1 && !showAddedRowLabel){
		return null;
	}
	var newClone;

	//IE up to at least 6.x can't set the id attribute after the element has been create.
	//Also associating the events after it has been created is a problem.
	if(oldNode.outerHTML && oldNode.tagName)
	{
		var newStartTag = oldNode.outerHTML.substring(oldNode.outerHTML.search("<"),oldNode.outerHTML.search(">")+1);
		for(var i = 0; i >= (-count); i--)
		{
			//When more than one appear on a line remove any above the max
			if(linknum+i+count >= max &&
				oldNode.id &&
				oldNode.id.search(new RegExp(group+""+(linknum+i), "gi")) != -1)
			{
				var newTD = document.createElement('<td></td>');
				if(oldNode.id.search("ADDLINK_") == 0)
				{
					newImg = document.createElement('<img src="/xtol/images/blankdot.gif" height="1" width="32">');
					newTD.appendChild(newImg);
				}
				return newTD;
			}
			newStartTag = newStartTag.replace(new RegExp(group+""+(linknum+i), "g"), group+(linknum+i+count));
		}
		newClone = document.createElement(newStartTag+'</'+oldNode.tagName+'>');
	}
	else
	{
		newClone = oldNode.cloneNode(false);
		//Replace the uniqueids with the new appropriate ones.
		for(var i = 0; i >= (-count); i--)
		{
			for(var j = 0; newClone.attributes && j < newClone.attributes.length; j++)
			{
				//Adjust the id for the new row.
				if(newClone.attributes[j].nodeValue && typeof newClone.attributes[j].nodeValue == 'string' &&
				   (!newClone.outerHTML  || newClone.attributes[j].nodeName.toUpperCase() != 'ID'))
				{
					newClone.attributes[j].nodeValue = newClone.attributes[j].nodeValue.replace(new RegExp(group+""+(linknum+i), "gi"), group+(linknum+i+count));  //Increment the unique ids in any attributes
				}
			}
			//When more than one appear on a line remove any above the max
			if(linknum+i+count >= max &&
				newClone.id &&
				newClone.id.search(new RegExp(group+""+(linknum+i+count), "gi")) != -1)
			{
				var newTD = document.createElement('td');
				if(oldNode.id.search("ADDLINK_") == 0)
				{
					var spaceImg = document.createElement('img');
					spaceImg.src = '/xtol/images/blankdot.gif';
					spaceImg.width = 32;
					spaceImg.height = 1;
					newTD.appendChild(spaceImg);
				}
				return newTD;
			}
		}
	}
	//Adjust the tabIndexes
	if(newClone.tabIndex && newClone.tabIndex != '' && newClone.tabIndex != -1)
	{
		newClone.tabIndex += tabInc;
	}

	//Replace the count in the addDivRows call
	if(newClone.tagName &&
	   newClone.tagName.toUpperCase() == "A" &&
	   newClone.href)
	{
		//Update the "add" button to update the correct location
		newClone.href = newClone.href.replace("addDivRows("+(linknum), "addDivRows("+(linknum+count));
	}
	
	if(newClone.tagName 
	   && newClone.tagName.toUpperCase() == "IMG"
	   && newClone.src.indexOf("/xtol/images/addline_on.gif") != -1)
	{			
		newClone.src = newClone.src.replace("/xtol/images/addline_on.gif", "/xtol/images/addline_off.gif");
	}

	//add children nodes.
	for(var i=0; i < oldNode.childNodes.length; i++)
	{
		var newChild = copyNodeExceptID(oldNode.childNodes[i], linknum, group, count, max, tabInc, showAddedRowLabel);
		if(newChild != null)
		{
			newClone.appendChild(newChild);
		}
	}

	//Leave the new inputs empty
	if(newClone.tagName &&
	   newClone.tagName.toUpperCase() == "INPUT" &&
	   newClone.type.toUpperCase() == "TEXT")
	{
		newClone.value = '';
		newClone.className = 'emptyText';
	}
	if(newClone.tagName &&
	   newClone.tagName.toUpperCase() == "SELECT")
	{
		newClone.options[0].selected = true;
		newClone.className = 'emptyText';
	}
	if(newClone.tagName &&
	   newClone.tagName.toUpperCase() == "INPUT" &&
	   newClone.type.toUpperCase() == "CHECKBOX")
	{
		newClone.checked = false;
		newClone.defaultChecked = false;
		newClone.className = 'emptyText';
	}
	return newClone;
}

function addDivRows(linknum, prefix, group, count, focus, showAddedRowLabel)
{
//alert("addDivRows->linknum: " + linknum + " prefix: " + prefix + " group: " + group + " count: " + count + " focus: " + focus);
	var uniqueID;
	if(prefix != "")
	{
		uniqueID = prefix+"_"+group;
	}
	else
	{
		uniqueID = group;
	}
	//Get the old size and max size and set the new size.
	var array_max = eval(uniqueID+'_COMBO_MAX');
	eval(uniqueID+'_COMBO_LENGTH += count');
	var array_size = eval(uniqueID+'_COMBO_LENGTH');
	//alert("max: " + array_max + " size: " + array_size);
	//alert("td id: " + uniqueID+(linknum-count));
	var tdTag = document.getElementById(uniqueID+(linknum-count));
	//alert("tdTag: " + tdTag);
	//Find the parent table row.
	var trTag = tdTag.parentNode;

	//Find the parent tbody
	var tbl = trTag.parentNode;
	var trClone = tbl.insertRow(trTag.rowIndex+1);
	trClone.className = trTag.className;
	trClone.height = trTag.height;

    if (trTag.id)
	{
		var trId = trTag.id;
		//alert("trId="+trId);

		var inx = trId.indexOf("_PREINC_");
		if (inx != -1)
		{
			var trIdBASE = trId.substring(0,inx+8);
			//alert ("trIdBASE="+trIdBASE);
			var newInx = trId.substring(inx+8);
			//alert("newInx="+newInx);
			var inxInt = parseInt(newInx);
			inxInt++;
			//alert("inxInt="+inxInt);
			trClone.id = trIdBASE+inxInt;
			//alert("trClone.id="+trClone.id);
		}
	}


	//Get the range of tab indexes
	var minTab = findTabExtremeMin(trTag);
	var maxTab = findTabExtremeMax(trTag);
	for(var i = 0; i < trTag.childNodes.length; i++)
	{
		trClone.appendChild(copyNodeExceptID(trTag.childNodes[i], linknum, group, count, array_max, maxTab-minTab, showAddedRowLabel));
	}

	//Hide the "add" button on the previous row.
	document.getElementById("ADDLINK_"+uniqueID+linknum).style.display = "none";
	//Move the footer down to accommodate the space.
	setFooter();
	//Set the focus to the first input of the new row. But not when created by defaults
	if(focus)
	{
		findFirstVisFormElement(trClone).focus();
	}
}


function ensureMinimumOpen2(group, min)
{
	eval('var curropen = '+group+'_COMBO_LENGTH');
	var count = min - curropen;
	addDivRows2(group, count, null, false);
}


function addDivRows2(group, count, holder, focus)
{
	eval('array_max = '+group+'_COMBO_MAX');
	eval(group+'_COMBO_LENGTH += '+count);
	eval('array_size = '+group+'_COMBO_LENGTH');

	if (array_size > array_max)
	{
		eval(group+'_COMBO_LENGTH = '+array_max);
		array_size = array_max;
	}

	for (i =0; i<array_max; i++)
	{
		for (j =1; j<8; j++)
		{
			var id = ""+group+"_"+j+""+i;

			if (i < array_size || i == 0)
			{
				changeToShow(id);
				if ("XT_GARAGE_CARS" == group)
				{
					checkForLivingSpace(document.xtolform["XT_GARAGE_STYLE"+i], 'GARAGE_LIVING_ABOVE_'+i, true);
				}
			}
			else
			{
				changeToHide(id);
				if ("XT_GARAGE_CARS" == group)
				{
					changeToHide('GARAGE_LIVING_ABOVE_'+i);
				}
			}
		}
		id = "ADDLINK_"+group+""+i;
		changeToHide(id);
	}
	if(focus)
	{
		for (j =1; j<8; j++)
		{
			id = group+"_"+j+(array_size-1);
			if(document.getElementById(id) != null && findFirstVisFormElement(document.getElementById(id)) != null)
			{
				findFirstVisFormElement(document.getElementById(id)).focus();
				break;
			}
		}
	}


	id = "ADDLINK_"+group+""+(array_size-1);
	if (array_size != array_max)
	{
		changeToShow(id);
	}
}

//*******************************************//
//* XTOL Scripts -- Misc.                   *//
//*******************************************//


var MAX_NUM_OF_GARAGES = 9;

function checkForLivingSpace(garageStyleObj)
{
	var num = garageStyleObj.name.substr(garageStyleObj.name.length -1);
	// show the living space above garage only if the garage style is Attached / Built-In and its not a condo
	if(garageStyleObj.value == "1" && (typeof isCondo == 'undefined' || (typeof isCondo != 'undefined' && !isCondo)))
	{
		changeToShow("GARAGE_LIVING_ABOVE_" + num);
	}
	else
	{
		changeToHide("GARAGE_LIVING_ABOVE_" + num);
	}
}

function checkHiddenForAllGarages()
{
	var cloneCount = 0;
	while (typeof document.xtolform['XT_GARAGE_CARS'+ cloneCount] != 'undefined' && cloneCount < 9)
	{
		var garageCarObj = document.xtolform['XT_GARAGE_CARS'+ cloneCount];
		var garageStyleObj = document.xtolform['XT_GARAGE_STYLE'+ cloneCount];

		checkHiddenGarageFields(garageCarObj, false);
		checkForLivingSpace(garageStyleObj);

		cloneCount++;
	}
}

function checkHiddenGarageFields(garageNumCarsObj, doFocus)
{
	//alert('whats going on')
	var num = garageNumCarsObj.name.substr(garageNumCarsObj.name.length -1);
	if (garageNumCarsObj.value != "0")
	{
		changeToShow("GARAGE_DETAILS_" + num);
		if (doFocus)
		{
			setShowTabFocus("GARAGE_DETAILS_" + num);
		}
	}
	else
	{
		changeToHide("GARAGE_DETAILS_" + num);
	}
	//alert('about to call');
	checkHiddenGarageFieldsPageSpecific(garageNumCarsObj, num);
}

function checkHiddenGarageFieldsPageSpecific(garageNumCarsObj, num)
{
	// Override this in the page if needed
	//alert("in scripts");
}

function checkHiddenDeckFields(deckSqftObj, doFocus)
{
	var num = deckSqftObj.name.substr(deckSqftObj.name.length -1);
	if (checkForInt(deckSqftObj) && parseInt(deckSqftObj.value) > 0)
	{
		changeToShow("DECK_DETAILS_" + num);
		if (doFocus)
		{
			setShowTabFocus("DECK_DETAILS_" + num);
		}
	}
	else
	{
		changeToHide("DECK_DETAILS_" + num);
	}
}

function checkHiddenPorchFields(porchSqftObj, doFocus)
{
	var num = porchSqftObj.name.substr(porchSqftObj.name.length -1);
	if (checkForInt(porchSqftObj) && parseInt(porchSqftObj.value) > 0)
	{
		changeToShow("PORCH_DETAILS_" + num);
		if (doFocus)
		{
			setShowTabFocus("PORCH_DETAILS_" + num);
		}
	}
	else
	{
		changeToHide("PORCH_DETAILS_" + num);
	}
}

function checkHiddenMMAdditionFields(mmAdditionSqftObj, doFocus)
{
	var num = mmAdditionSqftObj.name.substr(mmAdditionSqftObj.name.length-1);
	if (checkForInt(mmAdditionSqftObj) && parseInt(mmAdditionSqftObj.value) > 0)
	{
		changeToShow("PORCH_DETAILS_" + num);
		if (doFocus)
		{
			setShowTabFocus("PORCH_DETAILS_" + num);
		}
	}
	else
	{
		changeToHide("PORCH_DETAILS_" + num);
	}
}

function checkHiddenAttOtherFields(attOtherSqftObj, doFocus)
{
	var num = attOtherSqftObj.name.substr(attOtherSqftObj.name.length -1);
	if (checkForInt(attOtherSqftObj) && parseInt(attOtherSqftObj.value) > 0)
	{
		changeToShow("ATT_OTHER_DETAILS_" + num);
		if (doFocus)
		{
			setShowTabFocus("ATT_OTHER_DETAILS_" + num);
		}
	}
	else
	{
		changeToHide("ATT_OTHER_DETAILS_" + num);
	}
}

function additionSqFtOnChangeMM(sqftObj, doFocus)
{
	//alert("HI sqftObj.name.substr(0, 1)=["+sqftObj.name.substr(0, 1)+"]");
	var prefix = sqftObj.name.substr(0, 1);
	if (checkForInt(sqftObj) && parseInt(sqftObj.value) > 0)
	{
		changeToShow(prefix + "_ADDITION_DETAILS");
		if (doFocus)
		{
			setShowTabFocus(prefix + "_ADDITION_DETAILS");
		}
	}
	else
	{
		changeToHide(prefix + "_ADDITION_DETAILS");
	}
}

function checkAdditionShowMoreDetailMM(obj, doFocus)
{
	//alert("HI checkAdditionShowMoreDetailMM obj.name.substr(0, 1)=["+obj.name.substr(0, 1)+"]");
	var prefix = obj.name.substr(0, 1);
//	if (0 == obj.name.indexOf("SELECT"))
//	{
//		prefix = obj.name.substr(6, 1);
//		alert("HI sqftObj.name.substr(6, 1)=["+obj.name.substr(6, 1)+"]");
//	}
	var yearObj = document.xtolform[prefix + "_XT_ADDITION_YEAR_BUILT"];
	var sqftObj = document.xtolform[prefix + "_XT_TOTAL_SF"];
//	var typeObj = document.xtolform[prefix + "_XT_RT"];
//	var roofType = document.xtolform["SELECT_" + prefix + "_XTOLCOMBO_XTOL_RO"];
//	alert("yearObj=["+yearObj+"]\n sqftObj=["+sqftObj+"]\n typeObj=["+typeObj+"]\n roofType=["+roofType+"]");
	var yearOk =	(obj.name != yearObj.name)
				?	(checkForInt(yearObj) && parseInt(yearObj.value) > 0)
				:	validateXTOLYearBuiltObj(true, yearObj);
	var sqftOk = checkForInt(sqftObj) && parseInt(sqftObj.value) > 0;
//	var typeOk = true;
//	var roofOk = true;
//	if (yearOk && sqftOk && typeOk && roofOk)
	var name = prefix + "_ADDITION_MORE_DETAIL_LINK";
	if (yearOk && sqftOk)
	{
		var name = prefix + "_ADDITION_MORE_DETAIL_LINK";
		changeToShow(name);
		if (doFocus)
		{
			setShowTabFocus(name);
		}
	}
	else
	{
		changeToHide(name);
	}
}

function addAttachedStructureRow(index, structType)
{
	var newIndex = index + 1;
	if (newIndex < 9)
	{
		// Hide the old add row
		changeToHide(structType + "_ADDLINK_" + index);

		// Show the new row
		changeToShow(structType + "_BLOCK_" + newIndex);
		setFirstVisFormElementInNodeFocus(document.getElementById(structType + "_BLOCK_" + newIndex));
		changeToShow(structType + "_ADDLINK_" + newIndex);


		if ((newIndex+1) == 9)
		{
			changeToHide(structType + "_ADDLINK_" + newIndex);
		}
	}
}

function addAdditionMMRow(prefix, nextPrefix, index)
{
	var newIndex = index + 1;
	var magicNum = 5;
	var addLinkSuffix = "_ADDITION_ADDLINK";
	var blockSuffix = "_ADDITION_BLOCK";
	if (newIndex < magicNum)
	{
		// Hide the old add row
		changeToHide(prefix + addLinkSuffix);

		// Show the new row
		changeToShow(nextPrefix + blockSuffix);
		setFirstVisFormElementInNodeFocus(document.getElementById(nextPrefix + blockSuffix));
		changeToShow(nextPrefix + addLinkSuffix);

		if ((newIndex+1) == magicNum)
		{
			changeToHide(nextPrefix + addLinkSuffix);
		}
	}
}

function setFirstVisFormElementInNodeFocus(node)
{
	var focusElement = findFirstVisFormElement(node);
	if (focusElement && focusElement.focus)
	{
		focusElement.focus();
		if (focusElement.select)
		{
			focusElement.select();
		}
	}
}

/*
*	For the Attached Structures Tab. This function shows or hides details associated with garages, decks, etc, until
*	the user changes the number of garages, or sq ft first. Then it shows or hides the details depending on the change.
*	This is also called from comPopulateOpener.jsp (which is included on the worksheet detail forms).
*/
function checkForShowDetails(obj,doTab)
{
	var val = obj.value;
	var num = obj.name.substr(obj.name.length -1);
	var divId = "DETAILS_" + obj.name;

	var show = false;

	if (obj.name.indexOf("XT_GARAGE_CARS") == 0)
	{
		checkForLivingSpace(document.xtolform["XT_GARAGE_STYLE" + num], 'GARAGE_LIVING_ABOVE_' + num, true);
	}

	if (val < 1 || isNaN(val))
	{
		changeToHide(divId);
	}
	else
	{
		changeToShow(divId);
		if (doTab !== null && doTab == true)
		{
			if (obj.type.indexOf("select") < 0)
			{
				setShowTabFocus(divId);
			}
		}
	}
}

/*
*	This is used when a hidden DIV is shown in
*	the checkForShowDetails() function.
*/
function setShowTabFocus(tabDivId)
{
	var childDiv = document.getElementById(tabDivId);

	if (childDiv != null)
	{
		var eligibleTabObj = getFirstEligibleTab(childDiv);
		if (typeof eligibleTabObj != "undefined" && eligibleTabObj != null)
		{
			eligibleTabObj.focus();
		}
	}
}

function getFirstEligibleTab(nodeObj)
{
	var eligibleNode = null;
	if (typeof nodeObj != "undefined" && nodeObj != null)
	{
		// Focus on the first eligible field (i.e. input (thats not hidden) or a select)
		if ((nodeObj.tagName == "INPUT" && nodeObj.type != "hidden") || nodeObj.tagName == "SELECT")
		{
			eligibleNode = nodeObj;
		}
		// If this node isn't eligible, recurse on all of this nodes children
		else
		{
			for (var i=0; i < nodeObj.childNodes.length; i++)
			{
				eligibleNode = getFirstEligibleTab(nodeObj.childNodes[i]);
				if (typeof eligibleNode != "undefined" && eligibleNode != null)
				{
					break;
				}
			}
		}
	}
	return eligibleNode;
}

//  Takes the current window.location and removes
//  everthing following the last slash then adds the
//  value of to
function relativeForward(to)
{
	var loc = window.location.pathname;
	window.location = getRelativeLocation(loc, to);
}

//  Takes the specified URL and removes
//  everthing following the last slash then adds the
//  value of to
function getRelativeLocation(URL, to)
{
	var loc = URL;
	var idx = loc.lastIndexOf("/") + 1;
	var newLoc = loc.substring(0, idx) + to;
	return newLoc;
}

//********************************************//
//* Focus Scripts :Tracking focus on fields *//
//*******************************************//

var interFocus = "";
var idFocus = "";
var groupFocus = "";
var valueFocus = "";

//used to keep track of combo fields
var comboName = new Array();
var comboNum = 0;

function addComboName(val)
{

	comboName[comboNum] = val;
	var tmp = comboName[comboNum];
	comboNum++;
}

var validatingAddressNow = false;
var preValidateNeedToCallGetRoomDefaults = false;
var preValidateNeedToCallGetFoundationDefaults = false;
var gettingDefaultsNow = false;
var gettingDefaultsFocusCount = 0;

var lastFocusedField = null;

function isDefaultsQuestion(id)
{
	return false;
}

function isFoundationDefaultsQuestion(id)
{
	return false;
}

function isAddressQuestion(id)
{
	return false;
}
// inter and group aren't used?!? Why are they passed in?
// if someone decides to start using them change boolWidgetOnChange
// to pass in values for this method
function showFocus(field,inter,group)
{
	//alert(field.name + '---' + inter + '---' + group+ '---' + field.type);
	//alert("gettingDefaultsNow: " + gettingDefaultsNow + " validatingAddressNow: " + validatingAddressNow);
	if (gettingDefaultsNow || validatingAddressNow)
	{
		lastFocusedField.focus();
	}
	else
	{
		//alert("needToCallValidateStreetAddress: " + needToCallValidateStreetAddress 
		//		+ " needToCallGetRoomDefaults: " + needToCallGetRoomDefaults 
		//		+ " needToCallGetFoundationDefaults: " + needToCallGetFoundationDefaults);
				
		if (!isAddressQuestion(field.name) && needToCallValidateStreetAddress)
		{
			needToCallValidateStreetAddress = false;
			lastFocusedField = field;
			validateStreetAddress();
		}
		
		if (!isDefaultsQuestion(field.name) && needToCallGetRoomDefaults)
		{
				needToCallGetRoomDefaults = false;
				lastFocusedField = field;
				getRoomDefaults();
		}

		if(!isFoundationDefaultsQuestion(field.name) && needToCallGetFoundationDefaults)
		{
				needToCallGetFoundationDefaults = false;
				lastFocusedField = field;
				getFoundationDefaults();
		}
	}
}

var doAddressVerification = false;
function checkStreetAddress()
{
	if (doAddressVerification)
	{
		// If the address changed set the status back to "Not Checked"
		document.xtolform.XT_STREET_STATUS.value = 0;
		updateAddressLook();
		if (checkRequiredFieldsForAddressVerification())
		{
			needToCallValidateStreetAddress = true;
		}	
		else
		{
			document.xtolform['XT_STRUCTURE_ID'].value = "";
			changeToHide("MAP_THIS_ADDRESS");
		}	
		
	}
}

function checkRequiredFieldsForAddressVerification()
{
	var streetFound = document.xtolform.XT_STREET.value != "";
	var cityFound = document.xtolform.XT_CITY.value != "";
	var stateFound = document.xtolform.XT_STATE.value != "";
	var zipFound = document.xtolform.XT_ZIP.value != "";
	var USAFound = document.xtolform.XT_COUNTRY.value == "USA";
	return streetFound && ((cityFound && stateFound) || zipFound) && USAFound;
}

function getAddressMap(useSimpleMap, sessionId)
{
	var street = document.xtolform['XT_STREET'].value;
	var zip = document.xtolform['XT_ZIP'].value;
	var country = document.xtolform['XT_COUNTRY'].value;
	var structureId = document.xtolform['XT_STRUCTURE_ID'].value;
	//alert("im here structureId: " + structureId + " needToCallValidateStreetAddress: " + needToCallValidateStreetAddress);
	
	if (street == "")
	{
		alert("The 'Street' field must be entered before using this feature");
		document.xtolform['XT_STRUCTURE_ID'].value = "";
		changeToHide("MAP_THIS_ADDRESS");
	}
	else if (zip == "")
	{
		alert("The 'ZIP Code' field must be entered before using this feature");
		document.xtolform['XT_STRUCTURE_ID'].value = "";
		changeToHide("MAP_THIS_ADDRESS");
	}
	else if ("USA" != country)
	{
		alert("Currently only addresses found in the USA are available");
		document.xtolform['XT_STRUCTURE_ID'].value = "";
		changeToHide("MAP_THIS_ADDRESS");
	}
	else if (structureId == "" || needToCallValidateStreetAddress)
	{
		if (needToCallValidateStreetAddress)
		{
			needToCallValidateStreetAddress = false;
			validateStreetAddress();
		}
		else
		{
			alert("The feature is only available after you have validated your address");
	        document.xtolform['XT_STRUCTURE_ID'].value = "";
	        changeToHide("MAP_THIS_ADDRESS");
		}        
	}
	else
	{		
		var width = 600;
		var height = 600;
		var url = document.location.href;
		var temp = url.substring((url.indexOf("//")+2));
		
		var domain = temp.substring(0, temp.indexOf("/"));
		var newUrl = "http://" + domain + "/apps/xtol/Map.jsp;jsessionid="+sessionId+"?structure_id="+structureId+"&street="+escape(street)+"&zipcode="+escape(zip)+"&simple="+useSimpleMap;
		
		var x = (window.screen.availWidth/2) - (width/2);
		var y = (window.screen.availHeight/2) - (height/2);
		var position = getWindowPosition(x, y);
		
		mqsizablewin =  window.open(newUrl, "mapquestmap", position + ",toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=yes,height=" + height + ",width=" + width);
		if (mqsizablewin.opener == null) mqsizablewin.opener = self;
		mqsizablewin.focus();
	}
}


function isAddressQuestion(id)
{
	if (id == 'XT_STREET') return true;
	else if (id == 'XT_CITY') return true;
	else if (id == 'XT_STATE') return true;
	else if (id == 'XT_ZIP') return true;
	else if (id == 'XT_COUNTRY') return true;
	return false;
}

function validateStreetAddress()
{	
	if (doAddressVerification)
	{
		var streetObj = document.xtolform.XT_STREET;
		var cityObj = document.xtolform.XT_CITY;
		var stateObj = document.xtolform.XT_STATE;
		var zipObj = document.xtolform.XT_ZIP;
		var isUSA = document.xtolform.XT_COUNTRY.value == "USA";
		if (streetObj.value != "" && (zipObj.value != "" || (cityObj.value != "" && stateObj.value)) && isUSA)
		{
			validatingAddressNow = true;
			preValidateNeedToCallGetRoomDefaults = needToCallGetRoomDefaults;
			preValidateNeedToCallGetFoundationDefaults = needToCallGetFoundationDefaults;
			var qString = "UPDATE_STREET_STATUS=true&address=" + escape(streetObj.value) 
					+ "&city=" + escape(cityObj.value) + "&state=" + escape(stateObj.value) + "&zip=" + escape(zipObj.value);
			ajaxPost("HndValuation", qString, updateStreetStatus);
			return true;
		}
	}
	return false;
}

function updateStreetStatus()
{	
	if (doAddressVerification)
	{	
		try
		{
			if(request.readyState == 4)
			{
				if(request.status == 200)
				{
					var xmldoc = request.responseXML;				
					var response = xmldoc.getElementsByTagName('response').item(0);	
					var status = response.getAttribute("status");
					var source = response.getAttribute("source");
					if (isNaN(parseInt(status)))
					{
						status = "0";
						source = "ERROR";
					}
					document.xtolform.XT_STREET_STATUS.value = status;
					document.xtolform.XT_STATUS_SOURCE.value = source;
					if (null == response.getAttribute("error") && status == "1")
					{		
						var standardAddr = makeAddressString(response.getAttribute("address"), response.getAttribute("city"), 
											response.getAttribute("state"), response.getAttribute("zip"));
						var streetObj = document.xtolform.XT_STREET;
						var cityObj = document.xtolform.XT_CITY;
						var stateObj = document.xtolform.XT_STATE;
						var zipObj = document.xtolform.XT_ZIP;
						
						var prevAddr = makeAddressString(streetObj.value, cityObj.value, 
											stateObj.value, zipObj.value);
						if (prevAddr.toUpperCase() != standardAddr.toUpperCase())
						{
							var standardLink = "<a href=\"javascript:setConfirmAnswer(0)\" style=\"font-size:13px;\">" + standardAddr + "</a>";
							var prevLink = "<a href=\"javascript:setConfirmAnswer(1)\" style=\"font-size:13px;\">" + prevAddr + "</a>";
							
							xtolConfirm("&nbsp;&nbsp;Address Verification", "Would you like to use the standardized address:<br>" + standardLink
								+ "<br>or<br>keep the address already specified:<br>" + prevLink, null, null, null, "350px", "100px",
								function(answer) 
								{
									if (answer == 0)
									{
										updateToStandardizedAddress(response);
									}
									else
									{
										// The status should be set to whatever STREET_NOT_ACCEPTED is.
										document.xtolform['XT_STREET_STATUS'].value = "10";
										doAfterAddressVerify(false);									
									}																								
								});	
						}
						else
						{	
							updateToStandardizedAddress(response);
						}
					}
					else
					{
						if (null != document.getElementById("MAP_THIS_ADDRESS") && document.getElementById("MAP_THIS_ADDRESS").style.display != "none")
						{
							alert("Unable to find address.  The 'Map this Address' link will no longer be available");
						}
						doAfterAddressVerify(false);
					}				
				}
				else
				{
					doAfterAddressVerify(false);
				}
			}		
		}
		catch (ex)
		{
			alert(ex);
			doAfterAddressVerify(false);
		}	
	}	
}

function updateToStandardizedAddress(response)
{
	var streetObj = document.xtolform.XT_STREET;
	var cityObj = document.xtolform.XT_CITY;
	var stateObj = document.xtolform.XT_STATE;
	var zipObj = document.xtolform.XT_ZIP;
	
	if ("true" != response.getAttribute("uniquezip"))
	{						
		streetObj.value = response.getAttribute("address");
	}
	cityObj.value = response.getAttribute("city");
	stateObj.value = response.getAttribute("state");
	zipObj.value = response.getAttribute("zip");
	if (null != response.getAttribute("structure_id"))
	{
		document.xtolform.XT_STRUCTURE_ID.value = response.getAttribute("structure_id");
	}									
	setExplicit(streetObj);							
	setExplicit(cityObj);
	setExplicit(stateObj);
	setExplicit(zipObj);
	doAfterAddressVerify(true);
	
}

function makeAddressString(street, city, state, zip)
{
	var fullAddress = "";
	var showComma = false;
	if (street != "")
	{
		fullAddress += street;
		showComma = true;
	}
	if (city != "")
	{
		if (showComma)
		{
			fullAddress += ", ";
		}
		fullAddress += city;
		showComma = true;
	}
	if (state != "")
	{
		if (showComma)
		{
			fullAddress += ", ";
		}
		fullAddress += state;
		showComma = true;
	}
	if (zip != "")
	{
		if (showComma)
		{
			fullAddress += " ";
		}
		fullAddress += zip;
	}
	return fullAddress;
}


function doAfterAddressVerify(addressFoundAndUsingIt)
{
	if (doAddressVerification)
	{
		if (addressFoundAndUsingIt)
		{
			changeToShow("MAP_THIS_ADDRESS");
		}
		else
		{		
			changeToHide("MAP_THIS_ADDRESS");
			document.xtolform['XT_STRUCTURE_ID'].value = "";						
		}				
	
		updateAddressLook();
		validatingAddressNow = false;	
		needToCallGetRoomDefaults = preValidateNeedToCallGetRoomDefaults;
		needToCallGetFoundationDefaults = preValidateNeedToCallGetFoundationDefaults;
		doAfterAddressVerifyPageSpecific();
	}
}

function openAddressStandardizationHelp()
{
	OpenHelp('AddressStandardization01');
}


function updateAddressLook()
{
	try
	{
		//alert("in update");
		var statusObj = document.xtolform.XT_STREET_STATUS;
		//alert("in update: " + statusObj);
		//alert("in update value: " + statusObj.value);
		if (typeof statusObj != 'undefined')
		{			
			var statusImg = document.getElementById("STATUS_IMG");
			if (null != statusImg)
			{
				if (statusObj.value == 0)
				{
					statusImg.src = "/xtol/images/av_stndrd_blank.gif";
					statusImg.alt = statusImg.title = "Address Not Standardized";
					statusImg.style.cursor = 'auto';
					removeEvent(statusImg, "click", openAddressStandardizationHelp, false);
				}
				else if (statusObj.value == 1)
				{
					statusImg.src = "/xtol/images/av_stndrd_drkblue.gif";
					statusImg.alt = statusImg.title = "Address Standardized";
					statusImg.style.cursor = 'help';
					addEvent(statusImg, "click", openAddressStandardizationHelp, false);
				}
				else
				{
					statusImg.src = "/xtol/images/av_nonstndrd_drkblue.gif";
					statusImg.alt = statusImg.title = "Address Not Standardized";
					statusImg.style.cursor = 'help';
					addEvent(statusImg, "click", openAddressStandardizationHelp, false);
				}
			}
			
			
			/*var streetObj = document.xtolform.XT_STREET;
			var cityObj = document.xtolform.XT_CITY;
			var stateObj = document.xtolform.XT_STATE;
			var zipObj = document.xtolform.XT_ZIP;*/
			
			
			
			
			/*
			//background color
			var fieldClassName = (structIdObj.value == "") ? "nonstandardizedaddress" : "standardizedaddress";
			streetObj.className = fieldClassName;
			cityObj.className = fieldClassName;
			stateObj.className = fieldClassName;
			zipObj.className = fieldClassName;*/
			
			/*
			//border
			if (structIdObj.value == "")
			{
				streetObj.style.borderWidth = "2px 1px 1px 2px";
				streetObj.style.borderStyle = "window-inset";
				streetObj.style.borderColor = "#ff5555";
				
				cityObj.style.borderWidth = "2px 1px 1px 2px";
				cityObj.style.borderStyle = "window-inset";
				cityObj.style.borderColor = "#ff5555";
				
				stateObj.style.borderWidth = "2px 1px 1px 2px";
				stateObj.style.borderStyle = "window-inset";
				stateObj.style.borderColor = "#ff5555";
				
				zipObj.style.borderWidth = "2px 1px 1px 2px";
				zipObj.style.borderStyle = "window-inset";
				zipObj.style.borderColor = "#ff5555";
			}
			else
			{
				streetObj.style.borderWidth = "2px 1px 1px 2px";
				streetObj.style.borderStyle = "window-inset";
				streetObj.style.borderColor = "#55ff55";
				
				cityObj.style.borderWidth = "2px 1px 1px 2px";
				cityObj.style.borderStyle = "window-inset";
				cityObj.style.borderColor = "#55ff55";
				
				stateObj.style.borderWidth = "2px 1px 1px 2px";
				stateObj.style.borderStyle = "window-inset";
				stateObj.style.borderColor = "#55ff55";
				
				zipObj.style.borderWidth = "2px 1px 1px 2px";
				zipObj.style.borderStyle = "window-inset";
				zipObj.style.borderColor = "#55ff55";
			}
			*/
			
		}
	}
	catch(ex){/*alert('error');*/}
}

function trackFocus(field,inter,group)
{
	if(field.name.substr(0,9) == 'XTOLCOMBO' && document.xtolform['SELECT_'+field.name].type != 'hidden')
	{
		idFocus = 'SELECT_'+field.name;
		valueFocus = document.xtolform[idFocus].value;
	}
	else if(field.name.substr(0,10) == 'XTOLCCOMBO' && document.xtolform['SELECT_'+field.name] != 'hidden')
	{
		idFocus = 'SELECT_'+field.name;
		valueFocus = document.xtolform[idFocus].value;
	}
	else if(field.name.substr(0,13) == 'SEL_XTOLCOMBO' && document.xtolform['SELECT_'+field.name.substr(4,(field.name).length)].type != 'hidden')
	{
		idFocus = 'SELECT_'+field.name.substr(4,(field.name).length);
		valueFocus = document.xtolform[idFocus].value;
	}
	else if(field.name.substr(0,4) == 'SEL_' && document.xtolform[field.name.substr(4,(field.name).length)].type != 'hidden')
	{
		idFocus = field.name.substr(4,(field.name).length);
		valueFocus = document.xtolform[idFocus].value;
	}
	else if(field.name.substr(0,3) == 'CC_' && document.xtolform[field.name.substr(3,(field.name).length)].type != 'hidden')
	{
		idFocus = field.name.substr(3,(field.name).length);
		valueFocus = document.xtolform[idFocus].value;
	}
	else
	{
		idFocus = field.name;
		valueFocus = field.value;
	}

	interFocus = inter;
	groupFocus = group;
}

function setPageFocus(track, pageVar, val, group)
{
	if(track != '')
	{
		if(typeof document.xtolform[track] == 'undefined')
		{
			if(track.substr(0,7) == 'SELECT_')
			{
				if(val != '' && typeof document.xtolform[val] != 'undefined')
				{
					//alert('setting default for value!-->'+val);
					setDefault(val);
					return;
				}
				else
				{
					for(i=0;i<comboName.length;i++)
					{
						tmp=comboName[i];
						if(val == document.xtolform[tmp].value)
						{
							setDefault(tmp);
							return;
						}
					}
					if(group.substr(group.length-4,group.length) == '_SUB')
					{
						if(typeof document.xtolform['SELECT_XTOLCOMBO_'+group.substr(0,group.length-4)+'0'] != 'undefined')
						{
							setDefault('SELECT_XTOLCOMBO_'+group.substr(0,group.length-4)+'0');
							return;
						}
					}
				}

			}
			else if(group.substr(group.length-4,group.length) == '_SUB')
			{
				if(typeof document.xtolform['SELECT_XTOLCOMBO_'+group.substr(0,group.length-4)+'0'] != 'undefined')
				{
					setDefault('SELECT_XTOLCOMBO_'+group.substr(0,group.length-4)+'0');
					return;
				}
			}
			else
			{
				for(i=0;i<comboName.length;i++)
				{

					tmp=comboName[i];
					if(track == document.xtolform[tmp].value)
					{
						setDefault(tmp);
						return;
					}
				}
			}
		}
		else
		{
			if(typeof eval('document.xtolform.'+track+'[0]') == 'object')
			{
				if(eval('document.xtolform.'+track+'[0].type') == 'radio')
				{
					//alert('setting[]');
					setDefault(track+'[0]');
					return;
				}
			}
			setDefault(track);
			return;
		}
	}
	setDefault(pageVar);
	return;
}

function setDefault(pageVar)
{
	if(pageVar != '' && typeof document.xtolform[pageVar] != 'undefined')
	{
		try
		{
			document.xtolform[pageVar].focus();
			if(document.xtolform[pageVar].type != 'radio' && document.xtolform[pageVar].type != 'select-one')
			{
				document.xtolform[pageVar].select();
			}
		}
		catch (ignoreit)
		{
			//alert(ignoreit.description);
		}

	}
}

//**********************************//
//* Event Scripts :COUNT STUFF *//
//**********************************//

var eventcount = 0;
function disallowChars(box,event)
{
	if (!event) {event = window.event;}
	//alert(event.keyCode);
	if(event.preventDefault)
	{
		if((isNaN(String.fromCharCode(event.charCode)) || String.fromCharCode(event.charCode) == " ") && event.keyCode == 0)
		{
			event.preventDefault();
		}
	}
	else
	{
		if(isNaN(String.fromCharCode(event.keyCode)) || String.fromCharCode(event.keyCode) == " ")
		{
			event.returnValue = false;
		}
	}
	if(parseInt(box.value) == 0)
	{
		box.value = '';
	}
}

function disallowCharsExceptOneDot(box, event)
{
	if (!event) {event = window.event;}
	//alert(window.event.keyCode);
	if(event.preventDefault)
	{
		if (String.fromCharCode(event.charCode) == '-')
		{
			if (box.value.indexOf('-') == -1)
			{
				box.value = "-" + box.value;
			}
			event.preventDefault();
		}
		else if((isNaN(String.fromCharCode(event.charCode)) ||
			String.fromCharCode(event.charCode) == " ") && event.keyCode == 0)
		{
			if(String.fromCharCode(event.charCode) != '.'
				|| box.value.indexOf('.') > -1) //Only allow one period.
			{
				event.preventDefault();
			}
		}
	}
	else
	{
		if (String.fromCharCode(event.keyCode) == '-')
		{
			if (box.value.indexOf('-') == -1)
			{
				box.value = "-" + box.value;
			}
			event.returnValue = false;
		}
		else if(isNaN(String.fromCharCode(event.keyCode)) ||
			String.fromCharCode(event.keyCode) == " ")
		{
			if(String.fromCharCode(event.keyCode) != '.'
				|| box.value.indexOf('.') > -1) //Only allow one period.
			{
				event.returnValue = false;
			}
		}
	}

	if(parseFloat(box.value) == 0)
	{
		box.value = '';
	}
}


function disallowCharsFloat(box, event)
{
	if (!event) {event = window.event;}
	//alert(window.event.keyCode);
	if(event.preventDefault)
	{
		if(((isNaN(String.fromCharCode(event.charCode)) && (String.fromCharCode(event.charCode) != '.'
				|| box.value.indexOf('.') > -1))  ||
			String.fromCharCode(event.charCode) == " ") && event.keyCode == 0)
		{
			event.preventDefault();
		}
	}
	else
	{
		if((isNaN(String.fromCharCode(event.keyCode)) && (String.fromCharCode(event.keyCode) != '.'
				|| box.value.indexOf('.') > -1))  ||
			String.fromCharCode(event.keyCode) == " ")
		{
			event.returnValue = false;
		}
	}
	if(parseFloat(box.value) == 0)
	{
		box.value = '';
	}
}


function allowPhoneNums(textField)
{
	//alert(window.event.keyCode);
	if(isNaN(String.fromCharCode(window.event.keyCode)) && window.event.keyCode != 40 && window.event.keyCode != 41 && window.event.keyCode != 45 && window.event.keyCode != 32)
	{
		event.returnValue = false;
	}
}

function checkEventCount()
{
	if(!window.event) return;

	if(window.event.repeat)
	{
		eventcount ++;
	}
	if (eventcount>1000)
	{
		eventcount =0;
	}
}

function incrementDecrement(box, hascheckbox, inc, limit, event, showZeros)
{
	if (!event) {event = window.event;}
	var increment = 1;
	var limitarg = 0;
	if (inc)
	{
		increment = inc;
	}
	if (limit)
	{
		limitarg = limit;
	}
	if(event.keyCode ==38 || event.keyCode ==40)
	{
		var currValue = parseInt(box.value,10);
		if(isNaN(currValue)) currValue = 0;
		checkEventCount();
		if(event.keyCode ==38)
		{
			adjustone(box.name, 'up', hascheckbox, increment, limitarg, showZeros);
			box.select();
			if(!event.repeat) eventcount = 0;
		}
		else if(event.keyCode ==40)
		{
			adjustone(box.name, 'down', hascheckbox, increment, limitarg, showZeros);
			box.select();
			if(!event.repeat) eventcount = 0;
		}
	}
	else
	{
		return false;
	}
	return true;
}

function percentEvent(group,box,hascheckbox,event)
{
	if (!event) {event = window.event;}

//	if(!isNaN(String.fromCharCode(window.event.keyCode)))
//	{
//		setExplicit(box);
//		setExplicit(document.xtolform['SELECT_' + box.name]);
//	}

	if(event.keyCode ==38 || event.keyCode ==40)
	{
		var currValue = parseInt(box.value,10);
		if(isNaN(currValue)) currValue = 0;
		checkEventCount();
		if(event.keyCode ==38 )
		{
			if (getType(document.xtolform['SELECT_'+box.name].value) == 'COUNT')
			{

				limit = 0;
				var maxlength = box.maxLength;
				//alert("maxlength: " + maxlength);
				if (maxlength < 1 || maxlength > 12)
				{
					maxlength = 12;
				}

				limit = Math.pow(10, maxlength) - 1;

				if (limit != 0)
				{
					if (currValue > limit -1)
					{
						currValue = limit;
					}
					else
					{
						currValue += 1;
					}
				}
				else
				{
					currValue += 1;
				}
				box.value = currValue;
			}
			else
			{
				if (typeof document.xtolform['SELECT_' + box.name] != "undefined"
						&& document.xtolform['SELECT_' + box.name].tagName == "SELECT"
						&& document.xtolform['SELECT_' + box.name].selectedIndex == 0)
				{
						document.xtolform['SELECT_' + box.name].selectedIndex = 1;
				}
				if( currValue < 100)
				{
					box.value = currValue + 1;
					box.select();
					if(!event.repeat) eventcount = 0;
					if (group != 'null')
					{
						calcpercent(group, box, box.name, hascheckbox);
					}
				}
			}
			setExplicit(box);
		}
		else if(event.keyCode ==40 && currValue > 0)
		{
			box.value = currValue - 1;
			box.select();
			if(!event.repeat) eventcount = 0;
			if (group != 'null')
			{
				calcpercent(group, box, box.name, hascheckbox);
			}

			if (typeof document.xtolform['SELECT_' + box.name] != "undefined" && box.value == 0
						&& document.xtolform['SELECT_' + box.name].tagName == "SELECT")
			{
					document.xtolform['SELECT_' + box.name].selectedIndex = 0;
					box.value = ZEROVAL;
			}
			setExplicit(box);
		}
	}
}

// Currently this is only being used for radio buttons but the functionality
// will work for all javascript arrays
function setArrayExplicit(objArray)
{
	if (typeof objArray != 'undefined' && null != objArray)
	{
		for (var i = 0; i < objArray.length; i++)
		{
			setExplicit(objArray[i]);
		}
	}
}

function setExplicit(obj)
{
	if(typeof obj != 'undefined')
	{
		var objName = obj.name;
		//alert("in setExplicit object.name=["+objName+"]");

		if(objName.indexOf("SELECT_") == 0)
		{
			objName = objName.substr(7,objName.length);
			addComboBoxValueToExplicitList(obj);
		}

		var changeColorOnly = false;
		if(objName.indexOf("XTOLCOMBO_") != -1)
		{
			idx = objName.indexOf("XTOLCOMBO_");
			changeColorOnly = true;
			objName = objName.substr(10+idx,objName.length);
		}
		else if(objName.indexOf("XTOLCCOMBO_") != -1)
		{
			idx = objName.indexOf("XTOLCCOMBO_");
			changeColorOnly = true;
			objName = objName.substr(11+idx,objName.length);
		}
		else if(objName.indexOf("CBOX_") != -1)
		{
			changeColorOnly = true;
			objName = objName.substr(5,objName.length);
		}
		else if(objName.indexOf("CC_") != -1)
		{
			changeColorOnly = true;
			objName = objName.substr(3,objName.length);
		}
		else if(objName.indexOf("SEL_") != -1)
		{
			changeColorOnly = true;
			objName = objName.substr(4,objName.length);
		}

		if(showExplicit)
		{
			if(changeColorOnly)
			{
				//don't add answerGroup ids to the list, just real individual question ids.  So only change the color.
				obj.className = "defaultedText";
			}
			else if(addToExplicitList(getFullIdFromName(objName)))
			{
				obj.className = "defaultedText";
			}			
		}
		else if(!changeColorOnly) //not doing the color thing for this type of widget
		{
			addToExplicitList(getFullIdFromName(objName));
		}

	}
}

function isShowExplicit()
{
	return (typeof showExplicit != 'undefined' && showExplicit == true);
}

//If it ends up in the localExplicitList then it shouldn't have been in the one set in the page.
//Therefore we should be ok removing anything found in the slot being taken by the new change.
var localExplicitList = new Array();

function addComboBoxValueToExplicitList(comboBox)
{
	var objName = comboBox.name;
	//alert("1 :comboBox = " + comboBox.name + " fullName = " + objName);

	oldId = localExplicitList[objName];
	if (oldId != null)
	{
		//alert("removeFromExplicitList:"+oldId);
		removeFromExplicitList(oldId);
	}

	objVal = getFullIdFromHiddenFields(comboBox.name);
	//alert("2 : comboBox = " + comboBox.name + " getFullIdFromHiddenFields = " + objVal);

	if (!isExplicit(objVal))
	{
		//alert("adding to explicitlist:"+objVal);
		localExplicitList[objName] = objVal;
		addToExplicitList(objVal);
	}
}

// NOTE: This method is overridden in rooms
// in order to tack on the sourceId (or roomId) when put in explicit list
// it probably doesn't need to be if the room stuff could be made consistant FIXIT -nfd
function getFullIdFromName(objName)
{
	return getFullIdFromHiddenFields(objName);
}

function getActualId(objName)
{
	//alert('getFullIdFromHiddenFields('+objName+')');
	if(objName.indexOf("SELECT_") == 0)
	{
		objName = objName.substring(7);
	}

	var fullId = null;
	var actualId = objName;//.substring(2); //The old way they pulled off the prefix.  Shouldn't need it but... Should always have a SELECT_

	var ridObj = document.xtolform["RID_" + objName];  //sourceId hidden field
	var selectObj = document.xtolform["SELECT_" + objName];  //actualId hidden field

	if (typeof selectObj != "undefined" && selectObj != null)
	{
		actualId = selectObj.value;
		//alert('getFullIdFromName().actualId2:'+actualId);
	} //else alert('getFullIdFromName().actualId1:'+actualId);
	return actualId;
}

function getSourceId(obj)
{
	var objName = obj.name;
	if(objName.indexOf("SELECT_") == 0)
	{
		objName = objName.substring(7);
	}

	var ridObj = document.xtolform["RID_" + objName];

	var sourceId = null;
	if (typeof ridObj != 'undefined' && ridObj != null && ridObj.value != "")
	{
		sourceId = ridObj.value;
	}

	return sourceId;
}

function getPrefix(obj)
{
	return obj.name.substr(0, obj.name.indexOf('_'));
}

// obj param is optional for all fields except radio buttons
// because radio buttons all have the same name you can't get the
// specific obj calling this function from the name
function getFullIdFromHiddenFields(objName, obj)
{
	// Radio buttons need to be handled in a special way because each radio
	// button in a radio group has to have the same name.
	if (typeof obj == 'undefined' || obj == null)
	{
		obj = document.xtolform[objName];
	}

	//alert('getFullIdFromHiddenFields('+objName+')');
	if(objName.indexOf("SELECT_") == 0)
	{
		objName = objName.substring(7);
	}

	var fullId = null;
	var actualId = objName;//.substring(2); //The old way they pulled off the prefix.  Shouldn't need it but... Should always have a SELECT_
	var ridObj = document.xtolform["RID_" + objName];  //sourceId hidden field
	var selectObj = document.xtolform["SELECT_" + objName];  //actualId hidden field

	if (typeof selectObj != "undefined" && selectObj != null)
	{
		actualId = selectObj.value;
		//alert('getFullIdFromName().actualId2:'+actualId);
	} //else alert('getFullIdFromName().actualId1:'+actualId);

	if (typeof ridObj != "undefined" && ridObj != null)
	{
		rid = ridObj.value;
		//alert('getFullIdFromName().rid:'+rid);
		if (rid != null && rid.length > 0)
		{
			fullId = rid + ":" + actualId;
		}
		else fullId = actualId;
	}
	else
	{
		fullId = actualId;

	}
	//alert('getFullIdFromName().fullId:'+fullId);
	return fullId;
}


function removeFromExplicitList(id)
{
	if(document.xtolform.EXPLIST == 'undefined' ||
		document.xtolform.EXPLIST == null)
	{
		return false;
	}

	var inx = document.xtolform.EXPLIST.value.indexOf('~'+id+'~');
	if(inx != -1)
	{
		var list = document.xtolform.EXPLIST.value;

		document.xtolform.EXPLIST.value = list.substring(0,inx) + list.substring(inx+id.length+1);
		//alert('removed:'+id+'  list:'+document.xtolform.EXPLIST.value);
	}
	return false;
}

function onSoConfigurationChange(obj)
{
	setExplicit(obj);
	var prefix = obj.name.substring(0, 2);
	if (obj.options[obj.selectedIndex].value == "1")
	{
		changeToShowTR(prefix+"agsoconstuctiontype");
	}
	else
	{
		changeToHide(prefix+"agsoconstuctiontype");
	}
}


function addToExplicitList(id)
{
	if(document.xtolform.EXPLIST == 'undefined' ||	document.xtolform.EXPLIST == null)
	{
		return false;
	}

	if(!isExplicit(id))
	{
		document.xtolform.EXPLIST.value += "~"+id+"~";

		//alert('EXPLIST.added:'+id);
		//alert(document.xtolform.EXPLIST.value);
	}

	return showExplicit;
}

function isExplicit(id)
{
//alert("in isExplicit id: " + id);
	if(document.xtolform.EXPLIST == 'undefined' || document.xtolform.EXPLIST == null)
	{
		return false;
	}
	var explist = document.xtolform.EXPLIST.value;
	//alert ("explist: " + explist);
	if ("~" != explist.substring(explist.length-1))
	{
		explist += "~";
		document.xtolform.EXPLIST.value = explist;
	}
	return (explist.indexOf('~'+id+'~') != -1);
}

function mergeExpLists(expList1)
{
	if(document.xtolform.EXPLIST == 'undefined' || document.xtolform.EXPLIST == null)
	{
		return expList1;
	}
	idlist = toStringArray(expList1);
	for(i=0; i<idlist.length; i++)
	{
		addToExplicitList(idlist[i]);
	}
	return document.xtolform.EXPLIST.value;
}



function unDefaultKitchens()
{
	if(addToExplicitList('ROOM_KITCHEN_MEDIUM'))
	{
		document.xtolform['ROOM_KITCHEN_SMALL'].className = "defaultedText";
		addToExplicitList('ROOM_KITCHEN_SMALL')
		document.xtolform['ROOM_KITCHEN_MEDIUM'].className = "defaultedText";
		document.xtolform['ROOM_KITCHEN_LARGE'].className = "defaultedText";
		addToExplicitList('ROOM_KITCHEN_LARGE')
		document.xtolform['ROOM_KITCHEN_XLARGE'].className = "defaultedText";
		addToExplicitList('ROOM_KITCHEN_XLARGE')
		//document.xtolform['ROOM_KITCHEN_QUALITY'].className = "defaultedText";
	}
}

function unDefaultBaths()
{
	if(addToExplicitList('ROOM_BATHROOM_HALF'))
	{
		document.xtolform['ROOM_BATHROOM_HALF'].className = "defaultedText";
		document.xtolform['ROOM_BATHROOM_3Q'].className = "defaultedText";
		addToExplicitList('ROOM_BATHROOM_3Q')
		document.xtolform['ROOM_BATHROOM_FULL'].className = "defaultedText";
		addToExplicitList('ROOM_BATHROOM_FULL')
		document.xtolform['ROOM_BATHROOM_15'].className = "defaultedText";
		addToExplicitList('ROOM_BATHROOM_15')
		//document.xtolform['ROOM_BATHROOM_QUALITY'].className = "defaultedText";
	}
}

function unDefaultBedrooms()
{
	if(addToExplicitList('ROOM_BEDROOM_SMALL'))
	{
		document.xtolform['ROOM_BEDROOM_SMALL'].className = "defaultedText";
		document.xtolform['ROOM_BEDROOM_MEDIUM'].className = "defaultedText";
		addToExplicitList('ROOM_BEDROOM_MEDIUM')
		document.xtolform['ROOM_BEDROOM_LARGE'].className = "defaultedText";
		addToExplicitList('ROOM_BEDROOM_LARGE')
		document.xtolform['ROOM_BEDROOM_XLARGE'].className = "defaultedText";
		addToExplicitList('ROOM_BEDROOM_XLARGE')
		//document.xtolform['ROOM_BEDROOM_QUALITY'].className = "defaultedText";

		if(document.xtolform['SINGLE_BEDROOM_MEDIUM'] != 'undefined' && document.xtolform['SINGLE_BEDROOM_MEDIUM'] != null)
			document.xtolform['SINGLE_BEDROOM_MEDIUM'].className = "defaultedText";
	}
}

function unDefaultDeck(num)
{
	setExplicit(document.xtolform['XT_DECK_SQFT' + num]);
	setExplicit(document.xtolform['XT_DECK_COVERED_PERCENT' + num]);
	setExplicit(document.xtolform['XT_DECK_ENCLOSED_PERCENT' + num]);
	setExplicit(document.xtolform['XT_DECK_STYLE' + num]);
}

function unDefaultPorch(num)
{
	setExplicit(document.xtolform['XT_PORCH_SQFT' + num]);
	setExplicit(document.xtolform['XT_PORCH_COVERED_PERCENT' + num]);
	setExplicit(document.xtolform['XT_PORCH_ENCLOSED_PERCENT' + num]);
	setExplicit(document.xtolform['XT_PORCH_STYLE' + num]);
}

function unDefaultGarage(num)
{
	setExplicit(document.xtolform['XT_GARAGE_CARS' + num]);
	setExplicit(document.xtolform['XT_GARAGE_STYLE' + num]);
	setExplicit(document.xtolform['XT_LIVING_ABOVE_GARAGE' + num]);
}

function unDefaultAttached(num)
{
	setExplicit(document.xtolform['XT_OTHERATTACHED_SQFT' + num]);
	setExplicit(document.xtolform['XT_OTHERATTACHED_TYPE' + num]);
}


//**********************************//
//* Auto Calc Scripts :COUNT STUFF *//
//**********************************//

function adjustone(textBoxName, updown, hasCheckBox, inc, limitarg, showZeros)
{
	setExplicit(document.xtolform[textBoxName]);
	setExplicit(document.xtolform['SELECT_' + textBoxName]);
	setExplicit(document.xtolform['CC_' + textBoxName]);

	if(textBoxName.indexOf("ROOM_KITCHEN") == 0)
		unDefaultKitchens();
	else if(textBoxName.indexOf("ROOM_BATHROOM") == 0)
		unDefaultBaths();
	else if(textBoxName.indexOf("SINGLE_BEDROOM") == 0 || textBoxName.indexOf("ROOM_BEDROOM") == 0)
		unDefaultBedrooms();

	var increment = updown.indexOf("p"); //the p in up.
	if (arguments.length >= 4)
	{
		increment = inc*increment;
	}

	var limit = 0;
	if (arguments.length == 5)
	{
		limit = limitarg;
	}

    var currValue = parseFloat(document.xtolform[textBoxName].value);
    if (isNaN(currValue)) currValue = 0;

	currValue = currValue + increment;

	if (limit < 1)
	{
		var maxlength = document.xtolform[textBoxName].maxLength;
		//alert(maxlength);
		if (maxlength < 1 || maxlength > 12)
		{
			maxlength = 12;
		}
		limit = Math.pow(10, maxlength) - 1;
	}

	if (limit != 0)
	{
		if (currValue > limit)
		{
			currValue = limit;
		}
	}
	
	if (currValue > 0)
	{
		document.xtolform[textBoxName].value = currValue
	}
	else
	{
		if (showZeros)
		{
			document.xtolform[textBoxName].value = 0;
		}
		else
		{
			document.xtolform[textBoxName].value = ZEROVAL;
		}
	}

	if (hasCheckBox)
	{
		adjustcheck(textBoxName,true);

		if(document.xtolform['CC_'+textBoxName].checked == true)
		{
	//alert('SELECT_' + textBoxName);
	//alert(document.xtolform['SELECT_' + textBoxName]);
	//alert(document.xtolform['SELECT_' + textBoxName].selectedIndex);
    		if (typeof document.xtolform['SELECT_' + textBoxName] != "undefined" && document.xtolform['SELECT_' + textBoxName].tagName == "SELECT" && document.xtolform['SELECT_' + textBoxName].selectedIndex == 0)
			{
					document.xtolform['SELECT_' + textBoxName].selectedIndex = 1;
			}

		}
		else
		{
			if (typeof document.xtolform['SELECT_' + textBoxName] != "undefined" && document.xtolform['SELECT_' + textBoxName].tagName == "SELECT")
			{
				document.xtolform['SELECT_' + textBoxName].selectedIndex = 0;
			}

		}
	}
//	else if (textBoxName == "ROOM_GARAGE_CARS" && currValue > 7)
//	{
//		if (!confirm("Are you sure you want more than 7 cars?"))
//		{
//			document.xtolform[textBoxName].value = 0;
//		}
//	}
	else if ((textBoxName == "XT_DECK_AVG_HEIGHT" || textBoxName == "XT_DECK_NUM_LEVELS") && currValue > 20)
	{
		document.xtolform[textBoxName].value = 20;
	}
	else if (
				(
						textBoxName.indexOf("ROOM_KITCHEN") == 0
					||	textBoxName.indexOf("ROOM_BATHROOM") == 0
					||	textBoxName.indexOf("SINGLE_BEDROOM") == 0
					||	textBoxName.indexOf("ROOM_BEDROOM") == 0
				)
				&& currValue > 99
			)
	{
//		alert("textBoxName = ["+textBoxName+"]");
		document.xtolform[textBoxName].value = 99;
	}
	else if ((textBoxName == "XT_DECK_LINEAL_FOOT") && currValue > 200)
	{
		document.xtolform[textBoxName].value = 200;
	}

	//	Return focus to the element
	if (document.xtolform[textBoxName].type != "hidden" && !document.xtolform[textBoxName].disabled)
	{
		if(isIE50() == false)
		{
			document.xtolform[textBoxName].focus();
		}
	}
	adjustonePageSpecific(textBoxName, updown, hasCheckBox, inc, limitarg);
}
// Override this if you want to use adjustone to do a page specific task (i.e. secondary occ)
function adjustonePageSpecific(textBoxName, updown, hasCheckBox, inc, limitarg)
{
}

function autocheckpopulate(textBox)
{
	autocheck(textBox.name.substring(3), '1');
}

function autocheck(textBoxName, increment)
{
	setExplicit(document.xtolform[textBoxName]);
	setExplicit(document.xtolform['SELECT_' + textBoxName]);
	setExplicit(document.xtolform['CC_' + textBoxName]);

	if(textBoxName.indexOf("ROOM_KITCHEN") == 0)
		unDefaultKitchens();
	else if(textBoxName.indexOf("ROOM_BATHROOM") == 0)
		unDefaultBaths();
	else if(textBoxName.indexOf("SINGLE_BEDROOM") == 0 || textBoxName.indexOf("ROOM_BEDROOM") == 0)
		unDefaultBedrooms();

//	alert('SELECT_' + textBoxName);

	if(window.document.xtolform['CC_'+textBoxName].checked)
	{
		window.document.xtolform[textBoxName].value = increment;
//alert('SELECT_' + textBoxName);
//alert(document.xtolform['SELECT_' + textBoxName]);
//alert(document.xtolform['SELECT_' + textBoxName].selectedIndex);
		if (typeof document.xtolform['SELECT_' + textBoxName] != "undefined" && document.xtolform['SELECT_' + textBoxName].tagName == "SELECT")
		{
				document.xtolform['SELECT_' + textBoxName].selectedIndex = 1;
		}

	}
	else
	{
		window.document.xtolform[textBoxName].value = ZEROVAL;

		if (typeof document.xtolform['SELECT_' + textBoxName] != "undefined" && document.xtolform['SELECT_' + textBoxName].tagName == "SELECT")
		{
			document.xtolform['SELECT_' + textBoxName].selectedIndex = 0;
    	}

	}
}

function adjustcheck(textBoxName, hasCheckBox, limit, showZeros)
{
	setExplicit(document.xtolform[textBoxName]);
	setExplicit(document.xtolform['SELECT_' + textBoxName]);
	if(hasCheckBox)
	{
		setExplicit(document.xtolform['CC_' + textBoxName]);
	}

	if(textBoxName.indexOf("ROOM_KITCHEN") == 0)
		unDefaultKitchens();
	else if(textBoxName.indexOf("ROOM_BATHROOM") == 0)
		unDefaultBaths();
	else if(textBoxName.indexOf("SINGLE_BEDROOM") == 0 || textBoxName.indexOf("ROOM_BEDROOM") == 0)
		unDefaultBedrooms();

	var currValue = parseInt(document.xtolform[textBoxName].value,10);

    if (isNaN(document.xtolform[textBoxName].value) || currValue < 0)
	{
		if (showZeros)
		{
			document.xtolform[textBoxName].value = 0;
		}
		else
		{
			document.xtolform[textBoxName].value = ZEROVAL;
		}
	}

	var currValue = parseFloat(document.xtolform[textBoxName].value);
    if (isNaN(currValue)) currValue = 0;

	if (limit < 1)
	{
		var maxlength = document.xtolform[textBoxName].maxLength;
		//alert(maxlength);
		if (maxlength < 1 || maxlength > 12)
		{
			maxlength = 12;
		}
		limit = Math.pow(10, maxlength) - 1;
	}

	if (limit != 0)
	{
		if (currValue > limit)
		{
			currValue = limit;
		}
	}

	if (currValue > 0)
	{
		document.xtolform[textBoxName].value = currValue
	}
	else if (currValue == 0)
	{
		if (showZeros)
		{
			document.xtolform[textBoxName].value = 0;
		}
		else
		{
			document.xtolform[textBoxName].value = ZEROVAL;
		}
	}



//	else if (textBoxName == "ROOM_GARAGE_CARS" && currValue > 7)
//	{
//		if (!confirm("Are you sure you want more than 7 cars?"))
//		{
//			document.xtolform[textBoxName].value = 0;
//		}
//	}
	else if ((textBoxName == "XT_DECK_AVG_HEIGHT" || textBoxName == "XT_DECK_NUM_LEVELS") && currValue > 20)
	{
		document.xtolform[textBoxName].value = 20;
	}
	else if (
				(
						textBoxName.indexOf("ROOM_KITCHEN") == 0
					||	textBoxName.indexOf("ROOM_BATHROOM") == 0
					||	textBoxName.indexOf("SINGLE_BEDROOM") == 0
					||	textBoxName.indexOf("ROOM_BEDROOM") == 0
				)
				&& currValue > 99
			)
	{
//		alert("textBoxName = ["+textBoxName+"]");
		document.xtolform[textBoxName].value = 99;
	}
	else if ((textBoxName == "XT_DECK_LINEAL_FOOT") && currValue > 200)
	{
		document.xtolform[textBoxName].value = 200;
	}

	if (hasCheckBox)
	{
		if(window.document.xtolform[textBoxName].value == ZEROVAL || (showZeros && window.document.xtolform[textBoxName].value == 0))
		{
			window.document.xtolform['CC_'+textBoxName].checked=false;
		}
		else
		{
			window.document.xtolform['CC_'+textBoxName].checked=true;
		}
	}
}

//**************************************//
//* Auto Calc Scripts :END COUNT STUFF *//
//**************************************//


function doSpinnerOnChange(group,textBoxObj ,doAdjustTotal)
{
	var currValue = parseInt(textBoxObj.value,10);
	if (isNaN(textBoxObj.value) || currValue < 0)
    {
		setTimeout("reallySetValue('" + textBoxObj.name + "', "+ZEROVAL+");", 1);
	}
	else
	{
		if (getType(document.xtolform['SELECT_'+textBoxObj.name].value) != 'COUNT')
		{
			if (currValue > 100)
			{
				setTimeout("reallySetValue('" + textBoxObj.name + "',"+100+");", 1);
			}
		}
	}
	if (doAdjustTotal)
	{
		adjustTotal(group,textBoxObj.name);
	}
}

function reallySetValue(id, value)
{
	var control = document.getElementById(id);
	control.value = value;
}

function adjust(group,textBoxName, updown, doAdjustTotal)
{
	adjustBox(group,textBoxName, updown, doAdjustTotal);
	if(window.document.xtolform['SEL_'+textBoxName].checked == true)
	{
		window.document.xtolform['SEL_'+textBoxName].checked = false;
	}
	arrangenum(group,true);
}

function adjustTotal(group,inputid)
{
	if(window.document.xtolform['check'+inputid].checked == true)
	{
		window.document.xtolform['check'+inputid].checked = false;
	}
	arrangeNum(group,true);
}

function depress(img,up_down)
{
//	if(document.images[img+up_down] != null)
//	{
//		var source = document.images[img+up_down].src;
//		alert(document.images[img+up_down].src);
//		if(img.equals("/xtol/images/spinup_off.jpg"))
//			document.images[img+up_down].src = "/xtol/images/spinup_on.jpg";
//		else if(img.equals("/xtol/images/spinup_on.jpg"))
//			document.images[img+up_down].src = "/xtol/images/spinup_off.jpg";
//		else if(img.equals("/xtol/images/spinup_on.jpg"
//	}
}

function release(img,up_down)
{
//	if(document.images[img+up_down] != null)
//	{
//		document.images[img+up_down].src = preloads["spin"+up_down+"_on"].src;
//	}
}


function validateSinglePercent(Objectid,inputid,select)
{
	doSpinnerOnChange(null,Objectid,false);
}

function calcpercent(group, Objectid, inputid, select, showAddedRowLabel)
{
	//alert("calc percent->group: " + group + " Objectid: " + Objectid + " inputid: " + inputid + " select: " + select);
	var ccObj = document.xtolform['CC_'+inputid];
	var selObj = document.xtolform['SEL_'+inputid];

	setExplicit(document.xtolform[inputid]);
	setExplicit(document.xtolform['SELECT_' + inputid]);
	setExplicit(selObj);
	setExplicit(ccObj);

	try
	{
		array_size = eval(group+'_LENGTH');
	}
	catch (exception)
	{
		return;
	}

	var selectTotal;
	doSpinnerOnChange(group,Objectid,false);
	if(window.document.xtolform['AC_'+Objectid.name].value != 1)
	{
		selectTotal = parseInt(nonselectadd(group),10) + parseInt(Objectid.value,10);
	}
	else selectTotal = nonselectadd(group);
	if(select)
	{
		if(!selObj.checked)
		{
			if (typeof selObj != 'undefined')
			{
				selObj.checked = true;
			}
			if (typeof ccObj != 'undefined')
			{
				ccObj.checked = true;
			}
		}
		if(document.xtolform[inputid].value == 0)
		{
			if (typeof selObj != 'undefined')
			{
				selObj.checked = false;
			}
			if (typeof ccObj != 'undefined')
			{
				ccObj.checked = false;
			}
		}
	}
	else
	{
		if(document.xtolform[inputid].value == 0)
		{
			document.xtolform['SELECT_'+inputid].value = '';
		}
	}
	if(document.xtolform[inputid].value == 0)
	{
		document.xtolform['AC_'+inputid].value = null;
	}
	else
	{
		document.xtolform['AC_'+inputid].value = 1;
	}
	arrangenum(group,select);
	if(getType(document.xtolform['SELECT_'+inputid].value) != 'COUNT')
	{
		displayAdditionalRowsIfNeeded(group, showAddedRowLabel);
	}

}

function displayAdditionalRowsIfNeeded(group, showAddedRowLabel)
{
	//alert("addUp: " + addUp(group) + " blank not Found: " + (!blankQuestionDisplayed(group)));
	if (addUp(group) < 100 && !blankQuestionDisplayed(group))
	{
		var linkNum = eval(group+'_LENGTH');
		var prefix = "";
		if (group.indexOf("_XTOL") != -1)
		{
			// Get the prefix this way so that if prefix ever changes to be to chars it will still work
			prefix = group.substring(0, group.indexOf("_XTOL"));
		}
		//alert("linkNum: " + linkNum + " prefix: " + prefix);
		// group means two different things (in this method the param group has _COMBO
		// appended to it and a prefix at the front, in addDivRows it appends "_COMBO"
		// and the prefix inside the method.
		//alert("newGroup1: " + group);
		var newGroup = group.replace("_COMBO", "");
		//alert("newGroup2: " + newGroup);
		if (prefix != "")
		{
			newGroup = newGroup.substring(newGroup.indexOf("_XTOL")+1);
		}

		var uniqueID;
		if(prefix != "")
		{
			uniqueID = prefix+"_"+newGroup;
		}
		else
		{
			uniqueID = newGroup;
		}
		if(window[uniqueID+'_COMBO_MAX'] != undefined)
		{
			//Get the old size and max size and set the new size.
			var array_max = eval(uniqueID+'_COMBO_MAX');
			var array_size = eval(uniqueID+'_COMBO_LENGTH');

			if (array_size < array_max)
			{
				//alert("newGroup3: " + newGroup + " numOfColumns: " + getNumberOfColumns(newGroup));
				addDivRows(linkNum, prefix, newGroup, getNumberOfColumns(newGroup), true, showAddedRowLabel);
			}
		}
	}
}

// If you are using a question that has more than one column when it is displayed
// make sure you override this function in the page where it is located
function getNumberOfColumns(group)
{
	return 1;
}

function blankQuestionDisplayed(group)
{
	var ar = ArrayList[group];
	var foundOne = false;
	var array_size = eval(group + '_LENGTH');
	for (i =0; i<array_size; i++)
	{
		if (typeof window.document.xtolform[ar[i]] != 'undefined' && window.document.xtolform[ar[i]] != null)
		{
			var tmp = parseInt(window.document.xtolform[ar[i]].value);
			//alert("id: " + ar[i] + " val: '" + window.document.xtolform[ar[i]].value + "' int: " + tmp);
			if (isNaN(tmp))
			{
				foundOne = true;
				break;
			}
		}
	}
	return foundOne;
}

function setTotalForGroup(group)
{
	var grpstr= "TOTAL_"+group;
	var node = 	document.getElementById(grpstr)
	if (node != null && node.firstChild != null)
	{
		node.firstChild.nodeValue = ""+addUp(group);
	}
}

//This looks almost identical to the add() method?!?!?  Could be combined maybe?
function addUp(group)
{
	//alert('group is '+group);
	var ar = ArrayList[group];
	sum=0;
	eval('array_size = '+group+'_LENGTH');
	for (i =0; i<array_size; i++)
	{
		if (typeof window.document.xtolform[ar[i]] != 'undefined' && typeof window.document.xtolform[ar[i]] != null)
		{
			var tmp = parseInt(window.document.xtolform[ar[i]].value);
			if (!isNaN(tmp))
			{
				sum += tmp;
			}
		}
	}
	return sum;
}

/*
*	Returns the total count for the option value specified in all the select fields for the specified group.
*/
function getGroupValCount(form, group, optVal)
{
	var retVal = 0;
	idx = 0;
	if (    window.document != null &&
			eval("window.document." + form) != null &&
			typeof eval("window.document." + form + ".SELECT_XTOLCCOMBO_" + group + idx) != "undefined"	)
	{
		while(typeof eval("window.document." + form + ".SELECT_XTOLCCOMBO_" + group + idx) != "undefined")
		{
			sel = eval("window.document." + form + ".SELECT_XTOLCCOMBO_" + group + idx);
			if (sel.options[sel.selectedIndex].value == optVal)
			{
				retVal += parseInt(eval("window.document." + form + ".XTOLCCOMBO_" + group + idx + ".value"));
			}
			idx++;
		}
	}

	return retVal;
}


/*
*	Returns the total count for the option value specified in all the select fields for the specified group.
*/
function getPercentGroupValCount(form, group, optVal)
{
	//alert("form = ["+form+"]\ngroup=["+group+"]\noptVal=["+optVal+"]");
	var retVal = 0;
	idx = 0;
	if (    window.document != null &&
			eval("window.document." + form) != null &&
			typeof eval("window.document." + form + ".SELECT_XTOLCOMBO_" + group + idx) != "undefined"	)
	{
		while(typeof eval("window.document." + form + ".SELECT_XTOLCOMBO_" + group + idx) != "undefined")
		{
			sel = eval("window.document." + form + ".SELECT_XTOLCOMBO_" + group + idx);
			if (sel.options[sel.selectedIndex].value == optVal)
			{
				retVal += parseInt(eval("window.document." + form + ".XTOLCOMBO_" + group + idx + ".value"));
				//alert("optval "+optVal+" found = ["+parseInt(eval("window.document." + form + ".XTOLCOMBO_" + group + idx + ".value"))+"]");
			}
			idx++;
		}
	}

	return retVal;
}


/*
*	Returns the option value of the option within the group that has the highest percent.
*	Takes into account that there may be multiple select boxes specifying the same option.
*	Returns "" if no percent in the group was above 0;
*/
function getPercentGroupMaxId(group)
{
	var highPercent = 0;
	var highId = "";

	//	Get a first select object for this group.
	var selectObj = window.document.xtolform['SELECT_XTOLCOMBO_' + group + 0];

	if (typeof selectObj != "undefined" && selectObj != null)
	{
		for (i = 0; i < selectObj.options.length; i++)
		{
			if (selectObj.options[i].value != "")
			{
				var temp = getPercentGroupValCount('xtolform', group, selectObj.options[i].value);
				if (temp > highPercent)
				{
					highPercent = temp;
					highId = selectObj.options[i].value;
				}
			}
		}
	}
	return highId;
}

/*
*   Returns true if the specified percent group option's value is non-Zero and false if not.
*   This function is meant for the worksheet to determine if an option is selected in a combo widget.
*   It will throw an error if the specified group, option or corresponding array is not in the current document.
*	Takes into consideration that there may be multiple select objects specifying the same option.
*/
function isComboPercentGroupOptionNonZero(group, option)
{
	var retVal = false;
	var names = ArrayList[group + "_COMBO"];

	if(names != null)
	{
		for (var i = 0; i < names.length; i++)
		{
			if (typeof window.document.xtolform["SELECT_" + names[i]] != 'undefined' && typeof window.document.xtolform["SELECT_" + names[i]] != null)
			{
				var selectObj = window.document.xtolform["SELECT_" + names[i]];
				if (selectObj.value == option)
				{
					retVal = true;
					break;
				}
			}
		}
	}

	return retVal;
}

/*
*	Orders a percent group in decending order by percent specified and returns an array of answer IDs in that order.
*	Takes into consideration that there may be multiple select objects specifying the same option.
*	No gaurantees are made concerning the order of same percent values.
*/
function getPercentGroupIndiciesByValue(group)
{
	//alert("in getPercentGroupIndiciesByValue - group = [" + group + "]");
	//	Get a selectObj
	var selectObj = window.document.xtolform['SELECT_XTOLCOMBO_' + group + 0];

	//	Get IDs into new array including only those who's value is greater than 0
	var Ids = new Array();
	var IdIdx = 0;
	for (i = 0; i < selectObj.options.length; i++)
	{
		//alert("in getPercentGroupIndiciesByValue checking ["+selectObj.options[i].value+"] = ["+getPercentGroupValCount('xtolform', group, selectObj.options[i].value)+"]");
		if (selectObj.options[i].value != "" && getPercentGroupValCount('xtolform', group, selectObj.options[i].value) > 0)
		{
			Ids[IdIdx] = selectObj.options[i].value;
			//alert("in getPercentGroupIndiciesByValue adding ID index #["+IdIdx+"] = ["+Ids[IdIdx]+"]");
			IdIdx++;
		}
	}
	//alert("length of array to sort = ["+Ids.length+"]");

	//	Default new Index Array
	var newIdx = new Array();
	for (i = 0; i < Ids.length; i++)
	{
		newIdx[i] = i;
	}
	//alert("length of NEW INDEX array = ["+newIdx.length+"]");

	//	Find Sort Order and store in newIdx
	for (i = 0; i < Ids.length; i++)
	{
		//alert("Checking ["+Ids[i]+"] = ["+getPercentGroupValCount('xtolform', group, Ids[i])+"]");
		for (j = 0; j < Ids.length; j++)
		{
			//	Don't check against itself
			if (j != i)
			{
				//	Swap new index if another entry has higher percent and higher new index
				if (getPercentGroupValCount('xtolform', group, Ids[i]) < getPercentGroupValCount('xtolform', group, Ids[j]) &&
					newIdx[i] > newIdx[j]																			)
				{
					//alert("Checking ["+Ids[i]+"] = ["+getPercentGroupValCount('xtolform', group, Ids[i])+"]\n swapping indexes with \n ["+Ids[j]+"] = ["+getPercentGroupValCount('xtolform', group, Ids[j])+"]");
					temp = newIdx[i];
					newIdx[i] = newIdx[j];
					newIdx[j] = temp;
				}
			}
		}
	}

	//	Fill idsInOrder according to new index.
	var idsInOrder = new Array();
	for (i = 0; i < newIdx.length; i++)
	{
		idsInOrder[newIdx[i]] = Ids[i];
	}

	for (i = 0; i < idsInOrder.length; i++)
	{
		//alert("idsInOrder["+i+"] = ["+idsInOrder[i]+"]");
	}
	return idsInOrder;
}


function getGroupMaxNonCarpetIndex()
{
	var group = "XTOL_FC";
	var highId = getPercentGroupMaxId(group);
//	alert("In getGroupMaxNonCarpetIndex: The max Id is ["+highId+"]");
	if (isCarpetId(highId) || highId == "")
	{
		var idsInOrder = getPercentGroupIndiciesByValue(group);
		for (i = 0; i < idsInOrder.length; i++)
		{
			if (!isCarpetId(idsInOrder[i]))
			{
				highId = idsInOrder[i];
			}
		}
	}
	return highId;
}

function isCarpetId(id)
{
	var retVal = false;
	if (id == "XT_FC_CPT" || id == "XT_FC_CPT_HW" || id == "XT_FC_CPTW")
	{
		retVal = true;
	}
	//alert("In isCarpetId() ID = ["+id+"]\n\nRETURNING ["+retVal+"]");
	return retVal;
}


function nonselectadd(group)
{
	var ar = ArrayList[group];
	sum=0;
	array_size = eval(group+'_LENGTH');
	for (i =0; i<array_size; i++)
	{
		if (typeof window.document.xtolform[ar[i]] != 'undefined' && typeof window.document.xtolform[ar[i]] != null)
		{
			if(window.document.xtolform["AC_"+ar[i]].value == 1 && getType(window.document.xtolform["SELECT_"+ar[i]].value) != 'COUNT')
			{
				var tmpInt = parseInt(window.document.xtolform[ar[i]].value);
				if (!isNaN(tmpInt))
				{
					sum +=tmpInt;
				}
			}
		}

	}
	return sum;
}

function add(group)
{
	var ar = ArrayList[group];
	sum=0;
	array_size = eval(group+'_LENGTH');

	for (i =0; i<array_size; i++)
	{
		if (typeof window.document.xtolform[ar[i]] != 'undefined' && typeof window.document.xtolform[ar[i]] != null)
		{
			var tmpInt = parseInt(window.document.xtolform[ar[i]].value);
			if (!isNaN(tmpInt))
			{
				sum +=tmpInt;
			}
		}
	}
	return sum;
}

function selectcombo(group,input,id,select)
{
	if (isCountTypeInPercentGroup(id) && !isExplicit(getFullIdFromName(id)))
	{
		if (window.document.xtolform[id].value == "" || window.document.xtolform['AC_'+id].value != "1")
		{
			window.document.xtolform[id].value = "1";
		}
	}

	setExplicit(document.xtolform[id]);
	setExplicit(input);

	// External Combo Checkbox
	var ccObj = window.document.xtolform['CC_'+id];
	// Internal Combo Checkbox
	var selObj = window.document.xtolform['SEL_'+id];
	setExplicit(ccObj);

	if(input.value == '')
	{
		if(select)
		{
			if (typeof ccObj != 'undefined')
			{
				ccObj.checked = false;
			}
			if (typeof selObj != 'undefined')
			{
				selObj.checked = false;
			}
		}
		window.document.xtolform[id].value = ZEROVAL;
	}
	else if(select)
	{
		if (typeof ccObj != 'undefined')
		{
			ccObj.checked = true;

		}
		if (typeof selObj != 'undefined')
		{
			selObj.checked = true;
		}
	}

	window.document.xtolform['AC_'+id].value = null;


	// if its not a count type located in a percent group
	// call arrangenum() as usual
	if (isCountTypeInPercentGroup(id))
	{
		toggleCountTypePercentGroup(true, id);
	}
	else
	{
		toggleCountTypePercentGroup(false, id);
		arrangenum(group,select);
	}
}

function isCountTypeInPercentGroup(id)
{
	var retVal = false;
	var dropDownObj = document.xtolform['SELECT_'+id];
	if (typeof dropDownObj != 'undefined' && dropDownObj != null)
	{
		var comboType = getType(dropDownObj.value);
		if (null != comboType && comboType == 'COUNT')
		{
			retVal = true;
		}
	}
	return retVal;
}

function toggleCountTypePercentGroup(changeToCount, id)
{
	if (changeToCount)
	{
		changeToHide("percent_" + id);
		changeToShow("count_" + id, "inline");

		var noExplicit = document.xtolform.EXPLIST == 'undefined' || document.xtolform.EXPLIST == null;

		// Used to change this only if the value was blank. Because
		// of issue #1077 this now will always set the value to one

		// This will now leave some percent values that were sect explicitly
		// But only way to not wipe out data user has input.
		if (!noExplicit && !isExplicit(getFullIdFromName(id)))
		{
			document.xtolform[id].value = "1";
		}

		var autoCalcObj = document.xtolform["AC_"+id];
		if (typeof autoCalcObj != 'undefined' && null != autoCalcObj)
		{
			autoCalcObj.value = "1";
		}
	}
	else
	{
		changeToShow("percent_" + id, "inline");
		changeToHide("count_" + id);
	}
}

function autocalc(group,checkBox,id)
{

	setExplicit(document.xtolform[id]);
	setExplicit(checkBox);
	setExplicit(document.xtolform['SELECT_' + id]);

	if(!checkBox.checked)
	{
		//alert('Making it 0 :' + id);
		window.document.xtolform[id].value = ZEROVAL;
		window.document.xtolform['AC_'+id].value = null;
	}

// 	if(checkBox.checked==true && noncheckadd(group)>=100)
// 	{
// 		alert('Auto Calculate not possible. Sum is already 100 or over.')
// 	}
	arrangenum(group,true);
}

function singlePercentCheckbox(checkBox,id)
{
	setExplicit(document.xtolform[id]);
	setExplicit(checkBox);

//	if(id.indexOf("XT_DECK") == 0)
//		unDefaultDeck(id.substr(id.length -1));
//	else if(id.indexOf("XT_PORCH") == 0)
//		unDefaultPorch(id.substr(id.length -1));

	if(checkBox.checked==false)
	{
		window.document.xtolform[id].value=ZEROVAL;
	}
	else
	{
		window.document.xtolform[id].value=100;
	}
}


function arrangenum(group,select)
{
	var ar = ArrayList[group];
	sum=100-nonselectadd(group);
	//alert(sum);
	cnt=0;
	divided=0;
	remainder=0;
	array_size = eval(group+'_LENGTH');
	//alert("arrangenum-> array_size: " + array_size);

	for (i =0; i<array_size; i++)
	{
		if(select)
		{
			if (typeof window.document.xtolform['SEL_'+ar[i]] != 'undefined' && typeof window.document.xtolform['SEL_'+ar[i]] != null)
			{

				if(window.document.xtolform['SEL_'+ar[i]].checked == true && window.document.xtolform['AC_'+ar[i]].value != 1)
				{
					cnt++;
				}
			}
		}
		else
		{
			if (typeof window.document.xtolform['SELECT_'+ar[i]] != 'undefined' && typeof window.document.xtolform['SELECT_'+ar[i]] != null)
			{
				if(window.document.xtolform['SELECT_'+ar[i]].value != '' && window.document.xtolform['AC_'+ar[i]].value != 1)
				{
					cnt++;
				}
			}
		}
	}

	divided = Math.floor(sum/cnt);
	remainder = sum%cnt;
	var add;
	//alert('div='+divided+' rem='+remainder+' cnt='+cnt + ' sum=' + sum);
	if(select)
	{
		for (i =0; i<array_size; i++)
		{
			if (typeof window.document.xtolform['SEL_'+ar[i]] != 'undefined' && typeof window.document.xtolform['SEL_'+ar[i]] != null)
			{
				if(window.document.xtolform['SEL_'+ar[i]].checked == true && window.document.xtolform['AC_'+ar[i]].value != 1)
				{
					if(divided < 0)
					{
						window.document.xtolform['SEL_'+ar[i]].checked = false;
						window.document.xtolform[ar[i]].value = '';
					}
					else
					{
						if(remainder > 0)
						{
							add = divided + 1;
							remainder--;
						}
						else
						{
							add = divided;
						}
						window.document.xtolform[ar[i]].value = add;
					}
				}
			}
		}
	}
	else
	{
		for (i =0; i<array_size; i++)
		{
			//alert(eval('window.document.xtolform.SELECT_'+ar[i]+'.value'));
			if (typeof window.document.xtolform['SELECT_'+ar[i]] != 'undefined' && typeof window.document.xtolform['SELECT_'+ar[i]] != null)
			{
				if(window.document.xtolform['SELECT_'+ar[i]].value != '' && window.document.xtolform['AC_'+ar[i]].value != 1)
				{
					if(divided < 0)
					{
						window.document.xtolform['SELECT_'+ar[i]].value = '';
						window.document.xtolform[ar[i]].value = '';
					}
					else
					{
						if(remainder > 0)
						{
							add = divided + 1;
							remainder--;
						}
						else
						{
							add = divided;
						}
						window.document.xtolform[ar[i]].value = add;
					}
				}
			}
		}
	}
		//alert("here a");

	//consolidate double answers. notice there are no evil evals.
	var tmpArray = new Array();
	for (i =0; i<array_size; i++)
	{
	//alert("ar["+i+"]=" + ar[i]);
		if ((!select || !window.document.xtolform['SEL_'+ar[i]] || window.document.xtolform['SEL_'+ar[i]].checked != false) &&
			typeof window.document.xtolform['SELECT_'+ar[i]] != 'undefined' && typeof window.document.xtolform['SELECT_'+ar[i]] != null &&
			window.document.xtolform[ar[i]].value != '')
		{
			var currId = window.document.xtolform['SELECT_'+ar[i]].value;
			if(currId == "XT_BGU")
			{
				currId = ar[i];
			}
			if(currId != '')
			{
				if(tmpArray[currId] == null)
				{
					tmpArray[currId] = i;
				}
				else
				{
					var inx = tmpArray[currId];
					var val		= parseInt(window.document.xtolform[ar[inx]].value);
					var val2	= parseInt(window.document.xtolform[ar[i]].value);

					if (isNaN(val)) val = 0;
					if (isNaN(val2)) val2 = 0;
					val += val2;
					if(val > 100)
					{
						val = 100;
					}
					if(val != 0)
					{
						window.document.xtolform[ar[inx]].value = val;
						window.document.xtolform[ar[i]].value = ZEROVAL;
						if(select)
						{
							window.document.xtolform['SEL_'+ar[i]].checked = false;
							window.document.xtolform['SEL_'+ar[inx]].checked = true;
						}
						else
						{
							window.document.xtolform['SELECT_'+ar[i]].value='';
						}
					}
					else
					{
						if(select)
						{
							window.document.xtolform[ar[inx]].value = ZEROVAL;
							window.document.xtolform[ar[i]].value = 0;
							window.document.xtolform['SEL_'+ar[i]].checked = true;
							window.document.xtolform['SEL_'+ar[inx]].checked = false;
						}
					}
				}
			}
		}
	}
		//alert("here b");

	for (i =0; i<array_size; i++)
	{
		if (typeof window.document.xtolform[ar[i]] != 'undefined' && typeof window.document.xtolform[ar[i]] != null)
		{
			var val	= parseInt(window.document.xtolform[ar[i]].value);
			if (isNaN(val)) val = 0;
			if(window.document.xtolform[ar[i]].value > 0)
			{
				setExplicit(document.xtolform[ar[i]]);
				setExplicit(document.xtolform['SELECT_' + ar[i]]);
				setExplicit(document.xtolform['SEL_' + ar[i]]);
			}
		}
	}

	setTotalForGroup(group);
}


//  Handles cases where the code to prevent users from selecting two instances of the same material
//  (i.e. 50% Basement, 50% Basement) interfears with the user's ability to use the up and down keys to
//  successfully select the option whey want. This if this is the case, it pushes the selection past the option
//  that is already selected before the other code (found near the end of the arrangenum function) forces the
//  choice back to [none selected].
//
//  This function uses the new standard event model and should be called thus: "onKeyDownCombo(event)"
//  This function is documented so indicating who the author is should be a unnecessary.
function onKeyDownCombo(e, groupName)
{
	//  Handle only cases for up or down arrow.
	if (e.keyCode == 38 || e.keyCode == 40)
	{
		//  Get the select element that fired this event.
		var selPrefix = "SELECT_";
		var comboPrefix = "XTOLCOMBO_";
		var groupSuffix = "_COMBO";
		var sel = e.currentTarget;
		if (!sel)
		{
			sel = e.srcElement;
		}

		//  Find out the index the user was moving to (ONKEYDOWN event fires before value changes)
		var destinationIdx = sel.selectedIndex;

		if (e.keyCode == 40)
		{
			if (destinationIdx < sel.length - 1)
			{
				++destinationIdx;
			}
		}
		else
		{
			if (destinationIdx > 0)
			{
				--destinationIdx;
			}
		}

		// STC: Nathan is right, there is a better way, I changed the widget.java to print out the groupName
		// so that you don't have to try and parse it out...the code below wasn't working with prefixes
/*		//  Extract the group name from the select element.
		//  NFD: I don't know what this is doing, but I don't like it. THGTBABW.  Fix it someday.
		var baseName = sel.name.slice((selPrefix + comboPrefix).length);
		while(typeof ArrayList[baseName.slice(0, (baseName.length-1)) + groupSuffix] == "undefined")
		{
			baseName = baseName.slice(0, (baseName.length-1));
			if (baseName.length < 1)
			{
				//  Safety valve to prevent case of endless looping - should not happen.
				return;
			}
		}
		baseName = baseName.slice(0, (baseName.length-1));
		var groupName = baseName + groupSuffix;
*/

		//  Get the corresponding array.
		var ar = ArrayList[groupName];

		//  Final value holder.
		var newIndex = sel.selectedIndex;


		//  Loop through group members checking for duplicate selections
		for (i = 0; i < ar.length; i++)
		{
			var destinationVal = sel.options[destinationIdx].value;
			otherSel = window.document.xtolform[selPrefix + ar[i]];

			//  The user is attempting to select something other than [none selected] and the same value exists in a
			//  different select field in the same group.
			if (otherSel != null && otherSel.name != sel.name && destinationVal != "" && otherSel.selectedIndex == destinationIdx)
			{
				// down arrow (increase index)
				if (e.keyCode == 40)
				{
					if (destinationIdx < sel.length - 1)
					{
						newIndex = destinationIdx;
						++destinationIdx;
						i = -1;
					}
					//  User pushing the down arrow when all the selections lower on the list are already taken
					else if (destinationIdx == (sel.length - 1))
					{
						//  Reset control - has the affect of blanking the select momentarily
						newIndex = -1;
						break;
					}
				}
				//  Up arrow (lower index)
				else
				{
					if (destinationIdx > 0)
					{
						newIndex = destinationIdx;
						--destinationIdx;
						i = -1;
					}
				}
			}
		}

		//  Set final value
		sel.selectedIndex = newIndex
	}
}

function adddefault(id,selectinput,hascheckbox)
{
	setExplicit(document.xtolform[id]);
	setExplicit(selectinput);
	if (hascheckbox) setExplicit(document.xtolform["CC_"+id]);

	if(selectinput.value=='')
	{
		document.xtolform[id].value='';
		if (hascheckbox != 'undefined' && hascheckbox)
		{
			document.xtolform["CC_"+id].checked=false;
		}
	}
	else
	{
		var actualId = getActualId(id);
		var limit = getLimit(actualId);
		var divName = "DIV_"+id;

		document.xtolform[id].value=1;

		if(limit == 1)
		{
			//hide box and spinner using div tags
			changeToHide(divName + "_1");
			changeToHide(divName + "_2");
			changeToHide(divName + "_3");
		}
		else
		{
			//show box and spinner - NFD said to use three divs instead of fixing the html, even though it is bad.
			changeToShow(divName + "_1");
			changeToShow(divName + "_2");
			changeToShow(divName + "_3");
		}

		if (hascheckbox != 'undefined' && hascheckbox)
		{
			document.xtolform["CC_"+id].checked=true;
		}
	}
	
	adddefaultPageSpecific(selectinput);
}

function adddefaultPageSpecific(obj)
{
	// override me in the page if you need to
}

//*********************//
//* DIV TAG FUNCTIONS *//
//*********************//

function changeToShow(tabContentID, displayType)
{
	var tabContent = document.getElementById(tabContentID);
	changeToShowByElement(tabContent, displayType);
}

function changeToShowByElement(tabContent, displayType)
{
	if (displayType == null)
	{
		displayType = "block";
	}
	if (tabContent != null)
	{
		tabContent.style.display = displayType;
	}
//	else
//	{
//		alert(tabContentID+" not found");
//	}
	setFooter();
}
function changeGettingDefaultsDivToShow(tabContentID)
{
	var tabContent = document.getElementById(tabContentID);
	if (tabContent != null)
	{
		tabContent.style.display = "inline-block";
	}
}
function changeToHide(tabContentID)
{
	var tabContent = document.getElementById(tabContentID);
	changeToHideByElement(tabContent);
}

function changeToHideByElement(element)
{
	if (element != null)
	{
		element.style.display = "none";
	}
//	else
//	{
//		alert(tabContentID+" not found");
//	}
	//setFooter();
}

function changeParentToShow(tabContentID)
{
	var tabContent = opener.document.getElementById(tabContentID);
	if (tabContent != null)
	{
		tabContent.style.display = "block";
	}
}
function changeParentToHide(tabContentID)
{
	var tabContent = opener.document.getElementById(tabContentID);
	if (tabContent != null)
	{
		tabContent.style.display = "none";
	}
}

// If you want to hide a <tr> or <td> tag use this one so that it works
// in i.e. and firefox
function changeToShowTR(tabContentID)
{
	changeToShow(tabContentID, "");
}


//*******************
//	Returns the value of the display attrib for the specified element.
//*******************
function getDisplay(id)
{
	var obj = document.getElementById(id);
	return obj.style.display;
}

//***************//
//* MHS SCRIPTS *//
//***************//

function headerXtolSubmit(navigate)
{
	if(navigate=='null')
	{
		navigate='Owner';
	}
	if (navigate != null && navigate == "Help")
	{
		navigate = document.xtolform.curpage.value;
		var query = new HelpQuery();
		query.XTOL_CUR_PAGE = navigate;
		query.helpFrameMode = "helpFrameNav";
		query.helpMode = "helpSearch";
		MHSNavHelpPopup(query.toString());
	}
	else
	{
		submitXtolForm(navigate);
	}
}

/*
	If you want to disable double clicking a link follow the following steps:
		1. Create JS array for it and add it to the STP_DBL_CLCK array (i.e. STP_DBL_CLCK['CALC'] = new Array();)
		2. Set its SDC_PROCESSING_INDEX to false and its SDC_TIMEOUT_INDEX to whatever you want
		3. Then in the page where the link is located add an onclick event that returns disableDoubleClick(type) (i.e. onclick="javascript:return disableDoubleClick('CALC');")
		4. Finally in the JS method called by the href call the setSDCProcessing(type) before you submit the page (i.e. setSDCProcessing('CALC');, see finalXtolSubmit() below)
*/


// Disable double click vars
var STP_DBL_CLCK = new Array();
STP_DBL_CLCK['CALC'] = new Array();
STP_DBL_CLCK['SEARCH'] = new Array();
STP_DBL_CLCK['REPORT'] = new Array();
STP_DBL_CLCK['SEND'] = new Array();
STP_DBL_CLCK['REASSIGN'] = new Array();

var SDC_PROCESSING_INDEX = 0;
var SDC_TIMEOUT_INDEX = 1;

STP_DBL_CLCK['CALC'][SDC_PROCESSING_INDEX] = false;
STP_DBL_CLCK['SEARCH'][SDC_PROCESSING_INDEX] = false;
STP_DBL_CLCK['REPORT'][SDC_PROCESSING_INDEX] = false;
STP_DBL_CLCK['SEND'][SDC_PROCESSING_INDEX] = false;
STP_DBL_CLCK['REASSIGN'][SDC_PROCESSING_INDEX] = false;

// milliseconds
STP_DBL_CLCK['CALC'][SDC_TIMEOUT_INDEX] = 10000;
STP_DBL_CLCK['SEARCH'][SDC_TIMEOUT_INDEX] = 10000;
STP_DBL_CLCK['REPORT'][SDC_TIMEOUT_INDEX] = 3000;
STP_DBL_CLCK['SEND'][SDC_TIMEOUT_INDEX] = 7000;
STP_DBL_CLCK['REASSIGN'][SDC_TIMEOUT_INDEX] = 10000;


function disableDoubleClick(type)
{
	if (STP_DBL_CLCK[type][SDC_PROCESSING_INDEX])
	{
		//alert("returning false");
		return false;
	}
	//alert("returning true");
	return true;
}

function setSDCProcessing(type)
{
	if (!STP_DBL_CLCK[type][SDC_PROCESSING_INDEX])
	{
		STP_DBL_CLCK[type][SDC_PROCESSING_INDEX] = true;
		setTimeout("STP_DBL_CLCK['"+type+"'][SDC_PROCESSING_INDEX] = false;", STP_DBL_CLCK[type][SDC_TIMEOUT_INDEX]);
	}
}

function finalXtolSubmit()
{
	//	Check XTOL Calculate and open pleasewait
	if (    (typeof document.xtolform.calculate != 'undefined' &&
			document.xtolform.calculate != null &&
			document.xtolform.calculate.value != "")
				||
			(typeof document.xtolform.recalculate != 'undefined' &&
			document.xtolform.recalculate != null &&
			document.xtolform.recalculate.value != "")
																	)
	{				
		setSDCProcessing('CALC');
		XTOLPleaseWaitPopup();
	}
	
	document.xtolform.submit();
}

var alreadyCalculating = false;
function disableDoubleCalc()
{
	alert('dont use this function, use disableDoubleClick instead. tell stc you saw this');
	if (alreadyCalculating)
	{
		return false;
	}
	return true;
}
	
function submitXtolForm(navigate)
{
	if (navigate != null && navigate != "")
	{
		document.xtolform.nav.value = navigate;
	}

	finalXtolSubmit();
}

function validateAndSubmit(navigate)
{
	submitXtolForm(navigate);
}

function validateAndCalculate(navigate)
{
	if (!document.xtolform.calculate.value)
	{
		document.xtolform.calculate.value = "true";
		validateAndSubmit(navigate);
	}
}

function submitXtolFormSave(navigate)
{
	document.xtolform.nav.value = navigate;
	document.xtolform.calculate.value = '1';
	submitXtolForm(navigate);
}


function boolWidgetOnChange(id)
{
//	if(id.indexOf("XT_OTHERATTACHED") == 0)
//		unDefaultAttached(id.substr(id.length -1));

	setExplicit(document.xtolform["CBOX_"+id]);
	setExplicit(document.xtolform[id]);

	if (document.xtolform["CBOX_"+id].checked)
	{
		document.xtolform[id].value = "1";
	}
	else
	{
		document.xtolform[id].value = "0";
	}
	boolWidgetOnChangeSpecialCases(id);
	showFocus(document.xtolform["CBOX_"+id]);
}

function boolWidgetOnChangeSpecialCases(id)
{
	// Attached structures section
	if (id == "XT_GLOBAL_CDQ_GF")
	{
		doIFGActualCondoQuestions()
	}

	if (id == "XT_GLOBAL_CDQ_OAS")
	{
		doOASActualCondoQuestions();
	}

	// Exterior Section
	/*if (id == "XT_GLOBAL_CDQ_ED" || id == "XT_GLOBAL_CDQ_W")
	{
		doExteriorFeaturesLink();
	}*/

	// Interior Section
	if (id == "XT_GLOBAL_CDQ_IWM")
	{
		doInteriorWMQuestion();
	}
	/*if (id == "XT_GLOBAL_CDQ_LF" || id == "XT_GLOBAL_CDQ_ID_IT")
	{
		doInteriorFeaturesLink();
	}*/

}

var needToCallGetRoomDefaults = false;
var needToCallGetFoundationDefaults = false;
var needToCallValidateStreetAddress = false;
function checkRequiredFieldsForFD()
{
	return true;
}

function checkRequiredFieldsForAD()
{
	return true;
}

function validateQuality()
{
	//if( window.document.xtolform.XT_STRUCT_QUALITY[window.document.xtolform.XT_STRUCT_QUALITY.selectedIndex].value == 111)
	//{
	//	return false;
	//}
	//else
	//{
		return true;
	//}
}

function functionalCostOnChange(funcObj)
{
	setExplicit(funcObj);
	checkAutoDefault();
	doWSCheck();
	doHWCheck();
}

function yearBuiltOnChange()
{
	validateXTOLYearBuilt(true);
	if( window.document.xtolform.XT_YEAR_BUILT.value > 0 &&
		window.document.xtolform.XT_YEAR_BUILT.value < 1971)
	{
		changeToShow('xtFunctionalCost');
	}
	else
	{
		if (typeof window.document.xtolform['CBOX_XT_FUNCTIONAL_COST'] != 'undefined')
		{
			window.document.xtolform.CBOX_XT_FUNCTIONAL_COST.checked = false;
			window.document.xtolform.XT_FUNCTIONAL_COST.value = 0;
		}
		changeToHide('xtFunctionalCost');
	}

	checkAutoDefault(window.document.xtolform.XT_YEAR_BUILT);
	doWSCheck();
	doHWCheck();
}

function useOnChange(obj)
{
	checkAutoDefault(obj);
	if (document.xtolform.MultiPlexAlert.value == 'false')
	{
		openMultiPlexAlert();
	}
}


function openMultiPlexAlert()
{
	if (document.xtolform.SELECT_XTOLCOMBO_XTOL_STRUCT_PURPOSE_PERCENT.value != "XT_STRUCT_PURPOSE_PERCENT0")
	{
		MHSSmallPopup("_MultiplexAlertPopup.jsp", 1);
	}
}

function squareFootageOnChange()
{
	setExplicit(document.xtolform.XT_USER_TOTAL_SF);

	syncSquareFootage();
	checkAutoDefault(document.xtolform.XT_USER_TOTAL_SF);
}

function structTypeOnChange(obj)
{
	setExplicit(obj);

	checkAutoDefault(obj);

	var styleObj = document.xtolform.SELECT_XTOLCOMBO_XTOL_STRUCT_STYLE_PERCENT;
	if (typeof styleObj != 'undefined' && null != styleObj)
	{
		var selectedStyle = styleObj.options[styleObj.selectedIndex].value;
		if (isCondoStyle(selectedStyle))
		{
			changeToHide("xtHalfStory");
		}
		else
		{
			checkHiddenValue();
		}
	}
}

function onSlopeChange(obj)
{
  setExplicit(obj);
  if (document.xtolform.curpage.value == 'Worksheet')
  {
	checkAutoDefault(obj);
  }
}

function onBasementQualityChange(obj)
{
 	setExplicit(obj);
	checkAutoDefault(obj);
}

function onFoundShapeChange(obj)
{
  setExplicit(obj);
//  if (document.xtolform.curpage.value == 'Worksheet')
//  {
	checkAutoDefault(obj);
//  }
}

function onBmtFinishedChange(obj)
{
  setExplicit(obj);
//  if (document.xtolform.curpage.value == 'Worksheet')
//  {
	checkAutoDefault(obj);
//  }
  validateSinglePercent(obj, obj.name, false);
}

function onSinglePercentChange(obj, inputid, check)
{
	if(obj.value != '')
	{
		setExplicit(obj);
	}
	validateSinglePercent(obj, obj.name, false);
	if(check)
	{
		setExplicit(window.document.xtolform['SEL_'+inputid]);
		if(window.document.xtolform['SEL_'+inputid].checked != true)
		{
			window.document.xtolform['SEL_'+inputid].checked = true;
		}
		if(window.document.xtolform[inputid].value == 0)
		{
			window.document.xtolform['SEL_'+inputid].checked = false;
		}
	}
}

function clearSquareFootage()
{
	if (xtolform.XT_SF_KNOWN[0].checked == true)
	{
		xtolform.XT_USER_TOTAL_SF.value = 0;
	}
	return;
}


function syncSquareFootage()
{
	document.xtolform.XT_USER_TOTAL_SF.value = document.xtolform.XT_USER_TOTAL_SF.value.replace(/,/g,"");
	var sf = parseInt(document.xtolform.XT_USER_TOTAL_SF.value, 10);

	if (document.xtolform.XT_USER_TOTAL_SF.value == ''
		|| isNaN(document.xtolform.XT_USER_TOTAL_SF.value) || sf <= 0)
	{
		document.xtolform.XT_USER_TOTAL_SF.value = ZEROVAL;
		return false;
	}
	return true;
}


function validateXTOLYearBuilt(doAlert)
{
	var yearObj = window.document.xtolform.XT_YEAR_BUILT;
	return validateXTOLYearBuiltObj(doAlert, yearObj);
}

function validateXTOLYearBuiltObj(doAlert, yearFieldObj)
{
	var year = yearFieldObj.value;
	var curYear = new Date().getFullYear();
	var isNumber = true;
	for (var i = 0; i < year.length; i++)
	{
		var c = year.charAt(i);
		if (isNaN(parseInt(c)))
		{
			isNumber = false;
		}
	}

	if (!isNumber || year.length != 4 || year < 1600 || year > curYear)
	{
		/*
			Perhaps you've noticed that the year field is reset in both the if
			and the else code blocks. Please don't break it out and remove the
			else block. Though it needs to happen in both cases, but it must
			happen in the setTimeout code when the alert is on to prevent
			the onchange event from firing twice in IE. - KMS
		*/
		if (doAlert)
		{
			alert("The Year Built field requires a four-digit year value that is\ngreater than 1599 but not greater than the current year.");
			var code = " document." + yearFieldObj.form.name + "['" + yearFieldObj.name + "'].value = ''; ";
			code += " document." + yearFieldObj.form.name + "['" + yearFieldObj.name + "'].focus(); ";
			setTimeout(code, 1);
		}
		else
		{
			yearFieldObj.value = "";
		}
		return false;
    }
	else
	{
		setExplicit(yearFieldObj);
		return true;
    }
}

function initHalfStory()
{
	if(		window.document.xtolform.SELECT_XTOLCOMBO_XTOL_STRUCT_TYPE_PERCENT.value == "XT_STRUCT_TYPE_PERCENT1"
		||	window.document.xtolform.SELECT_XTOLCOMBO_XTOL_STRUCT_TYPE_PERCENT.value == "XT_STRUCT_TYPE_PERCENT3"
		||	window.document.xtolform.SELECT_XTOLCOMBO_XTOL_STRUCT_TYPE_PERCENT.value == "XT_STRUCT_TYPE_PERCENT8"	)
	{
		changeToShow('xtHalfStory');
	}
}

function initYearBuilt()
{
	if( window.document.xtolform.XT_YEAR_BUILT.value > 0 &&
		window.document.xtolform.XT_YEAR_BUILT.value < 1971)
	{
		changeToShow('xtFunctionalCost');
	}
	else
	{
		window.document.xtolform.XT_YEAR_BUILT.checked = false;
		changeToHide('xtFunctionalCost');
	}
}

function checkHiddenValue()
{

	if(		window.document.xtolform.SELECT_XTOLCOMBO_XTOL_STRUCT_TYPE_PERCENT.value == "XT_STRUCT_TYPE_PERCENT1"
		||	window.document.xtolform.SELECT_XTOLCOMBO_XTOL_STRUCT_TYPE_PERCENT.value == "XT_STRUCT_TYPE_PERCENT3"
		||	window.document.xtolform.SELECT_XTOLCOMBO_XTOL_STRUCT_TYPE_PERCENT.value == "XT_STRUCT_TYPE_PERCENT8"	)
	{
		if (getDisplay('xtHalfStory') != "block")
		{
			changeToShow('xtHalfStory');
			window.document.xtolform.XT_HALF_STORY_FIN_PERCENT.value = 100;
        }
	}
	else
	{
		changeToHide('xtHalfStory');
        window.document.xtolform.XT_HALF_STORY_FIN_PERCENT.value = 0;
	}

	var styleObj = document.xtolform.SELECT_XTOLCOMBO_XTOL_STRUCT_STYLE_PERCENT;
	if (typeof styleObj != 'undefined' && null != styleObj)
	{
		var selectedStyle = styleObj.options[styleObj.selectedIndex].value;
		// Currently condos do not display the struct style drop down so this really isn't needed
		// I kept it here in case in the future the drop down is added

		if (!isCondoStyle(selectedStyle))
		{

			checkHiddenFoundationFields();
		}
		checkAllFireplaceDetailLinks();
	}

}

function checkHiddenFoundationFields()
{
	var foundBiLevel = false;
	var foundBasement = false;
	var foundPost = false;

	var storyObj = window.document.xtolform.SELECT_XTOLCOMBO_XTOL_STRUCT_TYPE_PERCENT;
	if(typeof storyObj != 'undefined' && storyObj.value == "XT_STRUCT_TYPE_PERCENT5")
	{
		foundBiLevel = true;
	}


	if(isComboPercentGroupOptionNonZero("XTOL_FOUND_CONST_PERCENT", "XT_FOUND_CONST_PERCENT0") || isComboPercentGroupOptionNonZero("XTOL_FOUND_CONST_PERCENT", "XT_FOUND_CONST_PERCENT6"))
	{
		foundBasement = true;
	}
	if(isComboPercentGroupOptionNonZero("XTOL_FOUND_CONST_PERCENT", "XT_FOUND_CONST_PERCENT4") || isComboPercentGroupOptionNonZero("XTOL_FOUND_CONST_PERCENT", "XT_FOUND_CONST_PERCENT5"))
	{
		foundPost = true;
	}

	if(foundBasement || foundBiLevel) changeToShow('xtbasement');
	else
	{
		changeToHide('xtbasement');
		window.document.xtolform.XT_BASEMENT_FIN_PERCENT.value = '';
		removeFromExplicitList(window.document.xtolform.XT_BASEMENT_FIN_PERCENT);
	}

	if(foundPost) changeToShow('xtposts');
	else changeToHide('xtposts');


}


function onFireplaceStyleChange(obj, num, isInit)
{
	if(isInit != true)
	{
		setExplicit(obj);
		// Make all the other fireplaces turn blue but not explicit
		for(var i=0; i < 9; i++)
		{
			var currentFireplaceObj = document.xtolform['XT_FP_STYLE' + i];
			if(typeof currentFireplaceObj != 'undefined' && currentFireplaceObj != null && showExplicit)
			{
				currentFireplaceObj.className = 'defaultedText';
			}
		}
	}

	var tabContent = document.getElementById('XT_FP_2'+num);
	//alert('selectedIndex = '+obj.selectedIndex+' display = ' + tabContent.style.display + ' opt.value = ' + obj.options[obj.selectedIndex].value);

	if (obj.selectedIndex > 0 && tabContent.style.display != 'none')
	{
		changeToShow('XT_FPO_3'+num);
	}
	else
	{
		obj.options.value = "0"; //Fireplace.BLANKSTYLE
		obj.options[obj.selectedIndex].value = "0"; //Fireplace.BLANKSTYLE
		changeToHide('XT_FPO_3'+num);  // Hide More Details
	}
	
	onFireplaceStyleChangePageSpecific(obj);
}

function onFireplaceStyleChangePageSpecific(obj)
{
	// override this if you need to in the page
}

function checkAllFireplaceDetailLinks()
{
	for (var i=0; i<XT_FP_COMBO_MAX; i++)
	{
		var obj = document.xtolform['XT_FP_STYLE'+i];
		onFireplaceStyleChange(obj, i, true);
	}
}

function FireplaceDetailPopupBase(navigate, num, name)
{
	var width = 400;
	var height = 350;
	var position = MHSCenterPopup(height, width);
	savenav = document.xtolform.nav.value;

	// Make sure num is correct (if there are blanks above a fireplace
	// they are shifted to the bottom and we need to account for that here)
	var newFireplaceNumber = num;
	for(var i=0; i<num; i++)
	{
		var obj = document.xtolform['XT_FP_STYLE'+i];
		if(typeof obj != 'undefined' && obj != null && obj.selectedIndex == 0)
		{
			newFireplaceNumber--;
		}
	}
	num = newFireplaceNumber;

	//setup data
	document.xtolform.savetofile.value = "";

	//set name if not passed in
	if(arguments.length < 3)
	{
		name = 'fpdetailwin';
	}

	//open window to submit to
	position = MHSCenterPopup(height, width);
	document.xtolform.fpnum.value = num;
	mhspopupfpdetailwin = popWindow("/xtol/blank.htm", name, position + ",toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=yes,height="+height+",width="+width);

	if (mhspopupfpdetailwin.opener == null)
		mhspopupfpdetailwin.opener = self;

	mhspopupfpdetailwin.focus();

	//redirect form
	document.xtolform.target = mhspopupfpdetailwin.name;
	submitXtolForm(navigate);

	//put things back.
	document.xtolform.target = "_top";
	document.xtolform.nav.value = savenav;
	document.xtolform.savetofile.value = "true";
	document.xtolform.fpnum.value = "";
}

function submitPageAndOpenPopup(navigate, height, width, name)
{
	var position = MHSCenterPopup(height, width);
	savenav = document.xtolform.nav.value;

	// I don't think I need to do this
	/*var saveToFileObj = document.xtolform['savetofile'];
	if (typeof saveToFileObj != undefined)
	{
		saveToFileObj.value = "";
	}*/

	popupwin = popWindow("/xtol/blank.htm", name, position + ",toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=yes,height="+height+",width="+width);

	if (popupwin.opener == null)
		popupwin.opener = self;

	popupwin.focus();

	//redirect form
	document.xtolform.target = popupwin.name;
	submitXtolForm(navigate);

	//put things back.
	document.xtolform.target = "_top";
	document.xtolform.nav.value = savenav;
	//document.xtolform.savetofile.value = "true";

}

function foundationConstOnChange(group,input,id,select)
{
  hiddenCheck(group, input, id, select);
  setExplicit(input);

//  if (document.xtolform.curpage.value == 'Worksheet')
//  {
	checkAutoDefault(input);
//  }
}

function foundationMatOnChange(group, input, id, select)
{
  setExplicit(input);
  selectcombo(group,input,id,select);
//  if (document.xtolform.curpage.value == 'Worksheet')
//  {
	checkAutoDefault(input);
//  }
}

function hiddenCheck(group,input,id,select)
{
	checkHiddenValue();
	selectcombo(group,input,id,select);
}

//<!--Guide-->
var pop = null;

function AgentPopupDownload()
{
		var loc = "/msagent/settings.htm";
		var width = 650;
		var height = 550;
		var position = MHSCenterPopup(height, width);

		pop = window.open(loc, "controlcenter", position + ',width=' + width + ',height=' + height + ', status=yes,menubar=no,resizable=no,top=0,left=600,screenX=0,screenY=0');
		pop.focus();
}

//******************************
// CONFIRM COMMAND

function ConfirmDelete(description, query)
{
	var sure = confirm("Are you sure you want to permanently delete " + UnescapeDQ(description) + "?");
	if (sure == true) location = query;
}

function ConfirmInactive(description, query)
{
	var sure = confirm("Are you sure you want to inactivate " + UnescapeDQ(description) + "?");
	if (sure == true) location = query;
}

function ConfirmUnlink(description, query)
{
	var sure = confirm("Are you sure you want to unlink " + UnescapeDQ(description) + "?");
	if (sure == true) location = query;
}

//******************************
// POPUP WINDOWS

//**********************************************
//	getWindowPosition
//*********************************************
//	Returns a multi-browser-compatible string to
//	be used in the window.open() features parameter.
//*********************************************

function getWindowPosition(x, y)
{
	var position = "screenX=" + x + ",screenY=" + y;
	if (getMSIEVersionNumber() != -1)
	{
		position = "left=" + x + ",top=" + y;
	}
	return position;
}

function centerPopup(height, width)
{
	return MHSCenterPopup(height, width);
}

function MHSCenterPopup(height, width)
{
	var x = (window.screen.availWidth/2) - (width/2);
	var y = (window.screen.availHeight/2) - (height/2);
	var position = getWindowPosition(x, y);
//	alert("MHSCenterPopup method: position =["+position+"].");
	return position;
}

function MHSSizablePopup(query, height, width, name)
{
	var position = MHSCenterPopup(height, width);
	if(arguments.length < 4)
	{
		name = 'sizablewin';
	}
	var mhssizablewin = popWindow(query, name, position + ",toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,height=" + height + ",width=" + width);
	if (mhssizablewin.opener == null)
		mhssizablewin.opener = self;
	mhssizablewin.focus();
}

function MHSNonSizablePopup(query, height, width, name)
{
	var position = MHSCenterPopup(height, width);
	if(arguments.length < 4)
	{
		name = 'sizablewin';
	}
	var mhsnonsizablewin = popWindow(query, name, position + ",toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,height=" + height + ",width=" + width);
	if (mhsnonsizablewin.opener == null)
		mhsnonsizablewin.opener = self;
	mhsnonsizablewin.focus();
}


function MHSModalSizablePopup(query, height, width)
{
	openDialog(query, width, height, null, null);
}

function MHSNoScrollSizablePopup(query, height, width, name)
{

	var position = MHSCenterPopup(height, width);
	if(arguments.length < 4)
	{
		name = 'noscrollsizablewin';
	}
	mhssizablewin = popWindow(query, name, position + ",toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=yes,height=" + height + ",width=" + width);
	if (mhssizablewin.opener == null) mhssizablewin.opener = self;
	mhssizablewin.focus();
}

function MHSNamedNoScrollSizablePopup(query, height, width, winName)
{
	if (checkDelayedAction('MHSNamedNoScrollSizablePopup(\"'+query+'\",\"'+height+'\",\"'+width+'\",\"'+winName+'\")'))
	{
		return;
	}

	var position = MHSCenterPopup(height, width);
	mhssizablewin = popWindow(query, winName, position + ",toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=yes,height=" + height + ",width=" + width);
	if (mhssizablewin.opener == null) mhssizablewin.opener = self;
	mhssizablewin.focus();
}

function XTOLLargeLongPopup(query, name)
{
	var width = 600;
	var height = 525;
	var position = MHSCenterPopup(height, width);
	if(arguments.length < 2)
	{
		name = 'largewin';
	}
	xtollargewin = popWindow(query, name, position + ',toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no,width='+width+',height='+height);

	if (xtollargewin.opener == null)
        xtollargewin.opener = self;

	xtollargewin.focus();
}

function XTOLPleaseWaitPopup()
{
	var width = 155;
	var height = 150;
	var x = (window.screen.availWidth/2) - (width/2);
	var y = (window.screen.availHeight/2) - (height/2);
	var position = MHSCenterPopup(height, width);
	var size = "width=" + width + ",height=" + height;
	var	query = "/xtol/xtolPleaseWait.htm";
	xtolpleasewait = window.open(query, 'mhspopuppleasewait', position + ',toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,' + size);
	if (xtolpleasewait.opener == null) xtolpleasewait.opener = self;
	xtolpleasewait.focus();
}

function GenericPleaseWaitPopup()
{
	var width = 155;
	var height = 150;
	var x = (window.screen.availWidth/2) - (width/2);
	var y = (window.screen.availHeight/2) - (height/2);
	var position = MHSCenterPopup(height, width);
	var size = "width=" + width + ",height=" + height;
	var	query = "/xtol/genericPleaseWait.htm"

	genericpleasewait = window.open(query, 'mhspopuppleasewait', position + ',toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,' + size);

	if (genericpleasewait.opener == null)
        genericpleasewait.opener = self;

	genericpleasewait.focus();
}

function XTOLClosePleaseWaitPopup()
{
	//	Check for the existence of a pleasewait popup and close it if it is there.
    if (typeof xtolpleasewait != 'undefined' && !xtolpleasewait.closed)
	{
		delete(xtolpleasewait);
		//xtolpleasewait = null;
		//xtolpleasewait.close();
	}
}

function GenericClosePleaseWaitPopup()
{
	//	Check for the existence of a pleasewait popup and close it if it is there.
    if (typeof genericpleasewait != 'undefined' && !genericpleasewait.closed)
	{
		delete(genericpleasewait);
	}
}

function MHSPleaseWaitPopup(query)
{
	var width = 130;
	var height = 150;
	var position = MHSCenterPopup(height, width);
	var size = "width=" + width + ",height=" + height;
	if (query == null)
	{
		query = "BaseAuthServlet?forwardURL=/PleaseWait.jsp";
	}
	mhspleasewait = window.open(query, 'mhspopuppleasewait', position + ',toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,' + size);
	if (mhspleasewait.opener == null) mhspleasewait.opener = self;
	mhspleasewait.focus();
}

function ClosePleaseWaitPopup()
{
	var width = 150;
	var height = 50;
	var x = window.screen.width + 1000;
	var y = window.screen.height + 1000;
	var position = "left=" + x + ",top=" + y;
	//window.alert(position);
	mhspleasewait = window.open( "/xtol/blank.htm", 'mhspopuppleasewait', position + ',toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no');
	mhspleasewait.close();
}

function MHSSmallPopup(query, poplevel, name, width, height)
{
	if (typeof width == 'undefined')
	{
		width = 400;
	}
	if (typeof height == 'undefined')
	{
		height = 300;
	}
	var position = MHSCenterPopup(height, width);
	if(null == name || typeof name == 'undefined')
	{
		name = 'smallwin';
	}
	var mhssmallwin = popWindow(query, name, position + ',toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width='+width+',height='+height);
	if (mhssmallwin.opener == null) mhssmallwin.opener = self;
	mhssmallwin.focus();
	if (poplevel != null)
	{
		mhssmallwin.poplevel = poplevel;
	}
}

//**********************************************
//	MHSNamedSmallPopup
//**********************************************
/*
*	Creates a popup window using the specified name as a suffix to the window name.
*	For example, a nameSuffix of fred would create a popup window named mhspopup_fred.
*/
//**********************************************

function MHSNamedSmallPopup(query, nameSuffix)
{
	var name = "mhspopup_" + nameSuffix;
	var width = 400;
	var height = 300;
	var position = MHSCenterPopup(height, width);
	var mhssmallwin = window.open(query, name, position + ',toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width='+width+',height='+height);
	if (mhssmallwin)
	{
		if (mhssmallwin.opener == null) mhssmallwin.opener = self;
		mhssmallwin.focus();
	}
}

//**********************************************
//	MHSCustomPopup
//**********************************************
/*
*	Creates a popup window using the specified name parametersas a suffix to the window name.
*	For example, a nameSuffix of fred would create a popup window named mhspopup_fred.
*/
//**********************************************

function MHSCustomPopup(query, nameSuffix, height, width, poplevel)
{
	var name = "mhspopup_" + nameSuffix;
    var position = MHSCenterPopup(height, width);
	var mhscustomwin = window.open(query, name, position + ',toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width='+width+',height='+height);
	if (mhscustomwin.opener == null) mhscustomwin.opener = self;
	mhscustomwin.focus();
    if (poplevel != null)
	{
		mhscustomwin.poplevel = poplevel;
	}
}

function MHSMediumPopup(query, poplevel, name)
{
	var width = 400;
	var height = 350;
	var position = MHSCenterPopup(height, width);
	if(arguments.length < 3)
	{
		name = 'mediumwin';
	}
	var mhsmediumwin = popWindow(query, name, position + ',toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no,width='+width+',height='+height);
	if (mhsmediumwin.opener == null) mhsmediumwin.opener = self;
	mhsmediumwin.focus();
    if (poplevel != null)
	{
		mhsmediumwin.poplevel = poplevel;
	}
}

function MHSSmallPopupFromOpener(query)
{
	if (top.opener != null && !top.opener.closed)
	{
		//alert("top.opener is valid = ["+top.opener+"]");
		top.opener.MHSSmallPopup(query);
	}
	else
	{
		MHSSmallPopup(query);
	}
}

function MHSLargePopupFromOpener(query)
{
	if (top.opener != null && !top.opener.closed)
	{
		//alert("top.opener is valid = ["+top.opener+"]");
		top.opener.MHSLargePopup(query);
	}
	else
	{
		MHSLargePopup(query);
	}
}

function MHSLargePopup(query, name)
{
	var width = 600;
	var height = 400;
	var position = MHSCenterPopup(height, width);
	if(arguments.length < 2)
	{
		name = 'largewin';
	}
	var mhslargewin = popWindow(query, name, position + ',toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no,width='+width+',height='+height);
	if (mhslargewin.opener == null) mhslargewin.opener = self;
	mhslargewin.focus();
}


function OtherPopup(query)
{
	var otherwin = window.open(UnescapeDQ(query), 'mhspopupotherwin');
	if (otherwin.opener == null) otherwin.opener = self;
	otherwin.focus();
}

function MHSQualityWizardPopup(query)
{
	var width = 800;
	var height = 465;
	//alert("qualityWizardWindowHeight=["+qualityWizardWindowHeight+"]\ntypeof qualityWizardWindowHeight = [" + typeof qualityWizardWindowHeight + "]");
	if (query == '_CDQualityCalculator.jsp')
	{
		height = 450;
	}
	//	Special kluydge to get the correct window size for the State Farm Quality Wizard.
	else if ("number" == typeof(qualityWizardWindowHeight) && null != qualityWizardWindowHeight)
	{
		height = qualityWizardWindowHeight;
	}


	var position = MHSCenterPopup(height, width);
	var features = 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=' + width + ',height='+ height + ',' + position;

	//	Do this stuff if page contains xtolform
	//alert("document=["+document+"]\ndocument.xtolform=["+document.xtolform+"]\ntypeof document.xtolform.nav = ["+typeof document.xtolform.nav+"]");
	if (document != null && document.xtolform != null && typeof document.xtolform.nav != "undefined")
	{
		var saveNav = document.xtolform.nav.value;
		var navObj = document.xtolform.nav;
		var formObj = document.xtolform;

		//	Open the window empty submit opener xtolform to popup window.
		var mhsqualitywin = popWindow("/xtol/blank.htm", 'qualitywizwin', features);

		//	redirect form
		navObj.value = 'QualityCalculator';
		if (query == '_CDQualityCalculator.jsp')
		{
			navObj.value = 'QualityCDCalculator';
		}
		formObj.target = mhsqualitywin.name;
		formObj.submit();
		formObj.target = "_top";
		navObj.value = saveNav;
	}
	else
	{
		//	Open the window with the requested query.
		mhsqualitywin = popWindow(query, 'qualitywizwin', features);
		if (mhsqualitywin.opener == null) mhsqualitywin.opener = self;
	}
	mhsqualitywin.focus();
}

function OpenTutorialPopupFromOpener(query)
{
	if (top.opener != null && !top.opener.closed)
	{
		top.opener.TutorialPopup(query);
	}
	else
	{
		TutorialPopup(query);
	}
}


function TutorialPopup(query)
{
	var width = 300;
	var height = 300;
	var position = MHSCenterPopup(height, width);
	var size = "width=" + width + ",height=" + height;
	var flashpopup = window.open(query, 'flashpopup', position + ',toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,' + size);
	if(flashpopup.opener == null)
		flashpopup.opener = self;

	flashpopup.focus();
}

function HTMLTutorialPopup(query)
{
	var width = 780;
	var height = 532;
	var position = MHSCenterPopup(height, width);
	var size = "width=" + width + ",height=" + height;
	var mhsflashpopup = window.open(query, 'mhspopuptutorialpopup', position + ',toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=yes,' + size);
	if(mhsflashpopup.opener == null)
		mhsflashpopup.opener = self;

	mhsflashpopup.focus();
}

function HTMLTutorialPopupFromOpener(query)
{
	var width = 780;
	var height = 532;
	var position = MHSCenterPopup(height, width);
	var size = "width=" + width + ",height=" + height;
	var mhsflashpopup = top.opener.open(query, 'mhspopuptutorialpopup', position + ',toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=yes,' + size);
	if(mhsflashpopup.opener == null)
		mhsflashpopup.opener = self;

	mhsflashpopup.focus();
}




function FlashPopup(filename)
{
	//alert("FlashPopup");
	var width = 650;
	var height = 375;
	var position = getWindowPosition(0, 0);
	var win = filename;
	var i = win.indexOf(".");
	if(i != -1)
	{
		win = win.substring(0, i);
	}
	win = win.replace(/-| /gi, "");
	filename = escape(filename);

	var loc= "ViewFlash.jsp?fn=" + filename;
	var flashpop = window.open(loc, win, position + ',width=' + width + ',height=' + height + ',menubar=no,resizable=yes');

	if (flashpop.opener == null) flashpop.opener = self;
	flashpop.focus();
//	flashpop.moveTo(0,0);
}

function CloseWindowAndForwardOpener(location)
{
	window.opener.location = location;
	self.close();

}//	end CloseWindowAndForwardOpener

function GeneralPopup(query)
{
	var win = window.open(query);
	if (win.opener == null) win.opener = self;
	win.focus();
}
/*
*   Saves the current value of the specified navHolder field from the specified form.
*   Sets the value of the specified navHolder field from the specified form to the value specified by the navigate param.
*   Opens a new window of the specified dimensions.
*   Sets the target of the specified form in the parent window to the new window then submits the form.
*   Resets the target of the specified form in the parent window.
*   Restors the in the value of the specified navHolder field from the specified form to it's original value.
*/
function ViewDetailPopup(navigate, form, navHolder, winHeight, winWidth, name)
{
	if (checkDelayedAction('ViewDetailPopup(\"'+navigate+'\",\"'+form+'\",\"'+navHolder+'\",\"'+winHeight+'\",\"'+winWidth+'\",\"'+name+'")'))
	{
		return;
	}

	var formObj = document.forms[form];
	var navObj = document.forms[form][navHolder];
	var saveNav = document.forms[form][navHolder].value;

	navObj.value = navigate;
	var position = MHSCenterPopup(winHeight, winWidth);

	var mhsdetailwin = popWindow("/xtol/blank.htm", ("detailwin_" + name), position + ",toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=yes,height=" + winHeight + ",width=" + winWidth);
	if (mhsdetailwin.opener == null) mhsdetailwin.opener = self;
	mhsdetailwin.focus();

	formObj.target = mhsdetailwin.name;
	formObj.submit();
	formObj.target = "_top";
	navObj.value = saveNav;
}


//******************************
// PICK DATE

function PickDate(form, field)
{
	var width = 385;
	var height = 280;
	var position = MHSCenterPopup(height, width);
	var nwquery = "CalendarServlet?frm=" + form + "&fld=" + field + "&dt=" + eval("document." + form + "." + field + ".value");
	var datewin = window.open(nwquery, "datewin", position + ",toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,width=" + width + ",height="+ height);
	if (datewin.opener == null) datewin.opener = self;
	datewin.focus();
}

//******************************
// PICK TODAYS DATE
function PickTodaysDate(form, field)
{
	var now = new Date();
	mm = now.getMonth() + 1;
	dd = now.getDate();
	yy = now.getFullYear();
	theForm = eval('document.'+ form);
	theForm[field].value= mm + '/' +  dd + '/' +  yy;
}

//******************************
// PICK PURCHASER

function PickPurchaser(form, field, field2, field3)
{
	var nwquery = "PurchaserServlet?frm=" + form + "&fld=" + field + "&fld2=" + field2 + "&fld3=" + field3;
	var width = 385;
	var height = 320;
	var position = MHSCenterPopup(height, width);
	var purchwin = window.open(nwquery, "mhspopuppurch", position + ",toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no,width=" + width + ",height="+ height);
	if (purchwin.opener == null) purchwin.opener = self;
	purchwin.focus();
}

//******************************

function isDisplayable(filename)
{
	var i	= filename.lastIndexOf(".");
	if (i == -1)
	{
		return false;
	}
	var ext = filename.substring(i,filename.length).toLowerCase();
	if (ext == ".gif" || ext == ".jpg" || ext == ".jpe" || ext == ".jpeg")
	{
		return true;
	}
	return false;
}


//******************************
//  Check Radio Button

function CheckRadioButton(form, element, index)
{
	eval("document." + form + "." + element + "[" + index + "]" + ".checked = true");
}

//******************************



//******************************
//  Submit Opener's Form

function SubmitOpenersForm(form)
{
	eval("window.opener.document." + form + ".submit()");
}

//******************************


//******************************
//  Change Opener's Location

function ChangeOpenersLocation(url)
{
	eval("window.opener.document." + form + ".submit()");
}

//******************************



//******************************
//  Toggle Check Box

function ToggleCheckbox(form, element)
{
	var elemType = eval("document." + form + "." + element + ".type");
	var elemObj = eval("document." + form + "." + element);

	if (eval("document." + form + "." + element + ".checked == true"))
	{
		if (!eval("document." + form + "." + element + ".type == 'radio'"))
		{
			eval("document." + form + "." + element + ".checked = false");
		}
	}
	else
	{
		eval("document." + form + "." + element + ".checked = true");
	}
	setExplicit(elemObj);
}

//******************************

function getTopLevelWindow()
{
	var topLevelObj = window.self;
	var backUpOnError;

	while(topLevelObj.parent != topLevelObj)
	{
//alert("while:"+	topLevelObj.name);
		try
		{
			backUpOnError = topLevelObj
			topLevelObj = topLevelObj.parent;
			var generateError = topLevelObj.name;
		}
		catch(oException)
		{
			return backUpOnError;
		}
	}
	return topLevelObj;
}

//******************************

    function handleLossofSession(url, reload)
	{
		if (isHelpIFrame(window))
		{
			window.parent.location = url;
			return;
		}
		else
		{
			//winName = top.name;
			topWindow = getTopLevelWindow();
			winName = topWindow.name;
			//alert("winName = " + winName);
			if (winName != null)
			{
				//	Check for MHS Popup window
				if(winName.indexOf("mhspopup") == 0)
				{
					if (typeof topWindow.poplevel != 'undefined')
					{
						var openerLevel = "top";
						var appendStr = ".opener";
						for (i = 0; i < poplevel; i++)
						{
							openerLevel += appendStr;
						}
	
						var curOpener = eval(openerLevel);
						curOpener.location = url;
	
						for (i = 0; i < poplevel; i++)
						{
							openerLevel = openerLevel.slice(0, openerLevel.length - appendStr.length);
							curOpener = eval(openerLevel);
							curOpener.close();
						}
					}
					else
					{
						topWindow.opener.location = url;
					}
					top.close();
					return;
				}
	
				//	Check for XactTotal popup
				if(winName.indexOf("xtpop") == 0)
				{
					topWindow.opener.location = url;
					top.close();
					return;
				}
			}
		}

		if(reload)
		{
			document.f.submit();
		}
		//top.location = url;
	}

//******************************


//******************************
//  Forward Popup or Main Window


    function ForwardPopupOrMain(PopupURL, MainURL)
	{
		var winName = window.name;
		var winPrefix = "";

		if (winName != null)
		{
			if (winName.length > 7)
			{
				winPrefix = winName.substr(0, 8);
				if(winPrefix == "mhspopup")
				{
					window.location = PopupURL;
					return;
				}
			}
		}

		window.location = MainURL;
	}

//******************************


//******************************
//  Unescape douple quotes

	function UnescapeDQ(str)
	{
		return str.replace(/~!~/gi, "\"");
	}

//******************************


//******************************
//  Check Supported Browser Type

	function isSupportedBrowser()
	{
		var version = parseFloat(navigator.appVersion);
		var browserUAString = navigator.userAgent;

		//  If browser is MS Internet Explorer
		if (browserUAString.indexOf("MSIE") != -1)
		{
			var msieVersion = browserUAString.slice(browserUAString.indexOf("MSIE ") + 5);
			if (parseFloat(msieVersion) >= 5.0)
			{
				return;
			}

			//	Get the actual MSIE version number rather than the number it reports in navigator.appVersion
			version = parseFloat(msieVersion);
		}
		alert("The browser you are using (" + navigator.appName + " " + version + ") is not supported by XactValue.com.\n\nXactValue.com supports Microsoft Internet Explorer 5.0 and higher.");
	}

    function isIE50()
    {
        var version = parseFloat(navigator.appVersion);
		var browserUAString = navigator.userAgent;

		//  If browser is MS Internet Explorer
		if (browserUAString.indexOf("MSIE") != -1)
		{
			var msieVersion = browserUAString.slice(browserUAString.indexOf("MSIE ") + 5);
			if (parseFloat(msieVersion) == 5.0)
				return true;
		}

        return false;
    }
//******************************


//******************************
//  ChangeBrowserNotifyOption

	function ChangeBrowserNotifyOption()
	{
		if (document.popunsupportedbrowser.UPUnsupportedBrowserPopSubmit.checked == true)
		{
			document.popunsupportedbrowser.submit();
		}
		else
		{
			window.close();
		}
		return;
	}

//******************************




//******************************
//  Strip non-numeric characters from a String

	function getOnlyDigits(val)
	{
		var newVal = "";
		for (i = 0; i < val.length; i++)
		{
			c = val.charAt(i);
			if (!isNaN(parseInt(c)))
			{
				newVal = newVal + c;
			}
		}
		return newVal;
	}
//******************************




//******************************
//  Format Phone Number Fields Dynamically
var areaCode  = false;
var areaCode2 = false;
var space     = false;
var areaCodeDash = false;
var dash	 =false;

	function dynamicPhoneFieldFormat(textField)
	{
//		alert("Field value before processing = [" + textField.value + "]");
		var origValue	= textField.value;
		var origLength	= origValue.length;
		var newValue	= "";
		var strippedVal	= "";
		var bogus		= false;
		var justNumbers	= true;
		var digitCount	= 0;
		//alert(origLength);
		if(origLength<6) space = false;
		if(origLength<5) areaCode2 = false;
		if(origLength<1) areaCode = false;
		if(!areaCode && origLength<4) dash = false;
		if(areaCode && origLength<10) areaCodeDash = false;
		//alert(origLength+' '+areaCode+' ' +areaCode2+' '+space);
		for (i = 0; i < origLength; i++)
		{
			c = origValue.charAt(i);
			if(i==0 && c=='(') areaCode = true;
			else if(i==0 && c!='(') areaCode = false;

			if(i==4 && c==')') areaCode2 = true;
			else if(i==4 && c!=')') areaCode2 = false;

			if(i==5 && c==' ') space = true;
			else if(i==5 && c!=' ')space == false;

			if(i==3 && c=='-' && !areaCode) dash = true;
			else if(i==3 && c!='-' && !areaCode) dash = false;

			if(i==9 && c=='-' && areaCode) areaCodeDash = true;
			else if(i==9 && c!='-' && areaCode) areaCodeDash = false;

			if (!isNaN(parseInt(c)))
			{
				digitCount = digitCount + 1;
				strippedVal = strippedVal + c;
			}
		}

		if (origLength > 0 && isBadPhoneChar(origValue.charAt(origLength-1)) || isBogusPhone(origValue))
		{
			bogus = true;
			alert("This field accepts only (xxx) xxx-xxx and xxx-xxxx formats for the phone number.");
		}
		newValue = strippedVal;
		//alert('before '+areaCode);
		//  Digits between 3 and 8
		if (digitCount == 3 && !dash && !areaCode)
		{
			newValue = newValue.substr(0, 3);
		}
		else if (digitCount == 3 && dash && !areaCode)
		{
			newValue = newValue.substr(0, 3) + "-";
		}
		else if (digitCount > 3 && digitCount < 8 && !areaCode)
		{
			newValue = newValue.substr(0, 3) + "-" + newValue.substr(3);
		}
		else if (digitCount > 3 && digitCount < 5 && areaCode)
		{
			newValue = "(" + newValue.substr(0, 3) + ") " + newValue.substr(3, 3);
		}
		else if (digitCount > 3 &&digitCount < 7 && areaCode && areaCodeDash)
		{
			newValue = "(" + newValue.substr(0, 3) + ") " + newValue.substr(3, 3) + "-";
		}
		else if (digitCount > 3 && digitCount < 7 && areaCode)
		{
			newValue = "(" + newValue.substr(0, 3) + ") " + newValue.substr(3, 3);
		}
		else if (digitCount > 3 && digitCount < 8 && areaCode)
		{
			newValue = "(" + newValue.substr(0, 3) + ") " + newValue.substr(3, 3) + "-" + newValue.substr(6);
		}
		else if (digitCount == 3 && areaCode && areaCode2 && space)
		{
			newValue = "(" + newValue.substr(0, 3) + ") ";
		}
		else if (digitCount == 3 && areaCode && areaCode2)
		{
			newValue = "(" + newValue.substr(0, 3) + ")";
		}
		else if (digitCount <= 3 && areaCode)
		{
			//alert('here');
			newValue = "(" + newValue.substr(0, 3);
		}
		else if (digitCount > 7)
		{
			newValue = "(" + newValue.substr(0, 3) + ") " + newValue.substr(3, 3) + "-" + newValue.substr(6);
		}
		//else alert('did not make it anywhere! '+ digitCount+' '+areaCode);
		textField.value = newValue;
//		textField.focus();
//		textField.select();
		return;
	}

//******************************

//******************************
//  isBogusPhone

	function isBadPhoneChar(c)
	{
		if (isNaN(parseInt(c)) && c != '(' && c != ')' && c != '-' && c != ' ')
		{
			return true;
		}
		return false;
	}
	function isBogusPhone(str)
	{
		var bogus = false;
		if (str.length == 0)
		{
			return bogus;
		}

		for (i = 0; i < str.length; i++)
		{
			c = str.charAt(i);
			if (isNaN(parseInt(c)))
			{
				switch(c)
				{
					case "(":
					{
						if (i != 0)
						{
							bogus = true;
						}
						break;
					}
					case ")":
					{
						if (i != 4)
						{
							bogus = true;
						}
						break;
					}
					case " ":
					{
						if (i != 5)
						{
							bogus = true;
						}
						break;
					}
					case "-":
					{
						if (i != 3 && i != 9)
						{
							bogus = true;
						}
						break;
					}
					default:
					{
						bogus = true;
						break;
					}
				}
			}
		}
		return bogus;
	}
//******************************


//******************************
//  Auto Jump to the Next Field

	function fieldAutoJump(formName, thisField, maxChars, nextFieldName)
	{
		if (thisField.value.length >= maxChars)
		{
			thisField.value = (thisField.value.substr(0, maxChars));
			eval("document." + formName + "." + nextFieldName + ".focus()");
			eval("document." + formName + "." + nextFieldName + ".select()");
		}
	}
//******************************

//******************************

	function syncParent(obj, parentFormName)
	{
		if (window.opener != null && !window.opener.closed)
		{
			if (window.opener.document != null)
			{
				if (eval("window.opener.document." + parentFormName) != null)
				{
					if(typeof eval("window.opener.document." + parentFormName + "." + obj.name) != "undefined")
					{
						parentSelectObj = eval("window.opener.document." + parentFormName + "." + obj.name);
						for (i = 0; i < parentSelectObj.length; i++)
						{
							if (parentSelectObj.options[i].value == obj.value)
							{
								if (obj.checked)
								{
									parentSelectObj.options[i].selected=true;
								}
								else
								{
									parentSelectObj.options[i].selected=false;
								}

							}
						}
                        if(parentSelectObj.onchange) parentSelectObj.onchange();
					}
				}
			}
		}
	}

//******************************

//******************************

	function isFormElementInOpener(objName, formName)
	{
		if (top.opener != null && !top.opener.closed)
		{
			if (top.opener.document != null)
			{
				if (eval("top.opener.document." + formName) != null)
				{
					if(typeof eval("top.opener.document." + formName + "." + objName) != "undefined")
					{
						return true;
					}
				}
			}
		}
		return false;
	}

//******************************

//******************************

	function isFormElementInDocument(objName, formName)
	{
		if (top.document != null)
		{
			if (eval("top.document." + formName) != null)
			{
				if(typeof eval("top.document." + formName + "." + objName) != "undefined")
				{
					return true;
				}
			}
		}
		return false;
	}

//******************************

//******************************

	function syncValWithParent(obj, parentFormName)
	{
		if (window.opener != null && !window.opener.closed)
		{
			if (window.opener.document != null)
			{
				if (eval("window.opener.document." + parentFormName) != null)
				{
					if(typeof eval("window.opener.document." + parentFormName + "." + obj.name) != "undefined")
					{
						parentObj = eval("window.opener.document." + parentFormName + "." + obj.name);
						obj.value = parentObj.value;
					}
				}
			}
		}
	}

//*************************
// This one is used by foundation type and wall material popups
// to change the opener (worksheet) page.
function addParentDivRows(linknum, group, count, roomId, isMulti)
{
	eval('array_max = window.opener.'+group+'_COMBO_MAX');
	eval('window.opener.'+group+'_COMBO_LENGTH += '+count);
	eval('array_size = window.opener.'+group+'_COMBO_LENGTH');

	if (array_size > array_max)
	{
		eval('window.opener.'+group+'_COMBO_LENGTH = '+array_max);
		array_size = array_max;
	}

	for (i =0; i<array_size; i++)
	{
		var id = ""+group+""+i;
		changeParentToShow(id);
	}

	for (i =1; i<=array_max; i++)
	{
		id = "ADDLINK_"+group+""+i;
		addelement = window.opener.document.getElementById(id);
		if (addelement != null)
		{
			if (i == array_size && array_size != array_max)
			{
				changeParentToShow(id);
			}
			else
			{
				changeParentToHide(id);
			}
		}
	}
}

//******************************

//******************************
//  getMSIEVersionNumber
//******************************
//  Get the version number of MSIE Browser.
//	If the browser is not MSIE, returns -1
//	Otherwise returns the version as a float.

	function getMSIEVersionNumber()
	{
		var previousString	= "MSIE ";
		var trailingString	= ";";
		var appString		= "Microsoft";

		if (navigator.appName.indexOf(appString) == -1)
		{
			return -1;
		}

		var versionString = navigator.appVersion;
		var begin = previousString.length + versionString.indexOf(previousString);
		var end = versionString.indexOf(trailingString, begin);
		versionString = versionString.substring(begin, end);
		return parseFloat(versionString);
	}
//******************************

//******************************
//  setSelect - Fix - Test This
//******************************
//  Set the value of the specified select
//	input object if it matches the specified value.
//	Otherwise, do nothing. Does nothing if either
//	specified object or value is null.

	function setSelect(selectObj, value)
	{
		if (		value == null
				||	typeof selectedObj == "undefined"
				||	selectedObj == null
				||	value == ""
				||	value.length < 1)
		{
			//alert("selectOjb = ["+ selectedObj +"]\nvalue = ["+value+"]");
			return;
		}
		else
		{
			//alert("selectOjb = ["+ selectedObj +"]\nvalue = ["+value+"]");
			for (var i = 0; i < selectObj.options.length; i++)
			{
				if (selectObj.options[i].value == value)
				{
					selectObj.selectedIndex = i;
					break;
				}
			}
		}
	}
//******************************

//******************************
//  returnTrue
//******************************
//  This function exactly as the
//	declaration suggests. It simply
//	returns true. It is designed to
//	supress the browser error window
//	for a know javascript error that
//	we expect and plan to do nothing about.

	function returnTrue(message, url, line)
	{
		return true;
	}

//******************************


//******************************
//  showError - For Debugging
//******************************
//  This function is used to show
//	what is sent to the error handler.
//	Use this method by assigning it
//	as the error handler, then viewing
//	the alert box that is generated.

	function showError(message, url, line)
	{
		alert("message = ["+message+"]\nURL = ["+url+"]\nline number = ["+line+"]");
		return;
	}

//******************************

//******************************
//	openNamedFromOpener
//******************************
//	This function will open a popup
//	window from the opener page if it
//	is not null and not closed. Otherwise,
//	it will open the window from the current
//	window. It uses the MHSNamedNoScrollSizablePopup
//	function to open the window.

function openNamedFromOpener(query, height, width, name)
{
	//alert("top.opener = ["+top.opener+"]");
	//alert("top.opener.closed = ["+top.opener.closed+"]");
	if (top.opener != null && !top.opener.closed)
	{
		//alert("top.opener is valid = ["+top.opener+"]");
		top.opener.MHSNamedNoScrollSizablePopup(query, height, width, name);
	}
	else
	{
		//alert("top.opener NOT valid");
		MHSNamedNoScrollSizablePopup(query, height, width, name);
	}
}
//******************************
//	openFromOpener
//******************************
//	This function will open a popup
//	window from the opener page if it
//	is not null and not closed. Otherwise,
//	it will open the window from the current
//	window. It uses the MHSNoScrollSizablePopup
//	function to open the window.

function openFromOpener(query, height, width)
{
	//alert("top.opener = ["+top.opener+"]");
	//alert("top.opener.closed = ["+top.opener.closed+"]");
	if (top.opener != null && !top.opener.closed)
	{
		//alert("top.opener is valid = ["+top.opener+"]");
		top.opener.MHSNoScrollSizablePopup(query, height, width);
	}
	else
	{
		//alert("top.opener NOT valid");
		MHSNoScrollSizablePopup(query, height, width);
	}
}
//******************************
//******************************
//	openViewFromOpener
//******************************
//	This function will open a popup
//	window from the opener page with
//	ViewDetailPopup if it
//	is not null and not closed. Otherwise,
//	it will open the window from the current
//	window using the MHSNamedNoScrollSizablePopup
//	function.

function openViewFromOpener(query, navigate, form, navHolder, winHeight, winWidth, name)
{
	if (	top.opener != null &&
			!top.opener.closed)
	{
		var interviewPage = "";
		if (navigate == "FoundationType"){interviewPage = "Foundation";}
		if (navigate == "WallMaterials"){interviewPage = "Rooms";}

		if (top.opener.document != null &&
			eval("top.opener.document." + form) != null &&
			typeof eval("top.opener.document." + form + ".curpage") != "undefined" &&
					(	eval("top.opener.document." + form + ".curpage.value") == interviewPage ||
						eval("top.opener.document." + form + ".curpage.value") == "Worksheet"		)	)
		{
			top.opener.ViewDetailPopup(navigate, form, navHolder, winHeight, winWidth, name);
			return;
		}
		else
		{
			top.opener.MHSNamedNoScrollSizablePopup(query, winHeight, winWidth, ("mhspopupdetailwin_" + name));
			return;
		}
	}

	//	Default case
	MHSNamedNoScrollSizablePopup(query, winHeight, winWidth, ("mhspopupdetailwin_" + name));
}
//******************************

//******************************
//	setSelectedIndexByValue
//******************************
//	This function will allow you to
//	set the selected index of a select
//	object in a form simply by specifying
//	the value of the selected option.
//	If that value is not found among the
//	options of the specified select object,
//	nothing is done.

function setSelectedIndexByValue(selectObj, val)
{
	//alert("in setSelectedIndexByValue val = ["+val+"]");
	for (i = 0; i < selectObj.options.length; i++)
	{
		if (selectObj.options[i].value == val)
		{
			selectObj.selectedIndex = i;
			return;
		}
	}
}

function isInteger(s)
{
    var i;
    for (i = 0; i < s.length; i++)
    {
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9")))
            return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag)
{
    var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++)
    {
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1)
            returnString += c;
    }

    return returnString;
}

function daysInFebruary(year)
{
    // February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}

function DaysArray(n)
{
    for (var i = 1; i <= n; i++)
    {
        this[i] = 31;
        if (i == 4 || i == 6 || i == 9 || i == 11)
        {
            this[i] = 30;
        }

        if (i == 2)
        {
            this[i] = 29;
        }
    }
    return this;
}


var dtCh = "/";
var minYear = 1900;
var maxYear = 2100;

function isDate(dtStr)
{
    var daysInMonth = DaysArray(12);
    var pos1 = dtStr.indexOf(dtCh);
    var pos2 = dtStr.indexOf(dtCh, pos1 + 1);
    var strMonth = dtStr.substring(0, pos1);
    var strDay = dtStr.substring(pos1 + 1, pos2);
    var strYear = dtStr.substring(pos2 + 1);
    strYr = strYear;

    if(strDay.charAt(0) == "0" && strDay.length > 1)
        strDay = strDay.substring(1);

    if(strMonth.charAt(0) == "0" && strMonth.length > 1)
        strMonth = strMonth.substring(1);

    for(var i=1; i<=3; i++)
    {
        if (strYr.charAt(0) == "0" && strYr.length > 1)
            strYr = strYr.substring(1);
    }

    month = parseInt(strMonth);
    day = parseInt(strDay);
    year = parseInt(strYr);

    if(pos1 == -1 || pos2 == -1)
    {
    	alert("The date format should be : mm/dd/yyyy");
    	return false;
    }

    if(strMonth.length < 1 || month < 1 || month > 12)
    {
        alert("Please enter a valid month");
   		return false;
   	}

   	if(strDay.length < 1 || day < 1 || day > 31 || (month == 2 && day > daysInFebruary(year)) || day > daysInMonth[month])
    {
   		alert("Please enter a valid day");
   		return false;
   	}

   	if(strYear.length != 4 || year == 0 || year < minYear || year > maxYear)
    {
        alert("Please enter a valid 4 digit year between " + minYear + " and " + maxYear);
   		return false;
   	}

    if (dtStr.indexOf(dtCh, pos2 + 1) != -1 || isInteger(stripCharsInBag(dtStr, dtCh)) == false)
    {
        alert("Please enter a valid date");
        return false;
   	}

    return true;
}

// One object tracks the current modal dialog opened from this window.
var dialogWin = new Object();

// Generate a modal dialog.
// Parameters:
// url -- URL of the page/frameset to be loaded into dialog
// width -- pixel width of the dialog window
// height -- pixel height of the dialog window
// returnFunc -- reference to the function (on this page)
// that is to act on the data returned from the dialog
// args -- [optional] any data you need to pass to the dialog
function openDialog(url, width, height, returnFunc, args)
{
	if (!dialogWin.win || (dialogWin.win && dialogWin.win.closed))
	{
		// Initialize properties of the modal dialog object.
		dialogWin.returnFunc = returnFunc
		dialogWin.returnedValue = ""
		dialogWin.args = args
		dialogWin.url = url
		dialogWin.width = width
		dialogWin.height = height
		// Keep name unique so Navigator doesn't overwrite an existing dialog.
		dialogWin.name = "mhspopup" + (new Date()).getSeconds().toString()
		// Assemble window attributes and try to center the dialog.

			// The best we can do is center in screen.
			dialogWin.left = (screen.width - dialogWin.width) / 2
			dialogWin.top = (screen.height - dialogWin.height) / 2
			var attr = "left=" + dialogWin.left + ",top=" + dialogWin.top + ",resizable=no,width=" + dialogWin.width + ",height=" + dialogWin.height

		// Generate the dialog and make sure it has focus.
		dialogWin.win=window.open(dialogWin.url, dialogWin.name, attr)
		dialogWin.win.focus()
	}
	else
	{
		dialogWin.win.focus()
	}
}
// Event handler to inhibit Navigator form element
// and IE link activity when dialog window is active.
function deadend()
{
	if (dialogWin.win && !dialogWin.win.closed)
	{
		dialogWin.win.focus() ;
		return false ;
	}
	return true;
}

// Since links in IE4 cannot be disabled, preserve
// IE link onclick event handlers while they're "disabled."
// Restore when re-enabling the main window. var IELinkClicks
// Disable form elements and links in all frames for IE.
function disableForms()
{
	IELinkClicks = new Array() ;
	for (var h = 0; h < frames.length; h++)
	{
		for (var i = 0; i < frames[h].document.forms.length; i++)
		{
			for (var j = 0; j < frames[h].document.forms[i].elements.length; j++)
			{
				frames[h].document.forms[i].elements[j].disabled = true ;
			}
		}
		IELinkClicks[h] = new Array() ;
		for (i = 0; i < frames[h].document.links.length; i++)
		{
			IELinkClicks[h][i] = frames[h].document.links[i].onclick;
			frames[h].document.links[i].onclick = deadend ;
		}
	}
}

// Restore IE form elements and links to normal behavior.
function enableForms()
{
	for (var h = 0; h < frames.length; h++)
	{
		for (var i = 0; i < frames[h].document.forms.length; i++)
		{
			for (var j = 0; j < frames[h].document.forms[i].elements.length; j++)
			{
				frames[h].document.forms[i].elements[j].disabled = false ;
			}
		}
		for (i = 0; i < frames[h].document.links.length; i++)
		{
			frames[h].document.links[i].onclick = IELinkClicks[h][i] ;
		}
	}
}

// Grab all Navigator events that might get through to form
// elements while dialog is open. For IE, disable form elements.
function blockEvents()
{
		disableForms() ;
		window.onfocus = checkModal ;
}

// As dialog closes, restore the main window's original
// event mechanisms.
function unblockEvents()
{
		enableForms() ;
}

// Invoked by onFocus event handler of EVERY frame,
// return focus to dialog window if it's open.
function checkModal()
{
	setTimeout("finishChecking()", 50);
	return true;
}

function finishChecking()
{
	if (dialogWin.win && !dialogWin.win.closed)
	{
		dialogWin.win.focus() ;
	}
}

function saveAssignToOpener(assignToUserNumber, userName, formElementName)
{
	//alert("In scripts.js saveAssignToOpener: formElementName=["+formElementName+"]");
	if (formElementName != null)
	{
		//alert("In scripts.js saveAssignToOpener: formElementName=["+formElementName+"]");
		//alert("opener.document.xtolform["+formElementName+"].value = ["+opener.document.xtolform[''+formElementName].value+"]");
		opener.document.xtolform[''+formElementName].value = assignToUserNumber;
	}
	else
	{
		opener.document.xtolform.XT_USER_USER_SELECT.value = assignToUserNumber;
	}

	// ID used below must match BnValuationOwner.ASSIGN_TO_ELEMENT_ID value
	//alert("opener.document.getElementById('AssignToTDID') = ["+opener.document.getElementById("AssignToTDID")+"]\nnode type=["+opener.document.getElementById("AssignToTDID").nodeType+"]")
	//alert("opener.document.getElementById('AssignToTDID').firstChild = ["+opener.document.getElementById("AssignToTDID").firstChild+"]\nnode type=["+opener.document.getElementById("AssignToTDID").firstChild.nodeType+"]")
	opener.document.getElementById("AssignToTDID").firstChild.nodeValue = userName;
}


function setAssignTo(assignToUserNumber, userName, formElementName)
{
	if (formElementName != null && formElementName.length > 0)
	{
		if (typeof(document.xtolform[''+formElementName]) != 'undefined')
		{
			document.xtolform[''+formElementName].value = assignToUserNumber;
		}
	}
	else
	{
		if (typeof(document.xtolform['XT_USER_USER_SELECT']) != 'undefined')
		{
			document.xtolform.XT_USER_USER_SELECT.value = assignToUserNumber;
		}
	}

	// ID used below must match BnValuationOwner.ASSIGN_TO_ELEMENT_ID value
	if (	document.getElementById("AssignToTDID") != null
		&&	document.getElementById("AssignToTDID").firstChild != null	)
	{
		document.getElementById("AssignToTDID").firstChild.nodeValue = userName;
	}
}

function isChecked(id)
{
	var obj = document.xtolform[id];
	return (typeof obj != 'undefined' && obj != null && typeof obj.checked != 'undefined' && obj.checked)
}

function isOverrideStyle(style)
{
    if(style == "XT_STRUCT_STYLE_PERCENT0" ||
       style == "XT_STRUCT_STYLE_PERCENT1" ||
       style == "XT_STRUCT_STYLE_PERCENT2" ||
       style == "XT_STRUCT_STYLE_PERCENT11")
        return false;
    else
        return true;
}


function isCondoStyle(style)
{
	if (style == "XT_STRUCT_STYLE_PERCENT11")
	{
		return true;
	}
	else
	{
		return false;
	}
}

function doCondoChangesForGeneralInfo(convertToCondo)
{
	if (convertToCondo)
	{
		changeToHide("structStyleQuestion");
		changeToHide("structPurposeQuestion");
		changeToHide("additionslink");
		changeToHide("xtHalfStory");

	}
	else
	{
		changeToShowTR("structStyleQuestion");
		changeToShowTR("structPurposeQuestion");
		changeToShowTR("additionslink");
		initHalfStory();
	}
}

function doCondoChangesForQualityQuestion(convertToCondo)
{
	var qual = document.xtolform["XT_STRUCT_QUALITY"];
	var link = document.getElementById("openQualityWizardAnchor");
	//alert("link href = ["+link.href+"]")
	if (qual != null)
	{
		if (convertToCondo)
		{
			qual.options[0].text = "";
			link.href = "javascript:MHSQualityWizardPopup('_CDQualityCalculator.jsp');";
			if (document.xtolform.curpage.value == 'Worksheet')
			{
				link.href = "javascript:qualityWizardPopup('_CDQualityCalculator.jsp');";
			}
			changeToHide("qualityResOptionalMarker");
			changeToShowTR("qualityResRequiredMarker");
		}
		else
		{
			qual.options[0].text = "Unknown";
			link.href = "javascript:MHSQualityWizardPopup('_QualityCalculator.jsp');";
			if (document.xtolform.curpage.value == 'Worksheet')
			{
				link.href = "javascript:qualityWizardPopup('_QualityCalculator.jsp');";
			}
			changeToHide("qualityResRequiredMarker");
			changeToShowTR("qualityResOptionalMarker");
		}
	}
}

function doCondoChangesForAttached(convertToCondo)
{
	var garageSpacer = document.getElementById("garagecondospacing");
	var spacerSize = "4%";
	if (garageSpacer != null)
	{
		garageSpacer.style.width = (convertToCondo)? spacerSize : "0";
	}

	var oasSpacer = document.getElementById("oascondospacing");
	if (oasSpacer != null)
	{
		oasSpacer.style.width = (convertToCondo)? spacerSize : "0";
	}

	if (convertToCondo)
	{

		changeToShowTR("ifgcondoquestion");
		doIFGActualCondoQuestions();
		changeToShowTR("oascondoquestion");
		doOASActualCondoQuestions();
		changeToHide("detachedstructureslink");

		// Hide Covered questions for decks and porches
		for (var i=0; i<9; i++)
		{
			var garageStyle = document.xtolform["XT_GARAGE_STYLE"+i];
			if (typeof garageStyle != 'undefined')
			{
				if (garageStyle.selectedIndex == 2)
				{
					// Carports don't exist in condo's so blow them away if they change it to a condo
					garageStyle.selectedIndex = 0;
					document.xtolform["XT_GARAGE_CARS"+i].selectedIndex = 0;
					changeToHide("GARAGE_DETAILS_"+i);
					changeToHide("GARAGE_LIVING_ABOVE_"+i);
					removeExplicitColor("XT_GARAGE_STYLE"+i);
					removeFromExplicitList("XT_GARAGE_STYLE"+i);
					removeExplicitColor("XT_GARAGE_CARS"+i);
					removeFromExplicitList("XT_GARAGE_CARS"+i);
				}
				garageStyle.remove(2);
				changeToHide("deckcovered"+i);
				changeToHide("porchcovered"+i);
			}
			else
			{
				break;
			}
		}
	}
	else
	{
		changeToHide("ifgcondoquestion");
		changeToShowTR("ifgactualcondoquestion");
		changeToHide("oascondoquestion");
		changeToShowTR("oasactualcondoquestions");
		changeToShowTR("detachedstructureslink");

		// Show Covered questions for decks and porches and remove carport option
		for (var i=0; i<9; i++)
		{
			var garageStyle = document.xtolform["XT_GARAGE_STYLE"+i];
			if (typeof garageStyle != 'undefined')
			{
				if(garageStyle.options.length < 3)
				{
					var addCarport = new Option("Carport","2", false, false);
					garageStyle.add(addCarport, 2);
				}
			}
			changeToShow("deckcovered"+i, "inline");
			changeToShow("porchcovered"+i, "inline");
		}
	}

	for (var i=0; i<9; i++)
	{
		if (typeof document.xtolform["XT_GARAGE_STYLE"+i] != 'undefined')
		{
			checkForLivingSpace(document.xtolform["XT_GARAGE_STYLE"+i], "GARAGE_LIVING_ABOVE_"+i, false);
		}
	}
}

function doIFGActualCondoQuestions()
{
	if (isChecked("CBOX_XT_GLOBAL_CDQ_GF"))
	{
		changeToShowTR("ifgactualcondoquestion");
	}
	else
	{
		changeToHide("ifgactualcondoquestion");
	}
}

function doOASActualCondoQuestions()
{
	if (isChecked("CBOX_XT_GLOBAL_CDQ_OAS"))
	{
		changeToShowTR("oasactualcondoquestions");
	}
	else
	{
		changeToHide("oasactualcondoquestions");
	}
}

function doExteriorFeaturesLink()
{
	if (!isChecked("CBOX_XT_GLOBAL_CDQ_ED") && !isChecked("CBOX_XT_GLOBAL_CDQ_W"))
	{
		changeToHide("exteriorfeatureslink");
	}
	else
	{
		changeToShowTR("exteriorfeatureslink");
	}
}

function doCondoChangesForInterior(convertToCondo)
{
	if (convertToCondo)
	{
		changeToShowTR("includeiwmquestion");
		changeToShowTR("includelfandidmquestions");
		doInteriorWMQuestion();
		//doInteriorFeaturesLink();
	}
	else
	{
		changeToHide("includeiwmquestion");
		changeToHide("includelfandidmquestions");
		changeToShowTR("interiorwmquestion");
		changeToShowTR("interiorfeatureslink");
	}
}
function doInteriorWMQuestion()
{
	if (isChecked("CBOX_XT_GLOBAL_CDQ_IWM"))
	{
		changeToShowTR("interiorwmquestion");
	}
	else
	{
		changeToHide("interiorwmquestion");
	}
}
function doInteriorFeaturesLink()
{
	if (!isChecked("CBOX_XT_GLOBAL_CDQ_LF") && !isChecked("CBOX_XT_GLOBAL_CDQ_ID_IT"))
	{
		changeToHide("interiorfeatureslink");
	}
	else
	{
		changeToShowTR("interiorfeatureslink");
	}
}

function doCondoChangesForKeyRooms(convertToCondo)
{
	if (convertToCondo)
	{
		changeToShowTR("keyroomcondoquestions");
	}
	else
	{
		changeToHide("keyroomcondoquestions");
	}
}

function doCondoChangesForSystems(convertToCondo)
{
	if (convertToCondo)
	{
		changeToShowTR("systemscondoquestions");
	}
	else
	{
		changeToHide("systemscondoquestions");
	}
}


//******************************


//******************************

function engineAboveGradeSF(
		foundation,
		profile,
		baseFinPerc,
		halfStoryFinPerc,
		totalFinishedSF)
{
	/*
	* This function must match the method of the same name in ResidentialWidget.java (HENCE SOME OF THE UNORTHODOX CODE)
	* which was built to duplicate the function used in the engine.
	*
	*	Parameters:
	*	foundation: The ID of the foundation type specified in the QWIZ.
	*	profile: The ID of the home profile (number of stories) specified in the QWIZ.
	*	baseFinPerc: The percentage of the level that is below grade level that is finished.
	*	halfStoryFinPerc: The percentage of the half level (bonus room in attic) that is finished. For homes
	*			where there is no half level, enter 0.
	*	totalFinishedSF: The number of total finished square feet in the structure (i.e. XT_USER_TOTAL_SF).
	*
	*/
	var log = false;
	var retVal = 0;

	//	Get values from widget
	var basementId			= "XT_FOUND_CONST_PERCENT0";
	var sBasementId			= "XT_FOUND_CONST_PERCENT6";
	var slabId				= "XT_FOUND_CONST_PERCENT1";
	var crawlId				= "XT_FOUND_CONST_PERCENT2";
	var pierId				= "XT_FOUND_CONST_PERCENT3";
	var postId				= "XT_FOUND_CONST_PERCENT4";
	var sweepStiltsId		= "XT_FOUND_CONST_PERCENT5";

	var fndBasePerc			= 0;
	var fndSBasePerc		= 0;
	var fndSlabPerc			= 0;
	var fndCrawlPerc		= 0;
	var fndPierPerc			= 0;
	var fndPostPerc			= 0;
	var fndSweepStiltsPerc	= 0;

	switch(foundation)
	{
		case basementId:
			fndBasePerc = 100.0;
			break;
		case sBasementId:
			fndSBasePerc = 100.0;
			break;
		case slabId:
			fndSlabPerc = 100.0;
			break;
		case crawlId:
			fndCrawlPerc = 100.0;
			break;
		case pierId:
			fndPierPerc = 100.0;
			break;
		case postId:
			fndPostPerc = 100.0;
			break;
		case sweepStiltsId:
			fndSweepStiltsPerc = 100.0;
			break;
	}

	var p_1_Story			= "XT_STRUCT_TYPE_PERCENT0";
	var p_1_5_Story			= "XT_STRUCT_TYPE_PERCENT1";
	var p_2_Story			= "XT_STRUCT_TYPE_PERCENT2";
	var p_2_5_Story			= "XT_STRUCT_TYPE_PERCENT3";
	var p_3_Story			= "XT_STRUCT_TYPE_PERCENT4";
	var p_3_5_Story			= "XT_STRUCT_TYPE_PERCENT8";
	var p_4_Story			= "XT_STRUCT_TYPE_PERCENT9";
	var p_biLevel			= "XT_STRUCT_TYPE_PERCENT5";
	var p_triLevel			= "XT_STRUCT_TYPE_PERCENT6";
	var p_4LevelSplit		= "XT_STRUCT_TYPE_PERCENT7";


	var p_1_StoryFrac		= 0;
	var p_1_5_StoryFrac		= 0;
	var p_2_StoryFrac		= 0;
	var p_2_5_StoryFrac		= 0;
	var p_3_StoryFrac		= 0;
	var p_3_5_StoryFrac		= 0;
	var p_4_StoryFrac		= 0;
	var p_biLevelFrac		= 0;
	var p_triLevelFrac		= 0;
	var p_4LevelSplitFrac	= 0;

	switch(profile)
	{
		case p_1_Story:
			p_1_StoryFrac = 1.0;
			break;
		case p_1_5_Story:
			p_1_5_StoryFrac = 1.0;
			break;
		case p_2_Story:
			p_2_StoryFrac = 1.0;
			break;
		case p_2_5_Story:
			p_2_5_StoryFrac = 1.0;
			break;
		case p_3_Story:
			p_3_StoryFrac = 1.0;
			break;
		case p_3_5_Story:
			p_3_5_StoryFrac = 1.0;
			break;
		case p_4_Story:
			p_4_StoryFrac = 1.0;
			break;
		case p_biLevel:
			p_biLevelFrac = 1.0;
			break;
		case p_triLevel:
			p_triLevelFrac = 1.0;
			break;
		case p_4LevelSplit:
			p_4LevelSplitFrac = 1.0;
			break;
		default:
			p_1_StoryFrac = 1.0;
			break;
	}


	var baseFinFrac			= baseFinPerc / 100.0;

	if (baseFinFrac == 0)
	{
		if (log)
		{
			alert("The basement finished fraction = 0. Therefore all the finished SF [" + totalFinishedSF + "] is above grade.");
		}

		//it's all above grade, just return it.  This prevents the rounding problems we were getting.
		return totalFinishedSF;
	}

	var halfStoryFinFrac		= halfStoryFinPerc / 100.0;

	var baseFrac = (fndBasePerc / 100.0) + (fndSBasePerc / 100.0);

	//	Force bottom level of bi-level to be basement.
	if (p_biLevelFrac > 0.0)
	{
		//	This should always total 1.0
		baseFrac = (	(fndBasePerc / 100.0)
					+	(fndSlabPerc / 100.0)
					+	(fndCrawlPerc / 100.0)
					+	(fndPierPerc / 100.0)
					+	(fndPostPerc / 100.0)
					+	(fndSweepStiltsPerc / 100.0)
					+	(fndSBasePerc / 100.0)			);
	}

	//	My guess is that tmpValue is some estimate at the number of equal area floors.
	var tmpValue =	p_biLevelFrac
					+	p_1_StoryFrac
					+	p_triLevelFrac
					+	p_1_5_StoryFrac
					+	p_4LevelSplitFrac * 1.5
					+	(p_2_StoryFrac + p_2_5_StoryFrac) * 2.0
					+	(p_3_StoryFrac + p_3_5_StoryFrac) * 3.0
					+	(p_4_StoryFrac) * 4.0
					+	(baseFrac * baseFinFrac)
					+	((p_1_5_StoryFrac + p_2_5_StoryFrac + p_3_5_StoryFrac) * halfStoryFinFrac * .75);

	//	Estimate the number of SF per standard floor.
	tmpValue = totalFinishedSF / tmpValue;

	//	Now estimating the number of SF for each floor of the home.
	var floor_1_SF	= Math.round(tmpValue);
	var floor_2_SF	= Math.round(tmpValue * (p_2_StoryFrac + p_2_5_StoryFrac + p_3_StoryFrac + (0.5 * p_4LevelSplitFrac)));
	var floor_3_SF	= Math.round(tmpValue * (p_3_StoryFrac + p_3_5_StoryFrac + p_4_StoryFrac));
	var floor_4_SF	= Math.round(tmpValue * p_4_StoryFrac);
	var attic_SF	= Math.round(tmpValue * (p_1_5_StoryFrac + p_2_5_StoryFrac + p_3_5_StoryFrac) * halfStoryFinFrac * 0.75);
	var basement_SF	= 0;
	if (baseFinFrac > 0.0)
	{
		basement_SF = Math.round(totalFinishedSF - (floor_1_SF + floor_2_SF + floor_3_SF + floor_4_SF + attic_SF));
	}

	//	Here they appear to be saving all the data they figured. So we'll save the data we want and return it.
	retVal = floor_1_SF + floor_2_SF + floor_3_SF + floor_4_SF + attic_SF;


	//	Log results
	if (log)
	{
		alert(	"\n  1st Floor SF = ["+floor_1_SF+"]"
			+	"\n  2nd Floor SF = ["+floor_2_SF+"]"
			+	"\n  3rd Floor SF = ["+floor_3_SF+"]"
			+	"\n  Attic Fin SF = ["+attic_SF+"]"
			+	"\n  Basement  SF = ["+basement_SF+"]"
			+	"\n AboveGrade SF = ["+retVal+"]");
	}

	return retVal;


}//******************************












var lastItem = 0;
function occupancyValidityCheck(obj, allowBlank)
{
	// Secondary Occupancies are allowed to be blank
	if (allowBlank && obj.selectedIndex == 0)
	{
		return;
	}
	// See if there is a BLANK at the end...this means its an invalid occupancy
	if(obj.value.substring(obj.value.length-5) != "BLANK")
    {
        lastItem = obj.selectedIndex;
    }
    else
    {
        var loc = obj.selectedIndex;
        var extendedString = obj.value;

        if(loc < 2)
        {
            obj.selectedIndex = 2;
        }

        if(loc > lastItem) //going down
        {
            occupancyGoDown(obj);
        }
        else if(loc < lastItem) //going up
        {
            occupancyGoUp(obj);
        }
        occupancyValidityCheck(obj);
    }
}

function occupancyGoDown(obj)
{
	var i;
    var loc = obj.selectedIndex;
    var max = obj.length;
	for(i = loc; i < max; i++)
    {
    	obj.selectedIndex = i;
    	if(getBlank(obj.value) != "BLANK")
    	{
    		lastItem = i;
			i = max;
    	}
    }
}

function occupancyGoUp(obj)
{
	var i;
    var loc = obj.selectedIndex;
    var max = obj.length;
	for(i = loc; i > 0; i--)
    {
    	obj.selectedIndex = i;
    	if(getBlank(obj.value) != "BLANK")
    	{
    		lastItem = i;
    		i = 0;
    	}
    }
}


function getBlank(id)
{
	return id.substring(id.length-5, id.length);
}

function syncSearchType(formname, prefix, typeField, trueVal, falseVal)
{
	var formObj = eval("document." + formname);
	var hiddenTypeFieldName = typeField.name.substr(prefix.length);
	//alert("begin type field (" + typeField.name + ") checked = [" + typeField.checked + "]\nbegin hidden field (" + hiddenTypeFieldName + ") value = [" + formObj[hiddenTypeFieldName].value + "]");
	if (typeField.checked)
	{
		formObj[hiddenTypeFieldName].value = trueVal;
	}
	else
	{
		formObj[hiddenTypeFieldName].value = falseVal;
	}
	//alert("end type field (" + typeField.name + ") checked = [" + typeField.checked + "]\nend hidden field (" + hiddenTypeFieldName + ") value = [" + formObj[hiddenTypeFieldName].value + "]");
}

//  DSG 9/21/04  Moved from ComWorksheet
function stripPhone()
{
	document.xtolform.XT_PHONE.value = getOnlyDigits(document.xtolform.XT_PHONE.value);
}

function FireplaceDetailPopup(navigate, num)
{
	if (checkDelayedAction('FireplaceDetailPopup(\"'+navigate+'\",'+num+')'))
	{
		return;
	}
	FireplaceDetailPopupBase(navigate,num);
}

function qualityWizardPopup(query)
{
	if (checkDelayedAction('qualityWizardPopup(\"'+query+'\")'))
	{
		return;
	}
	MHSQualityWizardPopup(query);
}

function checkDelayedAction(localAction)
{
	return false;
}

function doUUFieldChange()
{

}

function allocAdditionArrays()
{
	  additionID = new Array();
	  additionProfile = new Array();
	  additionYear = new Array();
	  additionSqFt = new Array();
}

function addSectionToDefaults(section, thisAddition, scaleFactor, scaledDefs)
{
	// make sure the section exists in the result
	if (typeof scaledDefs[section] == 'undefined')
	{
		var sArray = new Array();
		scaledDefs[section] = sArray;
	}
	for (tag in thisAddition[section])
	{
		// make sure the tag exists in the results
		if (typeof scaledDefs[section][tag] == 'undefined') scaledDefs[section][tag] = 0;
		var orig = scaledDefs[section][tag];
		var newVal = orig + (thisAddition[section][tag] * scaleFactor);
		scaledDefs[section][tag] = newVal;
	}
}

function calculateAdditionPercentages()
{
	mainProfile = profileIHValues[document.xtolform.SELECT_XTOLCOMBO_XTOL_STRUCT_TYPE_PERCENT.selectedIndex];
	mainYear = document.xtolform.XT_YEAR_BUILT.value;

	if (typeof document.xtolform['XT_FUNCTIONAL_COST'] != 'undefined'
		&& document.xtolform['XT_FUNCTIONAL_COST'].value > 0) mainYear = 2004;

	mainResults = new Array();
	getSingleFoundationDefaults(mainProfile, mainYear, mainResults);
	allDefaults = new Array();
	allDefaults[0] = mainResults;
	for (var i=0; i < additionCount; i++)
	{
		res = new Array();
		getSingleFoundationDefaults(additionProfile[i], additionYear[i], res);
		allDefaults[i+1] = res;
	}

	// calculate scaling factor
	scale = new Array();
	totalSF = document.xtolform.XT_USER_TOTAL_SF.value;
	if (totalSF == 0) return null;
	additionSF = 0;
	for (i=0; i < additionCount; i++) additionSF += parseInt(additionSqFt[i],10);
	if (additionSF > totalSF) totalSF = additionSF;

	var total = 0;
	for (i=0; i < additionCount; i++)
	{
		scale[i+1] = Math.round((additionSqFt[i]/totalSF) * 100)/100;
		total += scale[i+1];
	}
	scale[0] = 1 - total;

	// now scale the defaults
	scaledDefs = new Array();
	for (i=0; i<= additionCount; i++)
	{
		for (section in allDefaults[i])	addSectionToDefaults(section, allDefaults[i], scale[i], scaledDefs);
	}
	// round the results
	for (inx in scaledDefs)
	{
		currSect = inx;
		for (tag in scaledDefs[inx]) scaledDefs[inx][tag] = Math.round(scaledDefs[inx][tag]);
	}
	return scaledDefs;
}

function checkFoundationFields()
{
	var style = addUp('XTOL_FOUND_CONST_PERCENT_COMBO');
	var fm = addUp('XTOL_FOUND_WALL_MAT_PERCENT_COMBO');
	return (document.xtolform.SELECT_XTOLCOMBO_XTOL_FOUND_SHAPE_PERCENT.selectedIndex > 0 &&
				style == 100 && fm == 100)
}

function getFndDefaultStrings(defaults, section)
{
	ret = new Array();
	var ids = '';
	var vals = '';
	var sect = defaults[section];
	if (typeof sect == 'undefined' || sect == null) return null;
	for (inx in sect)
	{
		ids += '~'+found_trans[section][inx];
		vals += '~'+defaults[section][inx];
	}
	ret[0] = ids;
	ret[1] = vals;
	return ret;
}

function ViewMouseOver(bttn)
{
	bttn.src = document.view_on.src;
}

function ViewMouseOut(bttn)
{
	bttn.src = "/xtol/images/btn_view_off.gif";
}

function MoreMouseOver(object)
{
	object.src = document.more_on.src;
}

function MoreMouseOut(object)
{
	object.src = "/xtol/images/btn_more_off.gif";
}
function AddMouseOver(object)
{
	object.src = document.add_on.src;
}

function AddMouseOut(object)
{
	object.src = "/xtol/images/addline_off.gif";
}
function CalcMouseOver(object)
{
	object.src = document.calculate_on.src;
}


// end of Moved from ComWorksheet

//	TODO: Complete this function
function ownerOccupiedOnChange(object)
{
}

function doExtend(formObj, checkBoxArray, ValuationDesc)
{
	var anyChecked = false;
	for (i = 0; i < checkBoxArray.length; i++)
	{
		if (checkBoxArray[i].checked)
		{
			anyChecked = true;
			break;
		}
	}
	if(arguments.length == 2)
	{
		ValuationDesc = "valuation";
	}

	if (!anyChecked)
	{
		alert("Please check the "+ValuationDesc+"s whose drop dates you \nwant to extend, then click the Extend button.");
	}
	else
	{
		formObj.submit();
	}
}

function getWindowHeight()
{
	var windowHeight=0;
	if(typeof(window.innerHeight)=='number')
	{
		windowHeight=window.innerHeight;
	}
	else
	{
		if(document.documentElement &&	document.documentElement.clientHeight)
		{
			windowHeight = document.documentElement.clientHeight;
		}
		else
		{
			if(document.body && document.body.clientHeight)
			{
				windowHeight = document.body.clientHeight;
			}
		}
	}
	return windowHeight;
}

function getWindowWidth()
{
	var windowWidth=0;
	if(typeof(window.innerWidth)=='number')
	{
		windowWidth=window.innerWidth;
	}
	else
	{
		if(document.documentElement &&	document.documentElement.clientWidth)
		{
			windowWidth = document.documentElement.clientWidth;
		}
		else
		{
			if(document.body && document.body.clientWidth)
			{
				windowWidth = document.body.clientWidth;
			}
		}
	}
	return windowWidth;
}


function setPopupFooter()
{
    if( document.getElementById('header') != null &&
	document.getElementById('body') != null &&
	document.getElementById('footer') != null)
	{
		var windowHeight = getWindowHeight();
        if(windowHeight>0)
        {
            var headerHeight = document.getElementById('header').offsetHeight;
			var contentHeight = document.getElementById('body').offsetHeight;
            var footerElement = document.getElementById('footer');
            var footerHeight = footerElement.offsetHeight;

			footerElement.style.position = setFooterStyle();

            if(windowHeight < (headerHeight+contentHeight+footerHeight) )
            {
            		footerElement.style.top = headerHeight+contentHeight;
            }else
            {
            		footerElement.style.top = windowHeight - footerHeight;
            }
        }
    }
}

function setFooterStyle(style)
{
		var browserUAString = navigator.userAgent;
		var version = "";
		//  If browser is MS Internet Explorer
		if (browserUAString.indexOf("MSIE") != -1)
		{
			return 'absolute';
		}else
		{
			return 'relative';
		}
}
function getKeyCode(e)
{
	if (!e) e = window.event;
	var vNum = getMSIEVersionNumber();
	if(vNum == -1)
	{
		return e.which;
	}
	else
	{
		return e.keyCode;
	}
}


function containsElement(arr, ele)
{
	var found = false, index = 0;
	while(!found && index < arr.length)
	if(arr[index] == ele)
		found = true;
	else
		index++;
	return found;
}


function addGroupRows(groupID)
{
	var groupArray = eval(groupID+"_GROUPS");
	var groupCount = eval(groupID+"_COUNT");
	var groupMax = eval(groupID+"_MAX");
	for(var i=0; i < groupArray.length; i++)
	{
		addGroupRow(groupID, groupArray[i], null, i);
	}
	for(var i=0; i < groupArray.length; i++)
	{
		// Still can add rows
		if(groupCount[i] < groupMax[i])
		{
			return;
		}
	}
	var addLink = document.getElementById(groupID+"_ADDLINK");
	if (addLink != null) addLink.style.display = 'none';
}

function addGroupRow(groupID, subGroupId, prefix, subGroupIndexParam, showAddedRowLabel)
{
	var valuePrefix = "XTOLCOMBO_";
	var addLinkPrefix = "ADDLINK_";
	var usePrefix = false;
	var countArray = "_COUNT";
	var prefixStr = "";
	if (typeof prefix != undefined && prefix != null)
	{
		valuePrefix = prefix+"_"+valuePrefix;
		addLinkPrefix += prefix+"_";
		usePrefix = true;
		countArray = "_"+prefix+countArray;
		prefixStr = prefix+"_";
	}
	var selectPrefix = "SELECT_" + valuePrefix;;
	var cbPrefix = "SEL_" + valuePrefix;
	var groupArrayArr = eval(groupID+"_GROUPS");		//all groups can use same one
	var groupMaxArr		= eval(groupID+"_MAX");			//all groups can use same one
	var groupCountArr	= eval(groupID+countArray);		//there needs to be one per group
	var subGroupIndex	= -1;

	if (typeof subGroupIndexParam != 'undefined')
	{
		subGroupIndex = subGroupIndexParam;
		subGroupId = groupArrayArr[subGroupIndex];
	}
	else
	{
		for(var i=0; i < groupArrayArr.length; i++)
		{
			if (subGroupId == groupArrayArr[i])
			{
				subGroupIndex = i;
				break;
			}
		}
	}

	if (subGroupIndex == -1)
	{
		return;
	}

	var groupCount		= groupCountArr[subGroupIndex];
	var groupMax		= groupMaxArr[subGroupIndex];
	//alert("subGroupId: " + subGroupId + " groupCount: " + groupCount + " groupMax: " + groupMax);
	if(groupCount < groupMax)
	{
		//Find the table row.
		//alert("groupCount: " + groupCount + " trTag: " + prefixStr+subGroupId+(groupCount-1));
		var trTag = document.getElementById(prefixStr+subGroupId+(groupCount-1));

		//if (trTag == null) alert ("was null element:"+subGroupId+(groupCount-1));
		//else alert ("was not null element:"+subGroupId+(groupCount-1));

		//Find the parent tbody
		var tbl = trTag.parentNode;
		var trClone = tbl.insertRow(trTag.rowIndex+1);
		trClone.id = prefixStr+subGroupId+groupCount;
		//Get the range of tab indexes
		var minTab = findTabExtremeMin(trTag);
		var maxTab = findTabExtremeMax(trTag);
		for(var j = 0; j < trTag.childNodes.length; j++)
		{
			trClone.appendChild(copyNodeExceptID(trTag.childNodes[j], groupCount-1, subGroupId, 1, groupMax, maxTab-minTab, showAddedRowLabel));
			//IE Seems to lose the fact that a checkbox was uncheck so I do it again here
			if(window.document.xtolform[cbPrefix+subGroupId+groupCount])
			{
				window.document.xtolform[cbPrefix+subGroupId+groupCount].checked = false;
			}
			//find the first unselect option
			var new_option = 0;
			var k = 0
			while(k < groupCount)
			{
				if(window.document.xtolform[selectPrefix+subGroupId+k] &&
				   window.document.xtolform[selectPrefix+subGroupId+k].selectedIndex == new_option
				  )
				{
					new_option++;
					k = 0;
					continue;
				}
				k++
			}
			if(window.document.xtolform[selectPrefix+subGroupId+groupCount])
			{
				window.document.xtolform[selectPrefix+subGroupId+groupCount].selectedIndex = new_option;
			}
		}
		groupCountArr[subGroupIndex]++;

		for(var i=0; i < groupMaxArr[subGroupIndex]; i++)
		{
			//alert ('i='+i+' groupCountArr[subGroupIndex]='+groupCountArr[subGroupIndex]+' groupMaxArr[subGroupIndex]='+groupMaxArr[subGroupIndex]);
			if((i+1) < groupCountArr[subGroupIndex] || groupCountArr[subGroupIndex] >= groupMaxArr[subGroupIndex])
			{
				var addLink = document.getElementById(addLinkPrefix+subGroupId+i);
				if (addLink != null) addLink.style.display = 'none';
			}
		}
		setFooter();
	}
}

function removeGroupRow(groupId, subGroupId, rowToRemove)
{
	// remove row
	rowToRemove.parentNode.deleteRow(rowToRemove.rowIndex);

	var groupArrayArr = eval(groupId+"_GROUPS");
	var groupCountArr	= eval(groupId+"_COUNT");
	var subGroupIndex	= -1;
	for(var i=0; i < groupArrayArr.length; i++)
	{
		if (subGroupId == groupArrayArr[i])
		{
			subGroupIndex = i;
			break;
		}
	}
	groupCountArr[subGroupIndex]--;
}

function advanceOnKeyUp(e, obj, nextFieldName, fieldLength, formObj)
{
	var keyCode = getKeyCode(e);
	var isMSIE = (getMSIEVersionNumber() != -1);
	var filter = (isMSIE) ? [0,8,9,16,17,18,37,38,39,40,46] : [0,8,9];
	if (!containsElement(filter, keyCode) && obj.value.length == fieldLength)
	{
		formObj[nextFieldName].focus();
		formObj[nextFieldName].select();
	}
}

function pushEstimateIdToOpener(estimateId)
{
	if (typeof top.opener.document.xtolform['estimate'] != "undefined")
	{
		if ( top.opener.document.xtolform['estimate'].value == "" && null != estimateId && "" != estimateId)
		{
			top.opener.document.xtolform['estimate'].value = estimateId;
		}
	}
}

function checkReturnFocus(obj)
{
//	alert("in checkReturnFocus\ntypeof(returnFocus)=["+typeof(returnFocus)+"]\nreturnFocus=["+returnFocus+"]");
	if (typeof(returnFocus) != "undefined" && returnFocus)
	{
		returnFocus = false;
		obj.focus();
	}
}

function checkCancelTab(e)
{
	if (typeof(cancelKeyFlag) != "undefined" && cancelKeyFlag)
	{
		cancelKeyFlag = false;
		cancelKey(e);
	}
}

function cancelKey(e)
{
	e.returnValue=false;
}

function zipChanged(obj)
{
	onZipChange(obj);	
	setExplicit(obj);
}

function onZipChange(obj)
{
	obj.value = obj.value.toUpperCase();	
	checkAutoDefault(obj);
}


function checkAutoDefault(obj)
{
	//dummy method
}

function showFoundationTypes(pu, p, prefix)
{
	var valuePrefix = "";
	var usePrefix = false;

	if (typeof prefix != undefined && prefix != null)
	{
		valuePrefix = prefix+"_"+valuePrefix;
		usePrefix = true;
	}

	var selectPrefix = "SELECT_" + valuePrefix;;
	var cbPrefix = "SEL_" + valuePrefix;
	pu = pu.substring(6);

	var setExplicit = false;
	var hidingExplicit = false;
	var hidingDefaultValue = false;
	var doDefaults = false;

	for(var j=0; j<IDS.length; j++)
	{
		if(GROUPS[IDS[j]] == "XTOL_F")
		{
			var currId = IDS[j];

			if (usePrefix)
			{
				var sourceId = document.xtolform["RID_" + valuePrefix + currId].value;
 				currId = sourceId + ":" + currId;
 			}

			if(isExplicit(currId))
			{
				setExplicit = true;
			}
		}
	}

	for(var i=0; i<IDS.length; i++)
	{
		if(GROUPS[IDS[i]] != "XTOL_F") continue;

		var unprefixedTypeId = IDS[i];
		var divId = "DIV_" + unprefixedTypeId;
		var typeId = unprefixedTypeId;
		 if (usePrefix)
         {
                 typeId = prefix+"_"+unprefixedTypeId;
                 divId = divId + "_"+prefix;
         }

		if(includeId(unprefixedTypeId, pu, p, ''))
		{
			changeToShow(divId);
		}
		else
		{
			if(document.xtolform[typeId].value > 0)
			{
				hidingDefaultValue = true;
				if (setExplicit)
				{
					hidingExplicit = true;
				}
			}
			changeToHide(divId);
			document.xtolform[cbPrefix+unprefixedTypeId].checked = false;
			document.xtolform[valuePrefix+unprefixedTypeId].value = '';
		}
	}
	if(hidingExplicit || (usePrefix && hidingDefaultValue))
	{
		removeAllFoundationTypesFromExplicitList(prefix);
		if (usePrefix)
		{
			removeAllFoundationDefaults(prefix);
		}
	}
	if (!usePrefix)
	{
		if (hidingExplicit || !setExplicit)
		{
			doDefaults = true;
		}
	}
	return doDefaults;
}

function doFoundDefaults(pu, p, prefix)
{
	var usePrefix = false;
	var valuePrefix = "";
	if (typeof prefix != undefined && prefix != null)
	{
		valuePrefix = prefix+"_"+valuePrefix;
		useprefix = true;
	}

	var selectPrefix = "SELECT_" + valuePrefix;;
	var cbPrefix = "SEL_" + valuePrefix;

	pu = pu.substring(6);
	//alert("doingConstructionDefaults");
	for(var i=0; i<IDS.length; i++)
	{
		var unprefixedTypeId = IDS[i];
		if (GROUPS[unprefixedTypeId] != 'XTOL_F') continue;

		document.xtolform[cbPrefix+unprefixedTypeId].checked = false;
		document.xtolform[valuePrefix+unprefixedTypeId].value = '';

		var value = VARS[IDS[i]];

		if(value != 0 )
		{
			document.xtolform[valuePrefix+unprefixedTypeId].value = value;
			document.xtolform[cbPrefix+unprefixedTypeId].checked = true;
		}
	}
}

function doConstructionDefaults(pu, p, prefix)
{
	//alert("pu: " + pu + " p: " + p + " prefix: " + prefix);
	var usePrefix = false;
	var valuePrefix = "XTOLCOMBO_";
	if (typeof prefix != undefined && prefix != null)
	{
		valuePrefix = prefix+"_"+valuePrefix;
		usePrefix = true;
	}

	var selectPrefix = "SELECT_" + valuePrefix;;
	var cbPrefix = "SEL_" + valuePrefix;

	pu = pu.substring(6);
	//alert("doingConstructionDefaults");
	for(var i=0; i< XTOL_TCSUBGROUPS.length; i++)
	{
		var typeId = XTOL_TCSUBGROUPS[i];
		var rowIdBase = typeId;
		if (usePrefix) rowIdBase = prefix+"_"+rowIdBase;

		//alert("group = " + typeId);
		//alert("clearing group " + typeId);
		for (k=0; k<IDS.length;k++)
		{
			var rowId = rowIdBase+k;
			var rowObj = document.getElementById(rowId);
			//alert("rowid: " + rowId + " element: " + rowObj);
			if (rowObj != null)
			{
				if (k==0)
				{
					document.xtolform[cbPrefix+typeId+k].checked = false;
					document.xtolform[valuePrefix+typeId+k].value = '';

					// If this question has a drop down reset it to index zero
					var dropDownObj = document.xtolform["SELECT_XTOLCOMBO_" + rowId];
					if (typeof dropDownObj != 'undefined' && dropDownObj != null
							&& dropDownObj.options != null)
					{
						//alert("property: " + k);
						dropDownObj.selectedIndex = 0;
						changeToShow("ADDLINK_" + rowId);
					}
				}
				else
				{
					removeGroupRow("XTOL_TC", typeId, rowObj);
				}
			}
			else break;
		}

		var groupCount = 0;
		for(var j=0; j<IDS.length; j++)
		{
			if(GROUPS[IDS[j]] == XTOL_TCSUBGROUPS[i])
			{

				var value = VARS[IDS[j]];
				//alert("id: " + IDS[j] + " value: " + value);

				if(value != 0 )
				{
					//alert("var = " + IDS[j] + " value = " + value + " group = " + typeId + " groupCount = " + groupCount);
					var rowId = rowIdBase+groupCount;
					//alert("rowId: " + rowId + " rowObj: " + document.getElementById(rowId));
					if (document.getElementById(rowId) == null)
					{
						addGroupRow("XTOL_TC", typeId, prefix);
					}
					//alert("ids: "+valuePrefix+typeId+groupCount);
					document.xtolform[valuePrefix+typeId+groupCount].value = value;
					document.xtolform[cbPrefix+typeId+groupCount].checked = true;
					document.xtolform[selectPrefix+typeId+groupCount].value = IDS[j];
					groupCount++;
				}
			}
		}
	}
}

function includeGroupId(groupId, pu, p)
{
	for(var i = 0; i < IDS.length; i++)
	{
		if(IDS[i] == groupId && includeId(IDS[i], pu, p, '') && specialCaseIncludeId(pu, IDS[i]))
		{
			return true;
		}
	}
	return false;
}

// This should be overridden in the jsp and should call the
// includeIdSpecialCase method in the include.js file
function specialCaseIncludeId(pu, id)
{
	return true;
}



function showConstructionTypes(pu, p, prefix)
{
	var valuePrefix = "XTOLCOMBO_";
	var usePrefix = false;

	if (typeof prefix != undefined && prefix != null)
	{
		valuePrefix = prefix+"_"+valuePrefix;
		usePrefix = true;
	}

	var selectPrefix = "SELECT_" + valuePrefix;;
	var cbPrefix = "SEL_" + valuePrefix;
	pu = pu.substring(6);

	var setExplicit = false;
	var hidingExplicit = false;
	var hidingDefaultedValue = false;
	var doDefaults = false;

	for(var i=0; i< XTOL_TCSUBGROUPS.length; i++)
	{
		var typeId = XTOL_TCSUBGROUPS[i];

		for(var j=0; j<IDS.length; j++)
		{
			if(GROUPS[IDS[j]] == XTOL_TCSUBGROUPS[i])
			{
				var currId = IDS[j];
 				if (usePrefix)
 				{
 					var sourceId = document.xtolform["RID_" + valuePrefix + XTOL_TCSUBGROUPS[i] + "0"].value;
 					currId = sourceId + ":" + currId;
 				}

				if(isExplicit(currId))
				{
					setExplicit = true;
				}
			}
		}
	}

	for(var i=0; i< XTOL_TCSUBGROUPS.length; i++)
	{
		var typeId = XTOL_TCSUBGROUPS[i];
		var rowIdBase = typeId;
		if (usePrefix)
		{
			rowIdBase = prefix+"_"+rowIdBase;
		}

		for(var j=0; j<IDS.length; j++)
		{
			if(GROUPS[IDS[j]] == XTOL_TCSUBGROUPS[i])
			{
				if(includeGroupId(IDS[j], pu, p))
				{
					for (k=0; k<IDS.length;k++)
					{
						var rowId = rowIdBase+k
						if (document.getElementById(rowId) != null)
						{
							changeToShowTR(rowId);
						}
						else break;
					}
				}
				else
				{
					for (k=0; k<IDS.length;k++)
					{
						var rowId = rowIdBase+k
						if (document.getElementById(rowId) != null)
						{
							if(document.xtolform[valuePrefix+typeId+k].value > 0)
							{
								hidingDefaultedValue = true;
								if (setExplicit)
								{
									hidingExplicit = true;
								}
							}
							changeToHide(rowId);
							document.xtolform[cbPrefix+typeId+k].checked = false;
							document.xtolform[valuePrefix+typeId+k].value = '';
						}
						else break;
					}
				}
			}
		}
	}

	if(hidingExplicit || (hidingDefaultedValue && usePrefix))
	{
		removeAllSupportingWallExplicitAnswers(prefix);
		if (usePrefix)
		{
			removeAllSupportingWallDefaults(prefix);
		}
	}
	if (!usePrefix)
	{
		if (hidingExplicit || !setExplicit)
		{
			doDefaults = true;
		}
	}
	return doDefaults;
}

function hideAllButOne(dontHideThisOne, prefix)
{
	var usePrefix = false;
	var valuePrefix = "XTOLCOMBO_";

	if (typeof prefix != undefined && prefix != null)
	{
		valuePrefix = prefix+"_"+valuePrefix;
		usePrefix = true;
	}
	for(var i=0; i< XTOL_TCSUBGROUPS.length; i++)
	{
		var typeId = XTOL_TCSUBGROUPS[i];
		var rowIdBase = XTOL_TCSUBGROUPS[i];
		if (usePrefix)
		{
			rowIdBase = prefix+"_"+rowIdBase;
		}

		for(var j=0; j<IDS.length; j++)
		{
			if(GROUPS[IDS[j]] == XTOL_TCSUBGROUPS[i])
			{
				if(dontHideThisOne == IDS[j])
				{
					for (k=0; k<IDS.length;k++)
					{
						var rowId = rowIdBase+k
						if (document.getElementById(rowId) != null)
						{
							changeToShowTR(rowId);
						}
						else break;
					}
				}
				else
				{
					for (k=0; k<IDS.length;k++)
					{
						var rowId = rowIdBase+k
						if (document.getElementById(rowId) != null)
						{
							changeToHide(rowId);
						}
						else break;
					}
				}
			}
		}
	}
}

function removeAllSupportingWallDefaults(prefix)
{
	var valuePrefix = "XTOLCOMBO_";
	var usePrefix = false;
	if (typeof prefix != undefined && prefix != null)
	{
		valuePrefix = prefix+"_"+valuePrefix;
		usePrefix = true;
	}
	var selectPrefix = "SELECT_" + valuePrefix;;
	var cbPrefix = "SEL_" + valuePrefix;

	for(var i=0; i< XTOL_TCSUBGROUPS.length; i++)
	{
		var typeId = XTOL_TCSUBGROUPS[i];
		for(var j=0; j<IDS.length; j++)
		{

			var objValue = document.xtolform[valuePrefix + typeId + j];
			var objCheck = document.xtolform[cbPrefix + typeId + j];
			if (typeof objValue != 'undefined' && objValue != null
					&& typeof objCheck != 'undefined' && objCheck != null)
			{
				//alert("about to remove: " + valuePrefix + typeId + j);
				objValue.value = '';
				objCheck.checked = false;
			}
		}

	}
	if (usePrefix)
	{
		setTotalForGroup(prefix + '_XTOL_TC_SUB');
	}
	else
	{
		setTotalForGroup('XTOL_TC_SUB');
	}
}

function removeAllSupportingWallExplicitAnswers(prefix)
{
	var valuePrefix = "XTOLCOMBO_";
	var usePrefix = false;
	if (typeof prefix != undefined && prefix != null)
	{
		valuePrefix = prefix+"_"+valuePrefix;
		usePrefix = true;
	}
	var selectPrefix = "SELECT_" + valuePrefix;;
	var cbPrefix = "SEL_" + valuePrefix;

	for(var i=0; i< XTOL_TCSUBGROUPS.length; i++)
	{
		var typeId = XTOL_TCSUBGROUPS[i];

		for(var j=0; j<IDS.length; j++)
		{
			if(GROUPS[IDS[j]] == XTOL_TCSUBGROUPS[i])
			{
				removeFromExplicitList(getFullIdFromName(selectPrefix + typeId + j));
			}
			removeExplicitColor(cbPrefix + typeId + j);
			removeExplicitColor(selectPrefix + typeId + j);
			removeExplicitColor(valuePrefix + typeId + j);
		}

	}
}

function removeAllFoundationDefaults(prefix)
{
	var valuePrefix = "";
	var usePrefix = false;
	if (typeof prefix != undefined && prefix != null)
	{
		valuePrefix = prefix+"_"+valuePrefix;
		usePrefix = true;
	}

	var selectPrefix = "SELECT_" + valuePrefix;;
	var cbPrefix = "SEL_" + valuePrefix;

	for(var i=0; i<IDS.length; i++)
	{
		typeId = IDS[i];
		if (GROUPS[typeId] != 'XTOL_F') continue;


		var objValue = document.xtolform[valuePrefix + typeId];
		var objCheck = document.xtolform[cbPrefix + typeId];
		if (typeof objValue != 'undefined' && objValue != null
				&& typeof objCheck != 'undefined' && objCheck != null)
		{
			//alert("about to remove: " + valuePrefix + typeId);
			objValue.value = '';
			objCheck.checked = false;
		}
		else
		{
			//alert("objValue: " + valuePrefix + typeId + " objCheck: " + cbPrefix + typeId);
		}
	}

	if (usePrefix)
	{
		setTotalForGroup(prefix + '_XTOL_F');
	}
	else
	{
		setTotalForGroup('XTOL_F');
	}
}

function removeAllFoundationTypesFromExplicitList(prefix)
{
	var valuePrefix = "";
	var usePrefix = false;
	if (typeof prefix != undefined && prefix != null)
	{
		valuePrefix = prefix+"_"+valuePrefix;
		usePrefix = true;
	}

	var selectPrefix = "SELECT_" + valuePrefix;;
	var cbPrefix = "SEL_" + valuePrefix;

	for(var i=0; i<IDS.length; i++)
	{
		typeId = IDS[i];
		if (GROUPS[typeId] != 'XTOL_F') continue;

		if (usePrefix)
		{
			typeId = prefix+"_"+typeId;
		}

		removeFromExplicitList(getFullIdFromName(selectPrefix + typeId));

		removeExplicitColor(cbPrefix + typeId);
		removeExplicitColor(selectPrefix + typeId);
		removeExplicitColor(valuePrefix + typeId);
	}
}

function removeExplicitColor(id)
{
	var obj = document.xtolform[id];
	if(obj != null && typeof obj != 'undefined')
	{
		obj.className = "";
	}
}

function doQualityOptions(obj, pu)
{
	pu = pu.substring(6);

	if(null == obj || obj.name=='')
	{
		return ;
	}

	var questionName = obj.name;
	var oldAnswer = obj.value;
	var isexplicit = isExplicit(questionName);

	var isBasement = false;
	if(questionName.indexOf('BASEMENT') >= 0)
	{
		isBasement = true;
	}

	//for(var i = 0; i <  obj.options.length; i++)
	//{
		obj.options.length = 0;
	//}

	var counter = 0;
	for(var j = 0; j < QUALITY_OPTIONS.length; j++)
	{
		if("MF" == QUALITY_OPTIONS[j][0] && !isBasement)
		{
			continue;
		}

		var constructedId = "XT_Q_" + QUALITY_OPTIONS[j][0];

		if(includeId(constructedId, pu, '', ''))
		{
			obj.options[counter] = new Option(QUALITY_OPTIONS[j][1], QUALITY_OPTIONS[j][0]);
			obj.options[counter].value = QUALITY_OPTIONS[j][0];
			obj.options[counter].text = QUALITY_OPTIONS[j][1];
			if(QUALITY_OPTIONS[j][0] == oldAnswer)
			{
				obj.options[counter].selected = true;
			}
			counter++;
		}
		else
		{
			if(QUALITY_OPTIONS[j][0] == oldAnswer)
			{
				removeFromExplicitList(getFullIdFromName(questionName));
				removeExplicitColor(questionName);
			}
		}
	}
	if (obj.options.length <= 2 && obj.options[0].value == "NS" && !isExplicit(getFullIdFromName(questionName)))
	{
		obj.selectedIndex = 1;
	}

}

function checkForInt(input)
{
	if(input.value != '' && isNaN(parseInt(input.value)))
	{
		input.value = '';
		return false;
	}
	return true;
}

function getEstimateId()
{
	if(document.xtolform != 'undefined' && document.xtolform != null)
	{
		var estimateIdObj = document.xtolform.estimate;
		if (typeof estimateIdObj == 'undefined' || estimateIdObj == null)
		{
			//alert("No estimateId found in this page please tell stc where you saw this message");
		}
		else
		{
			//alert("found estimateId: " + estimateIdObj.value);
			return estimateIdObj.value;
		}
	}
	return "";
}
function addEstimateIdToLocation(location)
{
	if (location.indexOf("estimate=") == -1)
	{
		// If it doesn't have any vars yet we append a "?" instead of a "&"
		if (location.indexOf("?") == -1)
		{
			location += "?estimate=" + getEstimateId();
		}
		else
		{
			location += "&estimate=" + getEstimateId();
		}
	}
	return location;
}

var pageid = (new Date()).getMilliseconds();

var popUps = new Array();

function popWindow(location, caller, properties)
{
	// If we are going to blank.htm then we don't need to add the estimateId because
	// it submits to the handler. The estimateId in this case is updated in popups.gsl.
	if (location != "/xtol/blank.htm")
	{
		location = addEstimateIdToLocation(location);
	}
	popUps[popUps.length] = window.open(location, "mhspopup"+caller+pageid, properties);
	return popUps[popUps.length - 1 ];
}

function unloadKillsPopUps()
{
	try
	{
		for(var i = 0; i < popUps.length; i++)
		{
			try
			{
		  		popUps[i].close();
		  	}
		  	catch (err)
		  	{
		  		//alert("error occured1! " + err.description);
		  		break;
		  	}
		}
	}
	catch (err2)
	{
		//alert("error occured2! " + err2.description);
	}
}

function validateTxtDateField(inputField)
{
	var retVal = false;
	var dateTxt	= inputField.value;
	var dateMills = Date.parse("" + dateTxt);

	if (!isNaN(dateMills))
	{
		retVal = true;
	}

	return retVal;
}


function checkSearchDate(obj)
{
	var retVal = true;
	if(!validateTxtDateField(obj) && obj.value)
	{
		retVal = false;
		var dateText = obj.value;
		alert("The specified date value (" + dateText + ") is invalid.\n\nPlease specify a valid date using the following format:\n\nM/D/YYYY (e.g. 10/9/2005)");
		obj.value = "";
		obj.focus();
		obj.select();
	}
	return retVal;
}

/* Functions for CMC and AG Occupancy and Use (if you make changes make sure it works for both */

function addAttSoRow(index)
{
	var prefixCountObj = document.xtolform.PREFIX_COUNT;
	var newStructNumber = index + 2;
	var newParentIndex = index + 1;
	var newAttPrefix = alphabet.charAt(prefixCountObj.value++);
	var newAttSourceId = "SO_SRC_" + (index + 1);
	var newBuiltInPrefix = alphabet.charAt(prefixCountObj.value++);
	var newBuiltInSourceId = "SO_SRC_" + (index + 1) + "_0";
	var addedSoList = document.xtolform["ADDED_SO_LIST"];
	if (typeof addedSoList == 'undefined')
	{
		alert("Unable to find ADDED_SO_LIST");
	}
	else
	{
		addedSoList.value += newAttSourceId + "~";
		addedSoList.value += newBuiltInSourceId + "~";
	}

	var parentTemplate = document.getElementById("PARENT_TEMPLATE");
	var newAttParent = document.createElement("div");
	// copy template into new attached building parent
	newAttParent.innerHTML = parentTemplate.innerHTML;
	copyAttributes(parentTemplate, newAttParent);
	newAttParent.id = "PARENT_" + newParentIndex;
	newAttParent.style.display = "block";

	// replace fake tags from template with new values
	newAttParent.innerHTML = newAttParent.innerHTML.replace(new RegExp("--REPLACE_ME_WITH_STRUCTURE_NUMBER", "g"), newStructNumber);
	newAttParent.innerHTML = newAttParent.innerHTML.replace(new RegExp("--REPLACE_ME_WITH_PARENT_INDEX", "g"), newParentIndex);
	newAttParent.innerHTML = newAttParent.innerHTML.replace(new RegExp("--REPLACE_ME_WITH_ATT_PREFIX", "g"), newAttPrefix);
	newAttParent.innerHTML = newAttParent.innerHTML.replace(new RegExp("SO_SRC_--REPLACE_ME_WITH_ATT_SOURCE_ID", "g"), newAttSourceId);
	newAttParent.innerHTML = newAttParent.innerHTML.replace(new RegExp("--REPLACE_ME_WITH_BUILT_IN_PREFIX", "g"), newBuiltInPrefix);
	newAttParent.innerHTML = newAttParent.innerHTML.replace(new RegExp("SO_SRC_--REPLACE_ME_WITH_BUILT_IN_SOURCE_ID", "g"), newBuiltInSourceId);
	newAttParent.innerHTML = newAttParent.innerHTML.replace(new RegExp("--REPLACE_ME_WITH_CHILD_INDEX", "g"), "0");

	// Now add the new Attached Building to the document
	var attParent = document.getElementById("PARENT_BUILDINGS");
	attParent.appendChild(newAttParent);

	changeToHide('ADD_ATT_'+index);
	updateAddSOButtons();
	checkHiddenFields();
}

function addSoRow(parentPrefix, parentIndex, childIndex)
{
	var prefixCountObj = document.xtolform.PREFIX_COUNT;
	var newPrefix = alphabet.charAt(prefixCountObj.value++);
	var oldSourceId = "SO_SRC_"+((parentIndex==-1)?"PRIMARY":parentIndex)+"_"+childIndex;
	var newSourceId = "SO_SRC_"+((parentIndex==-1)?"PRIMARY":parentIndex)+"_"+(childIndex+1);
	var parentSourceId = "SO_SRC_"+((parentIndex==-1)?"PRIMARY":parentIndex);
	//alert("oldSourceId: " + oldSourceId + " newSourceId: " + newSourceId);
	var addedSoList = document.xtolform["ADDED_SO_LIST"];
	if (typeof addedSoList == 'undefined')
	{
		alert("Unable to find ADDED_SO_LIST");
	}
	else
	{
		addedSoList.value += newSourceId + "~";
	}
	var trSpacerTemplate = document.getElementById("SO_ROW_SPACER_--REPLACE_ME_WITH_BUILT_IN_PREFIX");
	var trTagTemplate = document.getElementById("SO_ROW_--REPLACE_ME_WITH_BUILT_IN_PREFIX");
	var tbody = document.getElementById("SO_TBODY_"+parentIndex);

	// First create a new spacer
	var newTrSpacer = tbody.insertRow(tbody.rows.length);
	copyAttributes(trSpacerTemplate, newTrSpacer);
	newTrSpacer.id = "SO_ROW_SPACER_" + newPrefix;
	for(var i = 0; i < trSpacerTemplate.cells.length; i++)
	{
		var tdSpacer = document.createElement("td");
		copyAttributes(trSpacerTemplate.cells[i], tdSpacer);

		tdSpacer.innerHTML = trSpacerTemplate.cells[i].innerHTML.replace(new RegExp("--REPLACE_ME_WITH_BUILT_IN_PREFIX", "g"), newPrefix);
		tdSpacer.innerHTML = tdSpacer.innerHTML.replace(new RegExp("SO_SRC_--REPLACE_ME_WITH_BUILT_IN_SOURCE_ID", "g"), newSourceId);
		newTrSpacer.appendChild(tdSpacer);
	}

	// Next create a new so row
	var newRow = tbody.insertRow(tbody.rows.length);
	copyAttributes(trTagTemplate, newRow);
	newRow.id = "SO_ROW_" + newPrefix;
	for(var i = 0; i < trTagTemplate.cells.length; i++)
	{
		var newTd = document.createElement("td");
		copyAttributes(trTagTemplate.cells[i], newTd);
		newTd.id = trTagTemplate.cells[i].id.replace(new RegExp("--REPLACE_ME_WITH_BUILT_IN_PREFIX", "g"), newPrefix);


		newTd.innerHTML = trTagTemplate.cells[i].innerHTML.replace(new RegExp("--REPLACE_ME_WITH_BUILT_IN_PREFIX", "g"), newPrefix);
		newTd.innerHTML = newTd.innerHTML.replace(new RegExp("SO_SRC_--REPLACE_ME_WITH_BUILT_IN_SOURCE_ID", "g"), newSourceId);
		newTd.innerHTML = newTd.innerHTML.replace(new RegExp("--REPLACE_ME_WITH_PARENT_INDEX", "g"), parentIndex);
		newTd.innerHTML = newTd.innerHTML.replace(new RegExp("--REPLACE_ME_WITH_ATT_PREFIX", "g"), parentPrefix);
		newTd.innerHTML = newTd.innerHTML.replace(new RegExp("SO_SRC_--REPLACE_ME_WITH_ATT_SOURCE_ID", "g"), parentSourceId);
		newTd.innerHTML = newTd.innerHTML.replace(new RegExp("--REPLACE_ME_WITH_CHILD_INDEX", "g"), (childIndex+1));

		newRow.appendChild(newTd);


		/***********FOR TESTING SHOULD BE REMOVED *************************/

		//newTd.innerHTML = newTd.innerHTML.replace(/ class="" onkeypress=javascript:disallowChars/, " class=\"\" value='" +newPrefix+"' onkeypress=javascript:disallowChars");

		/*********** END FOR TESTING SHOULD BE REMOVED *************************/
	}

	//Need to hide the previous add Row button

	//assumes it is in the 3rd last row.
	prevTr = tbody.rows[tbody.rows.length-3];
	if(prevTr.id.length != "SO_ROW_".length +1 || //Watch out for SO_ROW_SPACER ROWS
		prevTr.id.substr(0, "SO_ROW_".length) != "SO_ROW_"
		)
	{
		alert("Error:Not getting the right row to hide.\nGetting:" + prevTr.id);
		return;
	}
	//assumes it is in the 2nd last cell.
	tdToHide = prevTr.cells[prevTr.cells.length -2];
	if(tdToHide.id.substr(0, "ADD_ROW_TD_".length) != "ADD_ROW_TD_")
	{
		alert("Error:Not getting the right row to hide\nGetting:"+ tdToHide);
		return;
	}
	changeToHideByElement(tdToHide);

	updateAddSOButtons();

	checkHiddenFields();

	//set focus on the new row
	findFirstVisFormElement(newRow).focus();

}

function updateAddSOButtons()
{

	if(document.xtolform.PREFIX_COUNT.value > 50)
	{
		divList = document.getElementsByTagName("div");
		for(var i = 0; i < divList.length; i++)
		{
			if(divList[i].id &&
				divList[i].id.substr(0, "ADD_ATT_".length) == "ADD_ATT_")
			{
				changeToHideByElement(divList[i]);
			}
		}

		if(document.xtolform.PREFIX_COUNT.value > 51)
		{
			tdList = document.getElementsByTagName("td");
			for(var i = 0; i < tdList.length; i++)
			{
				if(tdList[i].id &&
					tdList[i].id.substr(0, "ADD_ROW_TD_".length) == "ADD_ROW_TD_")
				{
					changeToHideByElement(tdList[i]);
				}
			}
		}
	}

}

/******************** End of CMC and AG Occupancy and Use functions *****************************/


function copyAttributes(fromObj, toObj, showLogs)
{
	// 1 == ELEMENT_NODE
	if (1 == fromObj.nodeType && 1 == toObj.nodeType)
	{
		for (var j = 0; j < fromObj.attributes.length; j++)
		{
			if (typeof showLogs != 'undefined' && showLogs && fromObj.attributes[j].specified)
			{
				alert("fromname: " + fromObj.attributes[j].name + " fromval: " + fromObj.attributes[j].value);
			}
			if (fromObj.attributes[j].specified)
			{
				// Windows exploder doesn't handle class names correctly so I have to have
				// a special case for it. (if you get the attribute named 'class' and you want
				// to set it, you have to use className...at least with windows explorer, firefox
				// works fine with out this
				if ('class' == fromObj.attributes[j].name)
				{
					toObj.setAttribute('className', fromObj.attributes[j].value);
				}
				else
				{
					toObj.setAttribute(fromObj.attributes[j].name, fromObj.attributes[j].value);
				}
			}
			if (typeof showLogs != 'undefined' && showLogs && fromObj.attributes[j].specified)
			{
				alert("toname: " + toObj.attributes[j].name + " toval: " + toObj.attributes[j].value);
			}
		}
	}
}

function changeToShowComComboWidget(uniqueId)
{
	showHideComComboWidget(uniqueId, true);
}

function changeToHideComComboWidget(uniqueId)
{
	showHideComComboWidget(uniqueId, false);
}

function showHideComComboWidget(uniqueId, show)
{
	var inc = 0;
	var baseId = "TRTOP_" + uniqueId + "_PREINC_";

	//	Find the first row of the ComComboWidget
	var firstTR = document.getElementById(baseId + inc);

	//	Find the parent of the ComComboWidget rows
	var parent = firstTR.parentNode;

	//	Used to terminate iteration
	var rowFound = true;

	//	While there are more rows to hide/show, loop through each child of the parent to find the row and show/hide it.
	while (rowFound)
	{
		rowFound = false;
		for(var i = 0; i < parent.childNodes.length; i++)
		{
			if (parent.childNodes[i].id == (baseId + inc))
			{
				rowFound = true;
				if (show)
				{
					changeToShowTR(parent.childNodes[i].id);
				}
				else
				{
					changeToHide(parent.childNodes[i].id);
				}
			}
		}
		inc++;
	}
}

function checkShowMHFoundationMaterial()
{
	var uniqueId = "XTOL_FM";
	if (isComboPercentGroupOptionNonZero("XTOL_F", "XT_F_B") || isComboPercentGroupOptionNonZero("XTOL_F", "XT_F_CR"))
	{
//		alert("in checkShowMHFoundationMaterial() change to SHOW");
		changeToShowComComboWidget(uniqueId);
		changeToShow("xtMHFoundationMaterial");
	}
	else
	{
//		alert("in checkShowMHFoundationMaterial() change to HIDE");
		changeToHideComComboWidget(uniqueId);
		changeToHide("xtMHFoundationMaterial");
	}
}


//	Used on Commercian and Agricultural Use pages to link help topics with use type selections
function getPurposeHelpTopicLink(purpose)
{
	//alert("getPurposeHelpTopicLink("+purpose+")");
	return purposeHelp[purpose];
}

//	Used on Commercial and Agricultural Use pages to link help topics with use type selections
function doQualityFinishesLink(prefix, isQuality)
{
	var puObj = null;
	var qObj = null;
	if (typeof prefix != 'undefined')
	{
		puObj = document.xtolform['SELECT_' + prefix + '_XTOLCOMBO_XTOL_PU'];
		qObj = document.xtolform[prefix + '_XT_QUALITY'];
	}


	if (puObj.value.indexOf("_BLANK") != -1)
	{
		OpenHelp(getPurposeHelpTopicLink("DEFAULT"));
		return;
	}

	var id = getPurposeHelpTopicLink(puObj.value);
	if (isQuality)
	{
		var qVal = qObj.value;
		if (qVal == "NS")
		{
			qVal = qObj.options[1].value;
		}
		OpenHelp(id, getPurposeHelpTopicLink(qVal));
	}
	else
	{
		OpenHelp(id);
	}
}

//	Used on Commercian and Agricultural Use pages to link help topics with use type selections
function doBelowGradeQualityFinishesLink(prefix, useId, isQuality)
{
	var id = getPurposeHelpTopicLink(useId);
	var qObj = null;
	qObj = document.xtolform[prefix + '_XT_BASEMENT_QUALITY'];
	if (null != qObj && isQuality)
	{
		var qVal = qObj.value;
		if (qVal == "NS")
		{
			qVal = qObj.options[1].value;
		}
		OpenHelp(id, getPurposeHelpTopicLink(qVal));
	}
	else
	{
		OpenHelp(id);
	}
}

//Used for other attached structures to hide heated when Screened Lanai is selected.
function updateHeated(select)
{
	var heatedSpan = document.getElementById(select.name.replace("TYPE", "HEATED_DIV"));
	if(select.options[select.selectedIndex].value == "Screened_Lanai")
	{
		heatedSpan.style.visibility = "hidden";
	}
	else
	{
		heatedSpan.style.visibility = "visible";
	}

}



function onPercentInCountGroupChange(groupId, obj, uniqueId, select)
{
	var ccObj = document.xtolform['CC_'+uniqueId];
	var selectObj = document.xtolform['SELECT_'+uniqueId];
	var percentObj = document.xtolform[uniqueId];

	setExplicit(ccObj);
	setExplicit(selectObj);
	setExplicit(percentObj);

	var ccVal = false;
	var selectIndex = 0;
	var percentVal = ZEROVAL;

	// Case 1: Checkbox changed
	if (obj.name == 'CC_'+uniqueId)
	{
		if (ccObj.checked)
		{
			if (percentObj.value == "0" || percentObj.value == ZEROVAL)
			{
				percentVal = 100;
			}
			if (selectObj.selectedIndex == 0)
			{
				selectIndex = 1;
			}
			ccVal = true;
		}
	}
	// Case 2: Drop Down changed
	else if (obj.name == 'SELECT_'+uniqueId)
	{
		if (selectObj.selectedIndex != 0)
		{
			if (percentObj.value == "0" || percentObj.value == ZEROVAL)
			{
				percentVal = 100;
			}
			else
			{
				percentVal = percentObj.value;
			}
			ccVal = true;
			selectIndex = selectObj.selectedIndex;
		}
	}
	// Case 3: Percent Field changed
	else if (obj.name == uniqueId)
	{
		if (percentObj.value != "0" && percentObj.value != ZEROVAL)
		{
			ccVal = true;
			if (selectObj.selectedIndex == 0)
			{
				selectIndex = 1;
			}
			else
			{
				selectIndex = selectObj.selectedIndex;
			}
			percentVal = percentObj.value;
		}
	}

	// Make sure they didn't paste in strings or negative numbers
	if (isNaN(parseInt(percentVal)) || percentVal <= 0)
	{
		percentVal = ZEROVAL;
	}

	if (percentVal > 100)
	{
		percentVal = 100;
	}

	ccObj.checked = ccVal;
	selectObj.selectedIndex = selectIndex;
	percentObj.value = percentVal;
}

function overriddenStyleCheck()
{
	var styleObj = document.xtolform['SELECT_XTOLCOMBO_XTOL_STRUCT_STYLE_PERCENT'];
	if (isOverrideStyle(styleObj.value))
	{
		resetSelect('SELECT_XTOLCOMBO_XTOL_STRUCT_STYLE_PERCENT');
	}

}


function resetSelect(id)
{
	var selectObj = document.xtolform[id];
	if (typeof selectObj != 'undefined')
	{
		selectObj.selectedIndex = 0;
		removeExplicitColor(selectObj.name);

		var options = selectObj.options;
		for (var i = 0; i < options.length; i++)
		{
			removeFromExplicitList(options[i].value);
		}
	}
}

function resetInput(id)
{
	var inputObj = document.xtolform[id];
	if (typeof inputObj != 'undefined')
	{
		inputObj.value = "";
		removeExplicitColor(inputObj.name);
		removeFromExplicitList(getFullIdFromName(inputObj.name));
	}
}




function tutorialFlashInput(file, tutorialDir)
{
	

document.write(
'<object type="application/x-shockwave-flash" id="flash" data="/xtol/tutorialgen/html/flash/'+file+'">'+
'	<param name="movie" value="/xtol/tutorial/'+tutorialDir+'/html/flash/'+file+'"/>'+
'	<param name="quality" value="high"/>'+
'	<param name="wmode" value="transparent"/>'+
'</object>'
);
}

// return the value of the radio button that is checked
// return an empty string if none are checked, or
// there are no radio buttons
function getCheckedRadioValue(radioObj)
{
	if(!radioObj)
	{
		return "";
	}
	var radioLength = radioObj.length;
	if(radioLength == undefined)
	{
		if(radioObj.checked)
		{
			return radioObj.value;
		}
		else
		{
			return "";
		}
	}
	for(var i = 0; i < radioLength; i++)
	{
		if(radioObj[i].checked)
		{
			return radioObj[i].value;
		}
	}
	return "";
}

/***	AJAX Functions	***/
// Sample: ajaxPost("HndXTValuation", qString, updateStreetStatus);
function ajaxPost(url, qString, callBackMethod)
{
	try
	{
		request = getXmlHttpObject();
		if (request)
		{
			request.open("POST", url, true);
			if (callBackMethod)
			{
				request.onreadystatechange = callBackMethod;
			}
			request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
			// Make sure the server doesn't return a cached page
			request.send("sid=" + Math.random() + "&" + qString);
		}
	}
	catch (ex)
	{
		alert(ex);
	}
}

function getXmlHttpObject()
{
	var request = null;
	try
	{
		request = new XMLHttpRequest();
	}
	catch (trymicrosoft)
	{
		try
		{
			request = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (othermicrosoft)
		{
			try
			{
				request = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (failed)
			{
				request = null;
			}
		}
	}
	return request;
}

function updateScreenSize()
{
	var screenWidth = window.screen.availWidth;
	var screenHeight = window.screen.availHeight;
	var qString="screenWidth=" + screenWidth + "&screenHeight="+screenHeight;
	ajaxPost("HndValuation", qString, null);
}


/***	END: AJAX Functions	***/

function doAfterOnload()
{
	updateAddressLook();
	USER_WIN_WIDTH = getClientWindowWidth();
	// Do page specific things by adding the function below to your page
	doAfterOnloadPageSpecific();
	return;
}

function doAfterOnloadPageSpecific()
{
	// Override me if needed
}

function removeInvalidChars(obj)
{
	var value = obj.value;
	var name = obj.name;
	var newValue = "";
	
	var cmcname = obj.name.substring(2);
	
	for (var valIndex = 0; valIndex < value.length; valIndex++)
	{
		var currNumber = parseInt(""+value.charAt(valIndex));
		//alert("currNumber: " + currNumber);
		if (currNumber == "0" || (!isNaN(currNumber) && currNumber != ""))
		{
			//alert("going to add it");
			newValue += currNumber;
		}
		else if ((name == "XT_AVG_INT_HEIGHT" || cmcname == "XT_COMMERCIAL_NUM_STORIES") && ""+value.charAt(valIndex) == ".")
		{
			//this question is a type count, even though it really shouldn't be.
			newValue += ".";
		}
		//alert(" newValue so far: " + newValue);
		
	}
	
	if (newValue == "")
	{
		newValue = ZEROVAL;
	}
	
	obj.value = newValue;		
}



function addFakeOption(isAnswered, selObj, fakeText, fakeValue, fakeIndex, replaceRealOptionIfAnswered)
{
	var selText = new Array();
  	var selValue = new Array();
  	var selIsSel = new Array();  	
	var oldSize = selObj.length;
		
	for (var i = 0; i < oldSize; i++)
	{
		selText[i] = selObj[i].text;
		selValue[i] = selObj[i].value;
		selIsSel[i] = selObj[i].selected;		
	}
	//alert("name: " + selObj.name + " isAnswered: " + isAnswered + " fakeText: " + fakeText + " fakeValue: " + fakeValue + " fakeIndex: " + fakeIndex + " replace: " + replaceRealOptionIfAnswered);
	if (isAnswered)
	{	
		if (replaceRealOptionIfAnswered)
		{			
			selObj.options[0] = new Option(fakeText, fakeValue);
			selObj.options[0].selected = selIsSel[0];
		}
		setExplicit(selObj);
	}
	else
	{
		// If it hasn't been answered yet we want both the none and blank answers there
		selObj.options[fakeIndex] = new Option(fakeText, fakeValue);
	
		var newSize = oldSize + 1;
		var startIndex = fakeIndex + 1;
		for (var i = startIndex; i < newSize; i++)
		{
			var oldIndex = i - 1;
			selObj.options[i] = new Option(selText[oldIndex], selValue[oldIndex]);
			//selObj.options[i].selected = selIsSel[oldIndex];
		}
	}
	
	
}

var answerFunction;
function xtolConfirm(header, text, button0, button1, button2, width, height, callBackFunction) 
{
	if (null != header)
	{
		var headerTD = document.getElementById("confirmBoxHeader");
		headerTD.innerHTML = header;
	}

	if (null != text)
	{
		var textTD = document.getElementById("confirmText");
		textTD.innerHTML = text;
	}
	
	if (null != button0)
	{
		var btn0 = document.getElementById("confirmButton0");
		var btnTD0 = document.getElementById("confirmButtonTD0");
		btnTD0.style.display = "block";
		btn0.innerHTML = button0;
	}
	if (null != button1)
	{
		var btn1 = document.getElementById("confirmButton1");
		var btnTD1 = document.getElementById("confirmButtonTD1");
		btnTD1.style.display = "block";
		btn1.innerHTML = button1;
	}
	if (null != button2)
	{
		var btn2 = document.getElementById("confirmButton2");
		var btnTD2 = document.getElementById("confirmButtonTD2");
		btnTD2.style.display = "block";
		btn2.innerHTML = button2;
	}
	
	answerFunction = callBackFunction;

	width = width.replace("px", "");
	height = height.replace("px", "");
	var box = document.getElementById("confirmBox");
	box.style.visibility = "visible";
	box.style.width = width + "px";
	box.style.height = height + "px";
	
	var x = (document.body.clientWidth/2) - (width/2);
	var y = (document.body.clientHeight/2) - (height/2);
	
	box.style.left = x + "px";
	box.style.top = y + "px";
	
}


function setConfirmAnswer(response) 
{
	document.getElementById("confirmBox").style.visibility="hidden";
	document.getElementById("confirmButtonTD0").style.display = "none";
	document.getElementById("confirmButtonTD1").style.display = "none";
	document.getElementById("confirmButtonTD2").style.display = "none";
	answerFunction(response);
}

function doMMManufacturerOnChange(selectObj, event)
{
	var retVal = true;
	if (!event) {event = window.event;}
	var selectVal = selectObj.options[selectObj.selectedIndex].value;
	var textObj = document.xtolform["XT_OTHER_MAN"];
	textObj.value = "";
	if ("XT_M_O" == selectVal)
	{
		changeToShow("MMManufacturerDiv");	
		textObj.focus();
		textObj.select();
		retVal = false;
	}
	else
	{
		var otherDiv = document.getElementById("MMManufacturerDiv");
		var isOtherFieldVisible = ("block" == otherDiv.style.display);
		changeToHideByElement(otherDiv);
		if (isOtherFieldVisible && getMSIEVersionNumber() == -1)
		{
			retVal = false;
			var nextCell = document.getElementById("sectionFollowingManufacturer");
			findFirstVisFormElement(document.getElementById("sectionFollowingManufacturer")).focus();
		}
	}
	return retVal; 
}

function addEvent(elm, evType, fn, useCapture)
// addEvent
// cross-browser event handling for IE5+,  NS6 and Mozilla
{
	if (elm && elm.addEventListener)
	{
		//alert("firefox event=["+elm+"]\n function=["+fn+"]");
		elm.addEventListener(evType, fn, useCapture);
		return true;
	}
	else if (elm && elm.attachEvent)
	{
		//alert("IE event=["+elm+"]\n function=["+fn+"]");
		var r = elm.attachEvent("on" + evType, fn);
		return r;
	}
}

function removeEvent(obj, evType, fn, useCapture)
{
	if (obj.removeEventListener)
	{
		obj.removeEventListener(evType, fn, useCapture);
		return true;
	}
	else if (obj.detachEvent)
	{
		var r = obj.detachEvent("on"+evType, fn);
		return r;
	}
}

function showHideOldHomeCheckbox(id, showMe, defaultMe)
{
	var shouldShowCheckbox = false;
	if (id == "WS") shouldShowCheckbox = shouldShowWSCheckbox();
	else if (id == "HW") shouldShowCheckbox = shouldShowHWCheckbox();
	//alert("id: " + id + " showMe: " + showMe + " defaultMe: " + defaultMe + " shouldShowCheckbox: " + shouldShowCheckbox);
	if (shouldShowCheckbox && showMe)
	{
		changeToShow(id + "_CHECKBOX");
	}
	else
	{
		changeToHide(id + "_CHECKBOX");
	}
}

// If the year built is older than 1956 and Aluminum or Vinyl Siding is selected as 
// an Exterior Wall Material then the "Wood Siding Underlayment" checkbox will appear.
// (used in worksheet, AI, and condo BWI...if you change the logic make sure fix showWSCheckbox(...) too)
// you will also want to fix the logic in ResidentialWidget.removeHiddenVals()
function shouldShowWSCheckbox()
{	
	var yearBuiltMeetsCriteria = false;	
	var yearBuilt = document.xtolform["XT_YEAR_BUILT"].value;
	if (!isNaN(parseInt(yearBuilt)))
	{
		yearBuiltMeetsCriteria = yearBuilt < 1956;
	}
	
	var ewfMeetsCriteria = false;
	var ewfCount = 0;
	while (typeof document.xtolform["SELECT_XTOLCOMBO_XTOL_EWF"+ewfCount] != 'undefined')
	{
		var ewfId = document.xtolform["SELECT_XTOLCOMBO_XTOL_EWF"+ewfCount].value;
		var ewfPercent = parseInt(document.xtolform["XTOLCOMBO_XTOL_EWF"+ewfCount].value);
		//alert("ewfId: " + ewfId + " ewfCount: " + ewfCount);
		if (!isNaN(ewfPercent) && ewfPercent > 0 && (ewfId == "XT_EWF_AL" || ewfId == "XT_EWF_VL"))
		{
			ewfMeetsCriteria = true;
			break;
		}
		ewfCount++; 
	}
	
	var functionalCostIsChecked = false;
	if  (typeof document.xtolform["XT_FUNCTIONAL_COST"] != 'undefined')
	{
		var functionalCost = parseInt(document.xtolform["XT_FUNCTIONAL_COST"].value)
		if (!isNaN(functionalCost) && functionalCost == 1)
		{
			functionalCostIsChecked = true;
		}
	}
	
	return yearBuiltMeetsCriteria && ewfMeetsCriteria && !functionalCostIsChecked;
	
}

// If the year built is older than 1941 and there is
// as least one fc that is not carpet over hardwood the is greater than 0 
// then the "Hardwood Sub-flooring" checkbox will appear
// (used in worksheet, AI, and condo BWI...if you change the logic make sure fix showHWCheckbox(...) too)
// you will also want to fix the logic in ResidentialWidget.removeHiddenVals()
function shouldShowHWCheckbox()
{
	var yearBuiltMeetsCriteria = false;	
	var yearBuilt = document.xtolform["XT_YEAR_BUILT"].value;
	if (!isNaN(parseInt(yearBuilt)))
	{
		yearBuiltMeetsCriteria = yearBuilt < 1941;
	}
	
	var fcMeetsCriteria = false;
	var fcCount = 0;
	while (typeof document.xtolform["SELECT_XTOLCOMBO_XTOL_FC"+fcCount] != 'undefined')
	{
		var fcId = document.xtolform["SELECT_XTOLCOMBO_XTOL_FC"+fcCount].value;
		var fcPercent = parseInt(document.xtolform["XTOLCOMBO_XTOL_FC"+fcCount].value);
		//alert("fcId: " + fcId + " fcPercent: " + fcPercent + " fcCount: " + fcCount);
		if (!isNaN(fcPercent) && fcPercent > 0 && fcId != "XT_FC_CPT_HW")
		{
			fcMeetsCriteria = true;
			break;
		}
		fcCount++; 
	}
	
	var functionalCostIsChecked = false;
	if  (typeof document.xtolform["XT_FUNCTIONAL_COST"] != 'undefined')
	{
		var functionalCost = parseInt(document.xtolform["XT_FUNCTIONAL_COST"].value)
		if (!isNaN(functionalCost) && functionalCost == 1)
		{
			functionalCostIsChecked = true;
		}
	}
	//alert("yearBuiltMeetsCriteria: " + yearBuiltMeetsCriteria + " fcMeetsCriteria: " 
	//	+ fcMeetsCriteria + " functionalCostIsChecked: " + functionalCostIsChecked);
	return yearBuiltMeetsCriteria && fcMeetsCriteria && !functionalCostIsChecked;
}

// (used in interview...if you change the logic make sure fix shouldShowHWCheckbox(...) too)
// you will also want to fix the logic in ResidentialWidget.removeHiddenVals()
function showHWCheckbox(id, showHWAppRight, functionalYearBuilt, carpetOverHardwoodPercentage)
{
	//alert("showHWCheckbox(id="+id+", showHWAppRight="+showHWAppRight+", functionalYearBuilt="+functionalYearBuilt+", carpetOverHardwoodPercentage="+carpetOverHardwoodPercentage+")");
	var yearBuiltMeetsCriteria = false;	
	if (!isNaN(parseInt(functionalYearBuilt)))
	{
		yearBuiltMeetsCriteria = functionalYearBuilt > 0 && functionalYearBuilt < 1941;
	}
	
	var carpetOverHW = 0;
	if (!isNaN(parseInt(carpetOverHardwoodPercentage)))
	{
		carpetOverHW = parseInt(carpetOverHardwoodPercentage);
	}
	
	if (showHWAppRight && yearBuiltMeetsCriteria && carpetOverHW < 100)
	{
		changeToShow(id);
	}
	else
	{
		changeToHide(id);
	}
}
// (used in interview...if you change the logic make sure fix shouldShowWSCheckbox(...) too)
// you will also want to fix the logic in ResidentialWidget.removeHiddenVals()
function showWSCheckbox(id, showWSAppRight, functionalYearBuilt, alSidingPercent, vlSidingPercent)
{
	//alert("showWSCheckbox(id="+id+", showWSAppRight="+showWSAppRight+", functionalYearBuilt="+functionalYearBuilt+", alSidingPercent="+alSidingPercent+", vlSidingPercent="+vlSidingPercent+")");
	var yearBuiltMeetsCriteria = false;	
	if (!isNaN(parseInt(functionalYearBuilt)))
	{
		yearBuiltMeetsCriteria = functionalYearBuilt > 0 && functionalYearBuilt < 1956;
	}
	
	var alSiding = 0;
	var vlSiding = 0;

	if (!isNaN(parseInt(alSidingPercent)))
	{
		alSiding = parseInt(alSidingPercent);
	}
	
	if (!isNaN(parseInt(vlSidingPercent)))
	{
		vlSiding = parseInt(vlSidingPercent);
	}
	
	if (showWSAppRight && yearBuiltMeetsCriteria && (vlSiding > 0 || alSiding > 0))
	{
		changeToShow(id);
	}
	else
	{
		changeToHide(id);
	}
}

function doWSCheck()
{
	// Override me if needed in jsp
}

function doHWCheck()
{
	// Override me if needed in jsp
}

function doEWFKeyPressed(event)
{
	if (!event) {event = window.event;}
	if(event.keyCode == 38 || event.keyCode == 40)
	{		
		doWSCheck();
	}
}

function doFCKeyPressed(event)
{
	if (!event) {event = window.event;}
	if(event.keyCode == 38 || event.keyCode == 40)
	{
		doHWCheck();
	}
}

/**
	This function returns a delimited list of checkbox values. It only returns
	the values of those checkboxes that are checked. Intended for multiple
	checkbox elements within one form with the same name.
	
	formName (String):  The name of the form to use. Errors if null.
	checkboxName (String):  The checkbox element name. Errors if null.
	delimiter (String):  The delimiter to insert between values. Defaults to a
	comma (",") if null or empty.
*/
function getDelimitedCheckboxCheckedValues(formName, checkboxName, delimiter)
{
	if (!delimiter)
	{
		delimiter = ",";
	}
	
	var retVal = "";
	var checkboxes = document.forms[formName][checkboxName];
	
	for (var i = 0; i < checkboxes.length; i++)
	{
		if (checkboxes[i].checked)
		{
			retVal += checkboxes[i].value + delimiter;
		}
	}

	//	Remove the trailing delimiter;	
	if (retVal != "")
	{
		retVal = retVal.substr(0, (retVal.length - delimiter.length));
	}

	//alert("getDelimitedCheckboxCheckedValues: retVal=["+retVal+"]");
	
	return retVal;
}


