// JavaScript Document
// This file contains functions that are used by multiple projects

/**
 * function to switch tabs.  right now this changes the look 
 * USED BY: the tabs in incTabs.shtml
 */
function switchTab(objTab) {
	//    a .  span    .  div
	//objTab.parentNode.parentNode.id;
	
	// change the body class to the id of the div
	document.body.className = objTab.parentNode.parentNode.id;
	// loose focus on the link
	objTab.blur();
	
	switch(objTab.id) {
		default:
		break;
	}
	
	if(objTab.id == "tab1") {
		
	}
}

/**
 * this function gets the x and y coordinates of any element 
 */
function getPageCoords (elementId) {
	var coords = {x: 0, y: 0}
	var element;

	/* if elementId is an object id use, get the object by id, else use the object */
	if(typeof elementId == "string") {
		/* it could be an ID */
		if (document.all)
			element = document.all[elementId];
		else if (document.getElementById)
			element = document.getElementById(elementId);
	} else {
		/* it is an object */
		element = elementId;
	}
	
	while (element) {
		coords.x += element.offsetLeft;
		coords.y += element.offsetTop;
		element = element.offsetParent;
	}
	return coords;
}

/**
 * trim all space to the left
 */
function ltrim(str) { 
	for(var k = 0; k < str.length && isWhitespace(str.charAt(k)); k++);
	return str.substring(k, str.length);
}

/**
 * trim all space to the right
 */
function rtrim(str) {
	for(var j=str.length-1; j>=0 && isWhitespace(str.charAt(j)) ; j--) ;
	return str.substring(0,j+1);
}

/**
 * trim all space on left and right
 */
function trim(str) {
	return ltrim(rtrim(str));
}

/**
 * check if the character is a whitespace
 */
function isWhitespace(charToCheck) {
	var whitespaceChars = " \t\n\r\f";
	return (whitespaceChars.indexOf(charToCheck) != -1);
}


/**
 * --GetObjectValue--
 * 	Get the value for the field identified by objID. The method for obtaining the value depends upon the
 * 	object's type.
 * 
 *  Parameters:
 * 			objID - Element ID of the field for which the value is to be obtained
 * 
 *  Returns:
 * 			Value of the field
*/
function GetObjectValue(objID) {
	var value = "";
	
	var element = document.getElementById(objID);

	// check that the element.id and objID are equal. If IE can't find an ID then it looks at name but we check for name later
	if (element != null && element.id == objID) { 
		switch (element.type) {
			case "checkbox":
			case "radio":
				//alert('checkbox/radio: ' + element.id);
				value = element.checked;
				break;
			case "text":
			case "textarea":
			case "password":
			case "hidden":
			case "file":
				//alert('text/textarea/password/hidden/file: ' + element.id);
				value = element.value;
				break;
			case "select-one":
				//alert('select-one: ' + element.id + " : length = " + element.options.length);
				if (element.options.length > 0) {
				   value = element.options[element.selectedIndex].value;
				}
				if(value == "" && element.selectedIndex != 0) {
				   value = element.options[element.selectedIndex].text;
				}
				break;
			case "select-multiple":
				//alert('select-multiple: ' + element.id + " : length = " + element.options.length);
				value = '|';
				for (j = 0; j < element.options.length; j++) {
				  if (element.options[j].selected) {
					value += element.options[j].text + "|";
				  }
				}
				if (value == '|') {
					value = '';
				}
				break;
		}
	}
	// element doesn't exist or objID = radio/checkbox name
	else {
		var els = document.getElementsByName(objID);
		
		// els exists
		if(els.length > 0) {
			// if radio
			if(els[0].type == "radio") {
				for(var i = 0; i < els.length; i++) {
					if(els[i].checked) return els[i].value;
				}
			}
			// if checkbox
			else if(els[0].type == "checkbox") {
				var vals = "";
				for(var i = 0; i < els.length; i++) {
					if(els[i].checked) {
						vals += els[i].value + ",";
					}
				}
				
				if(vals.substring(vals.length-1,vals.length) == ",") {
					vals = vals.substring(0,vals.length-1);
				}
				
				return vals;
			}
		}
	}
	
	return value;
}


/**
 * --SetObjectValue--
 * 	Set the value for the field identified by objID. The method for setting the value depends upon the
 * 	object's type.
 * 
 * 	Parameters:
 * 			objID - Element ID of the field for which the value is to be set
 * 
 * 	Returns:
 * 			nothing
 */
function SetObjectValue(objID, value) {
	
	var element = document.getElementById(objID);
	if (element != null) {
		switch (element.type) {
			case "checkbox":
			case "radio":
				//alert('checkbox/radio: ' + element.id);
				element.value = value;
				break;
			case "text":
			case "textarea":
			case "password":
			case "hidden":
			case "file":
				//alert('text/textarea/password/hidden/file: ' + element.id);
				element.value = value;
				break;
			case "select-one":
				//alert('select-one: ' + element.id + " : length = " + element.options.length);
				for (var i=0; i<element.options.length; i++) {
						if(element.options[i].value == value || element.options[i].text.toLowerCase() == value.toLowerCase()) {
							element.selectedIndex = i;
						}
				    //value = element.options[element.selectedIndex].value;
				}
				break;
				/*
			case "select-multiple":
				//alert('select-multiple: ' + element.id + " : length = " + element.options.length);
				value = '|';
				for (j = 0; j < element.options.length; j++) {
				  if (element.options[j].selected) {
					value += element.options[j].text + "|";
				  }
				}
				if (value == '|') {
					value = '';
				}
				break;
				*/
		}
	}
	
	return value;
}


/**
 * get the numerical value of a month
 */
function getMonthNum(p_month) {
	switch(p_month.toLowerCase()) {
		case "jan":
			return 0;
		case "feb":
			return 1;
		case "mar":
			return 2;
		case "apr":
			return 3;
		case "may":
			return 4;
		case "jun":
			return 5;
		case "jul":
			return 6;
		case "aug":
			return 7;
		case "sep":
			return 8;
		case "oct":
			return 9;
		case "nov":
			return 10;
		case "dec":
			return 11;
		default:
			return -1;
	}
}

/**
 * get the string value for a month given a number
 */
function getMonthStr(p_month) {
	switch(p_month) {
		case 0:
			return "Jan";
		case 1:
			return "Feb";
		case 2:
			return "Mar";
		case 3:
			return "Apr";
		case 4:
			return "May";
		case 5:
			return "Jun";
		case 6:
			return "Jul";
		case 7:
			return "Aug";
		case 8:
			return "Sep";
		case 9:
			return "Oct";
		case 10:
			return "Nov";
		case 11:
			return "Dec";
		default:
			return -1;
	}
}


/**
 * set a cookie
 */
function setCookie(c_name,value,expire_mins)
{
	var expires = null;
	
	if(expire_mins) {
		var exdate=new Date();
		//exdate.setDate(exdate.getDate()+expiredays);
		exdate.setTime(exdate.getTime()+ (expire_mins*60*1000));
		expires = ";expires="+exdate.toGMTString();
	}
	
	document.cookie=c_name + "=" + escape(value)+((expires==null) ? "" : expires);
}


/**
 * get the value of a cookie
 */
function getCookie(c_name)
{
	if (document.cookie.length>0)
		{
			c_start=document.cookie.indexOf(c_name + "=");
			if (c_start!=-1)
				{ 
					c_start=c_start + c_name.length+1;
					c_end=document.cookie.indexOf(";",c_start);
					if (c_end==-1) 
						c_end=document.cookie.length;
					return unescape(document.cookie.substring(c_start,c_end));
				} 
		}
	return "";
}

/**
 * stripe tables
 */
function stripe(sTable) {
	/* recolor here */
	if (typeof sTable == "string") {
		sTable = document.getElementById(sTable);
	}
	
	// check if the table is defined before continuing
	if(sTable != undefined) {
		var row = null;
		
		// counter for visible rows
		var vr = 0;
		
		// go through each row in the table
		for(var i=0; i<sTable.getElementsByTagName("TBODY")[0].rows.length; i++) {
			row = sTable.getElementsByTagName("TBODY")[0].rows[i];
			if(i == 0) {
				prevRow = row;
			} else {
				prevRow =	sTable.getElementsByTagName("TBODY")[0].rows[i-1];
			}

			spanningRow = false;
			groupedRow = false;
			
			// compare row IDs
			if(row.id.length > 0 && prevRow.id.length > 0) {
				hLocR = row.id.indexOf("-");
				hLocP = prevRow.id.indexOf("-");
				if(row.id.substring(0,hLocR) == prevRow.id.substring(0,hLocP)) {
					groupedRow = true;
					if(vr == 0) vr=1;
					//alert(row.id.substring(0,hLocR) + "\n" + prevRow.id.substring(0,hLocP) + "\n#" + groupedRow);
				}
			}
		
			//	alert(row.childNodes[1].attributes.getNamedItem("colspan").value + "//" + row.childNodes[1].innerHTML);

			//	if(row.childNodes[0].hasAttribute && row.childNodes[0].hasAttribute("colspan")) {
			if(row.childNodes[0].nodeName != "#text") {
				if(row.childNodes[0].attributes.getNamedItem("colspan").value > 1 ) { //&& prevRow.childNodes[0].attributes.getNamedItem("colspan").value == 1
					spanningRow = true;
				} else {
					spanningRow = false;
				}
			} else if(row.childNodes[1].hasAttribute("colspan")) { // && !prevRow.childNodes[1].hasAttribute("colspan")
					spanningRow = true;
				} else {
					spanningRow = false;
			}


			// check if the row is visible... don't want to stripe invisible rows
			if(row.style.display != "none" && !spanningRow && !groupedRow) {
				vr++;
				// if the row index is even, set the row class to the even
				if(vr % 2 == 0) {
					row.className = "evenRow";
				}
				else
				{
					row.className = "oddRow";
				}		
			}	else if(spanningRow || groupedRow) {
					row.className = prevRow.className;
			}
			
		} // end for loop
	}
}

/**
 * Places a div behind a mouseover to hide selects in IE
 */
function activecontentHider(id) {

	//if (ie) {
	el = document.getElementById(id);
	if(!document.getElementById(id+"dummyFRM")) {
		ifrm = document.createElement("IFRAME");
		ifrm.setAttribute("id", id+"dummyFRM");
		ifrm.setAttribute("src", "#");
		ifrm.setAttribute("scroll", "yes");
		ifrm.setAttribute("frameborder", "0");
		ifrm.allowtransparency="false";
		ifrm.style.position = "absolute";
		//ifrm.style.setAttribute("visibility", "hidden");
		//ifrm.style.filter='Alpha(opacity=0)';
		ifrm.style.width = el.offsetWidth + "px";
		ifrm.style.height = el.offsetHeight + "px";
		ifrm.style.left = el.offsetLeft + "px";
		ifrm.style.top = el.offsetTop + "px";
		el.style.zIndex = 5000;
		ifrm.style.zIndex = el.style.zIndex-1;
		document.body.appendChild(ifrm);
	} else {
		document.getElementById(id+"dummyFRM").style.display = "";
	}
	//}
}	



/* ============================================================================ */
/* hideShowSelects()                                                            */
/*   This function hides or shows selects if they are behind divId.  The        */
/*   function loops through all the 'select' tags on the page and checks to see */
/*   four values: tl - top left                                                 */
/*                tr - top right                                                */
/*                bl - bottom left (*default)                                   */
/*                br - bottom right                                             */
/*                                                                              */
/*   The divId parameter can be either a string containing a single div id or   */
/*   it can be an array of div ids. Selects are hidden/shown depending on their */
/*   proximity to all of the div ids that are passed in.
/* ============================================================================ */
function hideShowSelects(divIds) {
	var divs = new Array();
	var divXs = new Array();
	var divYs = new Array();
	var divWs = new Array();
	var divHs = new Array();
	
	useLoop = true;
	if (typeof divIds == "string") {
		divs[divs.length] = divIds;
	} else if(isArray(divIds)) {
		divs = divIds;
	} else {
		divXs[0] = divIds.style.pixelLeft;
		divYs[0] = divIds.style.pixelTop;
		divWs[0] = divIds.offsetWidth;
		divHs[0] = divIds.offsetHeight;		
		useLoop = false;
	}
	
	if(useLoop) {
		for (var i = 0; i < divs.length; i++) {
			// x, y, w, h of the layer covering the selects
			divXs[i] = document.getElementById(divs[i]).style.pixelLeft;
			divYs[i] = document.getElementById(divs[i]).style.pixelTop;
			divWs[i] = document.getElementById(divs[i]).offsetWidth;
			divHs[i] = document.getElementById(divs[i]).offsetHeight;
			//alert("divs[" + i + "]" + divs[i] + ":" + divXs[i] + ":" + divYs[i] + ":" + divWs[i] + ":" + divHs[i]);
		}
	}

	var selects = document.getElementsByTagName("select");
	var coords;
	
	if(selects.length > 0) {
		for(var i=0; i<selects.length; i++) {

			var selCovered = false;

			for (var j = 0; (j < divs.length) && (! selCovered); j++) {
				// coords is the position of the select
				coords = getPageCoords(selects[i]);
				selX1 = coords.x;
				selX2 = coords.x + selects[i].offsetWidth;
				selY1 = coords.y;
				selY2 = coords.y + selects[i].offsetHeight;
				//alert("selects[" + i + "]" + selects[i].name + ":" + selX1 + ":" + selX2 + ":" + selY1 + ":" + selY2);
				
				var Xcovered = false;
				var Ycovered = false;

				if (Xcovered || (divXs[j] <= selX1 && selX1 <= (divXs[j]+divWs[j]))
							 || (divXs[j] <= selX2 && selX2 <= (divXs[j]+divWs[j]))
							 || (selX1 <= divXs[j] && (divXs[j]+divWs[j]) <= selX2)) {
					Xcovered = true;
				}
				if (Ycovered || (divYs[j] <= selY1 && selY1 <= (divYs[j]+divHs[j]))
							 || (divYs[j] <= selY2 && selY2 <= (divYs[j]+divHs[j]))
							 || (selY1 <= divYs[j] && (divYs[j]+divHs[j]) <= selY2)) {
					Ycovered = true;
				}
				
				selCovered = (Xcovered && Ycovered);
			} // end for(var j

			// if any part of the select was covered, hide it
			if (selCovered) {
				selects[i].style.visibility = "hidden";
			} else {
				// make this select visible again if it was previously hidden
				if(selects[i].style.visibility == "hidden") {
					selects[i].style.visibility = "visible";
				}
			} // end if(selCovered
		} // end for(var i
	} // end if(selects.length		
} // end function


/**
 * go to a URL
 */
function MM_goToURL() { //v3.0
  var i, args=MM_goToURL.arguments; document.MM_returnValue = false;
  for (i=0; i<(args.length-1); i+=2) eval(args[i]+".location='"+args[i+1]+"'");
}

function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

function isArray(obj){return(typeof(obj.length)=="undefined")?false:true;}


/**
 * get the numerical value of a month
 */
function setupTextfieldMasking(theEvent) {
	// get the event type
	evtType = theEvent.type;
	// get the source of the event.  this is usually the textbox
	evtObj = (theEvent.srcElement) ? theEvent.srcElement : theEvent.target;
	// get the value of the textbox
	objVal = GetObjectValue(evtObj.id);

	// onFocus.
	if(evtType == "focus") {
		// if the field is empty or equal to the title of the field, 
		// clear the field and set the text color to black when the 
		// users sets focus to the textbox to enter text
		if(objVal == "" || objVal == evtObj.title) {
			evtObj.className = "textFieldFilled";
			evtObj.value = "";
		}
	}
	// onBlur
	else if(evtType == "blur") {
		// when the textbox looses focus, set the value to the same value
		// of the title if the user empties the textbox
		if(objVal == "" || objVal == evtObj.title) {
			evtObj.className = "textFieldEmpty";
			evtObj.value = evtObj.title;
		} 			
	}
}


function fillInValues(form, grpName) {
/*
	- go through and see if row should be edited
	- go through columns and fill in data
*/
	if(typeof form == "string") {
		formLen = document.getElementById(form).elements.length;
		formObj = document.getElementById(form);
	} else {
		formLen = form.elements.length;
		formObj = form;
	}

	//lineItemColumns : array declared in main page
	
	for(var i=0; i < formLen; i++) {
		for(var j=0; j < lineItemColums.length; j++) {
			if(formObj.elements[i].id == lineItemColums[j]) {
				// starting number for checkboxes
				var c=1;
				var cbid = lineItemColums[j]+c;
				var countChecked = 0;
				while(document.getElementById(lineItemColums[j]+c) != null) {
					//alert(lineItemColums[j]+c);
					cbid = grpName + c;
					// check if the checkbox is selected
					if(document.getElementById(cbid).checked == true) {
						SetObjectValue(lineItemColums[j]+c, formObj.elements[i].value);
					} // end if
					
					c++;
				}	 // end while
			} // end if(formObj
		} // end for(var j=0
	}	// end for(var i=0
							
	return false;
} // end function



// used to minimize/restore portal
// imgObj = this  #the image object
function resizeMe(imgObj,openClose) { // openClose added by JFK
	var imgObj2 = new Object();
	imgObj2.elNode = imgObj;
		
	// boolean to determine if we have to create the div to hold the elements
	var contExists = false;

	// search for div above image
	while(imgObj2.elNode.parentNode.tagName != "DIV" && imgObj2.elNode.parentNode.tagName != "BODY") {
		imgObj2.elNode = imgObj2.elNode.parentNode;
	}
	
	// get the image's parent node (the DIV)
	var obj= imgObj2.elNode.parentNode;

	var resObj;
	
	// check to see if the container exists
	for(i=0; i<obj.childNodes.length; i++) {
		if(obj.childNodes[i].tagName == "DIV" && obj.childNodes[i].id.substring(0,20) == "sectionDivContainer_") {
			contExists = true;
			resObj = obj.childNodes[i];
		}
	}
	
	
	
	// check if the table is in the resize div
	// if parent of image and parent of table are not the same
	if(contExists == false) {
		resObj = document.getElementById(putElementsInDiv(obj));
	}
	

	/* This block checks to see if the icon used to shrink or expand the section is the "small version". If so, it sets a flag
			which gets used to determine what images to swap when the resize is performed immediately below */
	var lastSlash = imgObj.src.lastIndexOf("/");
	var iconImagefileName = imgObj.src.substring(lastSlash+1,imgObj.src.length);
	var smallIconFlag;
	if (iconImagefileName.indexOf('Small') > -1) {   // If the image is a small icon (must have 'Small' in the image filename)
		flagSmallIcon=true;
	}
	else {
		flagSmallIcon=false;
	}
	
	
	// do resize
	if((openClose=="open") || ((openClose != "close") && (resObj.style.display)) == "none") {
		resObj.style.display = "block";
		if (flagSmallIcon) {imgObj.src = "images/iconMinSmall.gif"}
		else {imgObj.src = "images/iconMin.gif"}
	} else {
		resObj.style.display = "none";
		if (flagSmallIcon) {imgObj.src = "images/iconMaxSmall.gif"}
		else {imgObj.src = "images/iconMax.gif"}
	}	
}

// put the table in a div... used with resizeMe()
function putElementsInDiv(obj) {
	// create div container
	var parDiv = document.createElement("div");
	// set the id
	var idsuffix=obj.id // JFK 20060606
	if (!idsuffix) { closeablePortletDivSeq++;idsuffix=closeablePortletDivSeq} // JFK 20060606
	
	parDiv.id = "sectionDivContainer_" + idsuffix; // JFK 20060606 (idsuffix was obj.id)
	// start adding after finding the span with the buttons
	var spanFound = false;
	// go through all the child nodes
	for(i=0; i<obj.childNodes.length; i++) {
		//alert(obj.id + "\\" + obj.childNodes[i].tagName + "//" + obj.childNodes[i].id);		
		// if we've found the first span (the one containing the buttons), continue
		if(spanFound == false && obj.childNodes[i].tagName == "SPAN") {
			// go through all remaining objects from the bottom up
			for(j=obj.childNodes.length-1; j>i; j--) {
				//alert(obj.id + "//" + obj.childNodes[j].tagName + "//" + obj.childNodes[j].id);		
				// add the first node
				if(parDiv.childNodes.length == 0) {
					parDiv.appendChild(obj.childNodes[j]);	
				} else {
					// insert remaining nodes before the first one
					parDiv.insertBefore(obj.childNodes[j],parDiv.childNodes[0]);	
				}
			}
			// done
			break;
		}		
	}	
	// add this div
	obj.appendChild(parDiv);	
	
	return parDiv.id;
}

// Added by Jim on 5/24/2007. Use to simulate a delay for the system to "respond"
// Set value of function call to number of milliseconds to delay 
function pauseHere(ms) 
{
	var date = new Date();
	var curDate = null;
	
	do { curDate = new Date(); } 
	while(curDate-date < ms);
} 


function setupAccessKeys(p_accessElements) {
	for(var i=0; i < p_accessElements.length; i++) {
		var elementId = p_accessElements[i][0];
		var elem = document.getElementById(elementId);
		var akey = p_accessElements[i][1];
		
		var lbl = findLabelFor(elementId);
		
		// modify the label for the field
		if(lbl != null) {
			var regexI = new RegExp(akey,"i");
			var regexS = new RegExp(akey);
			
			if(lbl.innerHTML.indexOf(akey) >= 0) {
				lbl.innerHTML = lbl.innerHTML.replace(regexS,"<span class=\"accesskey\">" + akey + "</span>");
			} else if (lbl.innerHTML.search(regex) >= 0) {
				lbl.innerHTML = lbl.innerHTML.replace(regexI,"<span class=\"accesskey\">" + akey.toUpperCase() + "</span>");
			}
		} 
		// if the element is a label, modify the text
		else if(elem.tagName == "A") {
			var regex = new RegExp(akey,"i");
			
			if(elem.innerHTML.indexOf(akey) >= 0) {
				elem.innerHTML = elem.innerHTML.replace(regex,"<span class=\"accesskey\">" + akey + "</span>");
			} else if (elem.innerHTML.search(regex) >= 0) {
				elem.innerHTML = elem.innerHTML.replace(regex,"<span class=\"accesskey\">" + akey.toUpperCase() + "</span>");
			}
		}
		
		var at = document.createAttribute("accesskey");
		at.value = akey;
		
		aa = "";
		if(elem.attributes.getNamedItem("accesskey") != null)
			aa = elem.attributes.getNamedItem("accesskey").value;
		
		str1 = aa + "/" + elementId + "/" + akey;
		//document.getElementById(elementId).accessKey = akey;
		elem.attributes.setNamedItem(at);

		if(elem.attributes.getNamedItem("accesskey") != null)
			aa = elem.attributes.getNamedItem("accesskey").value;
		str2 = aa + "/" + elementId + "/" + akey;		
		
		//alert(str1 + "\n" + str2);
		//document.getElementById(elementId).setAttribute("accesskey",accesskey);
	}
}

function findLabelFor(p_elementId) {
	var allLabels = document.getElementsByTagName("label");

	for(var i=0; i < allLabels.length; i++) {
		//alert(allLabels[i].getAttribute("for") + "/" + p_elementId + "/" + allLabels[i].attributes.getNamedItem("for").value);
		
		if(allLabels[i].attributes.getNamedItem("for") && allLabels[i].attributes.getNamedItem("for").value == p_elementId)
			return allLabels[i];
	}
	
	return null;
}

function whatkey(e,sectionIds) {
	var keyPressedCode = (window.event) ? event.keyCode : e.keyCode;
	var objWithFocus =  (window.event) ? event.srcElement : e.target;
	var shiftPressed =  (window.event) ? event.shiftKey : e.shiftKey;
	var ctrlPressed = (window.event) ? event.ctrlKey : e.ctrlKey;
	
	// remove any hidden sections from the list
	if(sectionIds && sectionIds.length > 0) {
		for(var i=sectionIds.length-1; i >= 0; i--) {
			if(document.getElementById(sectionIds[i]).style.display == "none") {
				sectionIds.splice(i,1);
			}
		}
	}
	
	switch (keyPressedCode) {
		case 113 : // F2

			if(shiftPressed) {
				// find out which one is selected
				var selectedArea = null;
				var i=0;
				for(i=sectionIds.length-1; i >= 0; i--) {
					var anArea = document.getElementById(sectionIds[i]);
					
					//alert(objWithFocus.tagName);
					if(anArea.className.indexOf("selectedArea") >= 0) {
						anArea.className = anArea.className.replace(/selectedArea/,"");
						objWithFocus.blur();
						//blurAll(anArea);
						break;
					}
				}
				
				// highlight next div
				if(i == 0) {
					i = sectionIds.length;
				}
				
				i--;
			} else {
			
				// find out which one is selected
				var selectedArea = null;
				var i=0;
				for(i=0; i<sectionIds.length; i++) {
					var anArea = document.getElementById(sectionIds[i]);
					
					//alert(objWithFocus.tagName);
					if(anArea.className.indexOf("selectedArea") >= 0) {
						anArea.className = anArea.className.replace(/selectedArea/,"");
						objWithFocus.blur();
						//blurAll(anArea);
						break;
					}
				}
				
				// highlight next div
				if(i == sectionIds.length || i == sectionIds.length -1) {
					i = -1;
				}
				
				i++;
			}
			
			//alert(i);
			var anArea = document.getElementById(sectionIds[i]);
			//alert(anArea + "/" + sectionIds[i+1]);
			
			anArea.className = anArea.className + " selectedArea";
			if(anArea.childNodes.length > 0) {
				getFocus(anArea);
			} else 
				anArea.focus();
			
			break;
		case 119 : // F8
		
			break;	
		case 120 : // F9
		
			break;		
		case 123 : // F12
		
			break;
		case 32 : // space
			if(ctrlPressed) {				
				if(document.getElementById("carRental") == null) {											   
					var cell_d2 = document.createElement("DIV");
					cell_d2.style.position = "absolute";
					cell_d2.style.top = 0;
					cell_d2.style.left = 0;
					cell_d2.id = "carRental";
					cell_d2.style.width = "100%";
					cell_d2.style.height = "1000px";	
					cell_d2.style.backgroundColor = "#000000";	
					cell_d2.style.textAlign = "center";	
					cell_d2.style.zIndex = "5000";
					
					var img = document.createElement("IMG");
					img.src = "images/car.jpg";
					img.border = 1;
					cell_d2.appendChild(img);
					
					//cell_d2.innerHTML = "<img src=\"images/car.jpg\">";
					document.body.appendChild(cell_d2);
			   } else if (document.getElementById("carRental").style.display == "none"){
					document.getElementById("carRental").style.display = "";
			   } else {
					document.getElementById("carRental").style.display = "none";
			   }
			}
			break;
	}
}

function blurAll(obj, counter) {
	//obj.blur();
	if(counter == null || counter < 0) {
		counter = 0;
	}
	document.getElementById("textareaQuickPad").value += counter + "/" + obj.tagName + "/" + obj.id + "\n";
	if(obj.childNodes != null && obj.childNodes.length > 0) {
		for(i=0; i<obj.childNodes.length; i++) {
			if(counter > 5) 
				{
					alert("breaking");
					break;
				}

			blurAll(obj.childNodes[i], ++counter);
		}
	}
}

function getFocus(obj, p_found) {
	if(p_found != true) {
		found = false;

		if(obj.tagName == "TEXTAREA" || obj.tagName == "INPUT" || obj.tagName == "A") {
			obj.focus();
			//alert("obj " + obj.id + " has focus");
			return true;
		} else {
			//alert(obj.childNodes.length + "/" + obj.tagName);
			for(var i=0; i<obj.childNodes.length; i++) {
				if(obj.childNodes[i].tagName == "TEXTAREA" || obj.childNodes[i].tagName == "INPUT" || obj.childNodes[i].tagName == "A") {
					//alert(i + "/" + obj.childNodes[i].tagName + "/" + obj.childNodes[i].id);
					obj.childNodes[i].focus();
					//alert("calling func with " + obj.id + "/" + obj.tagName);
					found = true;
					break;
				}
				getFocus(obj.childNodes[i], found);	
			}
		}
	}
}

document.onkeyup = function(e) {
		whatkey(e);
	}	
	
	
function addClassName(el, sClassName) {
	var s = el.className;
	var p = s.split(" ");
	var l = p.length;
	for (var i = 0; i < l; i++) {
		if (p[i] == sClassName)
			return;
	}
	p[p.length] = sClassName;
	el.className = p.join(" ").replace( /(^\s+)|(\s+$)/g, "" );
}

function removeClassName(el, sClassName) {
	var s = el.className;
	var p = s.split(" ");
	var np = [];
	var l = p.length;
	var j = 0;
	for (var i = 0; i < l; i++) {
		if (p[i] != sClassName)
			np[j++] = p[i];
	}
	el.className = np.join(" ").replace( /(^\s+)|(\s+$)/g, "" );
}

function hasClassName(el, sClassName) {
	var hasClass = false;
	var s = el.className;
	var p = s.split(" ");
	var np = [];
	var l = p.length;
	var j = 0;
	for (var i = 0; i < l; i++) {
		if (p[i] == sClassName)
			hasClass = true;
	}
	
	return hasClass;
}

// Adds events to objects... more details soon
function addEvent(elem, evType, func, useCapture) { 
	// check if the element is a string.  if it is, get the object associated with that id
	if (typeof elem == "string") {
		elem = document.getElementById(elem);
	}
	
	// check if event type includes "on" (ie onClick). if it does, remove it.
	if(evType.substring(0,2) == "on") {
		evType = evType.substring(2,evType.length);
	}
	
	// now continue if there is an element 
	if(elem) {
		if( elem.addEventListener ) { // Marlon: the W3C DOM approach window.alert("W3C approach");
			elem.addEventListener(evType, func, useCapture); return true; 
		} else if( elem.attachEvent ) { // Marlon: the IE DOM approach window.alert("IE approach"); 
			var r = elem.attachEvent("on" + evType, func); return r; 
		} else { // Marlon: Simon's approach window.alert("Simon's approach"); 
			var onEvt = "on" + evType; 
			var elOldEvFuncs = elem; 
			if( (typeof elem[onEvt]) != 'function' ) { 
				elem[onEvt] = func; 
			} else { 
				elem[onEvt] = function() { 
												elOldEvFuncs(); 
												func(); 
											} 
			} 
		} // end if(elem.addEventListener)
	} // end if(elem)
}	// end function

// removes an event from an object
function removeEvent(elem, evType, func, useCapture) {
	// check if the element is a string.  if it is, get the object associated with that id
	if (typeof elem == "string") {
		elem = document.getElementById(elem);
	}
	
	// check if event type includes "on" (ie onClick). if it does, remove it.
	if(evType.substring(0,2) == "on") {
		evType = evType.substring(2,evType.length);
	}
	
	// now continue if there is an element 
	if(elem) {
		if( elem.removeEventListener ) { // Marlon: the W3C DOM approach window.alert("W3C approach");
			elem.removeEventListener(evType, func, useCapture); return true; 
		} else if( elem.detachEvent ) { // Marlon: the IE DOM approach window.alert("IE approach"); 
			var r = elem.detachEvent("on" + evType, func); return r; 
		} // end if(elem.removeEventListener)
	} // end if(elem)	
}


function toggleCBs(startsWith,p_cb) {
	if(p_cb != null) {
		cb = p_cb;
	} else {
		cb = document.getElementById(startsWith);
	}
 	if (cb.checked == true) {
		checkCBs(startsWith);
 	}
 	else {
		unCheckCBs(startsWith);
 	}
}

/* this function goes through checkboxes that start with grpName and end in a number and unchecks them
   for example if grpName equals cb then the first check box should be cb1.  The function will try to get
   cb2, cb3, etc. until it reaches an item that does not exists.
   */
function unCheckCBs(grpName) {
	var i = 1;
	do {
		var cb = document.getElementById(grpName+i);
		if (cb != null) {
			if (cb.checked) {
				cb.click();
			}
			i++;
		}
	} while (cb != null);
}

function checkCBs(grpName) {
	var i=1;
	
	var cbid = grpName+i;
	while(document.getElementById(grpName+i) != null) {
		cbid = grpName + i;
		//document.getElementById(cbid).checked = true;
		if(document.getElementById(cbid).checked == false) {
			document.getElementById(cbid).click();
		}
		
		i++;
	}
}

/**
 * Query string
 */ 
function qs() {
	var qsParm = new Array();
	
	var query = window.location.search.substring(1);
	var parms = query.split('&');
	for (var i=0; i<parms.length; i++) {
		var pos = parms[i].indexOf('=');
		if (pos > 0) {
			var key = parms[i].substring(0,pos);
			var val = parms[i].substring(pos+1);
			qsParm[key] = val;
		}
	}
	
	return qsParm;
}


/**
 * returns the first integer in a string
 */
function findInt(str) {
	var regInt = new RegExp(/(\d+)/);
	regInt.exec(str, "i");
	if(regFloat.test(str)) {
		return RegExp.$1;
	} else {
		return "";
	}		
}

/**
 * returns the first float in a string
 */
function findFloat(str) {
	var regFloat = new RegExp(/(\d+\.\d+)/);
	regFloat.exec(str, "i");
	if(regFloat.test(str)) {
		return RegExp.$1;
	} else {
		return "";
	}
}

/**
 * returns the first number (int or float) in a string
 */
function findNumber(str) {
	var regFloat = new RegExp(/(\d+\.?\d*)/);
	regFloat.exec(str, "i");
	if(regFloat.test(str)) {
		return RegExp.$1;
	} else {
		return "";
	}
}

function clearMessageArea() {  // Clears message and error consoles on mouse click 
		alert("I am herer");
		var existElement=document.getElementById('divMessageConsole');
		if (existElement) {document.getElementById('divMessageConsole').style.display="none";}
		var existElement=document.getElementById('txtMessageConsoleTitle');
		if (existElement) {document.getElementById('txtMessageConsoleTitle').innerHTML="";}
		var existElement=document.getElementById('txtMessageConsole');
		if (existElement) {document.getElementById('txtMessageConsole').innerHTML="";}
		flagStatusMessage = false;
		var nextURL=getCookie('cookieNextURL');		// Get cookie from displayMessage function
		if (nextURL != 'self') {									// If we need to display a different page,
			MM_goToURL('parent',nextURL);              // Display the different page.
		}
}


// Function for displaying messages to the user. To use this, you must have a server-side include on the page
// usually located immediately below the Content DIV (divContent) that gets the file "incMessageConsole.shtml". 
// Parameters:
//   msgType:  info, warning, error 
//   msgTitle: A short title to be displayed in the "title bar" of error message
//   msgText:  A sentence or two that describes the error and tells the user what action they need to take to correct the error.
//   nextURL:  Optional. Determines which page should be displayed when the user dismisses the message. If not specified, stays on
//             same page.
function displayMessage(msgType,msgTitle,msgText,nextURL) {
		var existElement=document.getElementById('divMessageConsole');
		if (existElement) {document.getElementById('txtMessageConsoleTitle').innerHTML=msgTitle;}	
		if (existElement) {document.getElementById('txtMessageConsole').innerHTML=msgText;}	
		window.location="#ancTop";
		switch (msgType) {
		case 'info':
			document.getElementById('divMessageConsole').className="msgTypeInfo";
			document.getElementById('imgMsgIcon').src="images/iconMsgInfo.png";
			document.getElementById('divMessageConsole').style.display="block";
		break
		case 'warning':
			document.getElementById('divMessageConsole').className="msgTypeWarning";
			document.getElementById('imgMsgIcon').src="images/iconMsgWarning.png";
			document.getElementById('divMessageConsole').style.display="block";
		break
		case 'error':
			document.getElementById('divMessageConsole').className="msgTypeError";
			document.getElementById('imgMsgIcon').src="images/iconMsgError.png";
			document.getElementById('divMessageConsole').style.display="block";
			
		break
		case 'help':
			document.getElementById('divMessageConsole').className="msgTypeHelp";
			document.getElementById('imgMsgIcon').src="images/iconMsgHelp.png";
			document.getElementById('divMessageConsole').style.display="block";
		break
		default:
			document.getElementById('divMessageConsole').style.display="none";
		break
	}
  window.location="#ancTop";  // Scroll to top of page so that the message is visible
	if (nextURL) {								 // If a new URL was specified, then set a cookie for the clearMessageArea function to load									
		setCookie('cookieNextURL',nextURL,1);

	}
	else {												 // If a new URL wasn't specified, set the cookie to 'self'
		setCookie('cookieNextURL','self',1);
	}
}



