// JavaScript Document
String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}

var colMapping;
var colAlignment;
var curr_row;
var overGridCheckbox = false;

function ajaxRequest(eventObj, callbackFunction, debug) {							// This is the object constructor
	var that = this;													// A workaround for some javascript idiosyncrocies
	var updating = false;												// Set to true if this object is already working on a request
	
	if (callbackFunction == null)
		this.callback = function() { }									// A post-processing call -- a stub you overwrite.
	else
		this.callback = callbackFunction;
	
	this.update = function(url, param, contentType, responseType) {				// Initiates the server call.
		if (updating == true) { return false; }								// Abort if we're already processing a call.
		updating = true;												// Set the updating flag.
		var AJAX = null;												// Initialize the AJAX variable.
		if (window.XMLHttpRequest)										// Are we working with mozilla?
			AJAX = new XMLHttpRequest();									//  Yes -- this is mozilla.
		else															// Not Mozilla, must be IE
			AJAX = new ActiveXObject("Microsoft.XMLHTTP");					//  Wheee, ActiveX, how do we format c: again?

		if (AJAX == null) {												// If we couldn't initialize Ajax...
			alert("Your browser doesn't support AJAX.");						// Sorry msg.
			return false;												// Return false (WARNING - SAME AS ALREADY PROCESSING!)
		
		} else {
			AJAX.onreadystatechange = function() {							// When the browser has the request info..
				if (AJAX.readyState == 4 || AJAX.readyState=="complete") {		//   see if the complete flag is set.
				
					var res = AJAX.responseXML;
					
					if (responseType != null && responseType == "text") res = AJAX.responseText;
						
					if (l_debug) alert(AJAX.responseText);
					
					if (responseType == null || responseType != "text") {
						var xmlStatus = res.getElementsByTagName("ajax_status");
	
						if (xmlStatus == null)
							xmlStatus = res.getElementsByTagName("status");
	
						var responseCode = 0;
						// if return response is "success" then proceed
						if (xmlStatus != null) {
							responseCode = checkXMLResponse(xmlStatus);
							if (responseCode == 1) {
								// immediate processing logic goes here
							}
						}
					}
					
					delete AJAX;										//   delete the AJAX object since it's done.
					updating = false;									//   Set the updating flag to false so we can do a new request
					
					that.callback(l_eventObj, res);						// Call the post-processing function.					
				}													// End Ajax readystate check.
			}														// End create post-process fucntion block.

			
			AJAX.open("POST", url, true);									// Open the url this object was set-up with.
			
			if (contentType != null && contentType.toLowerCase() == "xml")
				AJAX.setRequestHeader("Content-Type", "text/xml");
				
			else {
				param += "&ts=" + (new Date() * 1);						// Append date to url (so the browser doesn't cache the call)
				AJAX.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			}
			
			if (l_debug) alert(param);
			
			AJAX.send(param);											// Send the request.
			return true;												// Everything went a-ok.
		}															// End Ajax setup aok if/else block
	}
	
	// This area set up on constructor calls.
	var l_eventObj = eventObj;											// Remember the layer associated with this object.
	var l_debug = (debug == null ? false : debug);
}

function ajaxBuildValueSetOptions(eventObj, callbackFunction) {					// This is the object constructor
	var that = this;													// A workaround for some javascript idiosyncrocies
	var updating = false;												// Set to true if this object is already working on a request
	
	if (callbackFunction == null)
		this.callback = function() { }									// A post-processing call -- a stub you overwrite.
	else
		this.callback = callbackFunction;
	
	this.update = function(value_set_id) {									// Initiates the server call.
		if (updating == true) { return false; }								// Abort if we're already processing a call.
		updating = true;												// Set the updating flag.
		var AJAX = null;												// Initialize the AJAX variable.
		if (window.XMLHttpRequest)										// Are we working with mozilla?
			AJAX = new XMLHttpRequest();									//  Yes -- this is mozilla.
		else															// Not Mozilla, must be IE
			AJAX = new ActiveXObject("Microsoft.XMLHTTP");					//  Wheee, ActiveX, how do we format c: again?

		if (AJAX == null) {												// If we couldn't initialize Ajax...
			alert("Your browser doesn't support AJAX.");						// Sorry msg.
			return false;												// Return false (WARNING - SAME AS ALREADY PROCESSING!)
		
		} else {
			AJAX.onreadystatechange = function() {							// When the browser has the request info..
				if (AJAX.readyState == 4 || AJAX.readyState=="complete") {		//   see if the complete flag is set.
				
					var res = AJAX.responseXML;
					var xmlStatus = res.getElementsByTagName("status");

					// if return response is "success" then proceed
					if (xmlStatus != null && checkXMLResponse(xmlStatus) == 1) {
						var xmlData = res.getElementsByTagName("record");
						
						l_eventObj.options.length = 0;
						
						for (j = 0; j < xmlData.length; j++) {
							l_eventObj.options[j] = new Option(
								xmlNVL(xmlData[j].getElementsByTagName("DISPLAY_NAME")[0].firstChild),
								xmlNVL(xmlData[j].getElementsByTagName("VALUE")[0].firstChild));
						}
					}
					
					delete AJAX;										//   delete the AJAX object since it's done.
					updating = false;									//   Set the updating flag to false so we can do a new request
					that.callback(res);									//   Call the post-processing function.
				}													// End Ajax readystate check.
			}														// End create post-process fucntion block.

			var param = "value_set_id=" + value_set_id + "&cmd=getvalueset&ts=" + (new Date() * 1);							// Append date to url (so the browser doesn't cache the call)
			
			AJAX.open("POST", "adc_api", true);									// Open the url this object was set-up with.
			AJAX.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			AJAX.send(param);											// Send the request.
			return true;												// Everything went a-ok.
		}															// End Ajax setup aok if/else block
	}
	
	// This area set up on constructor calls.
	var l_eventObj = eventObj;											// Remember the layer associated with this object.
}


function g_checkStatus() {	
	var status_msg = document.getElementById("status_msg");
		
	if (status_msg != null && status_msg.value > "") {
		alert(status_msg.value);
	}
}

function initHeader(autoFocusSearch, current_menu) {
	// set cookie to try to let server know when not a bot
	createCookie("user_agent", "1", 1);
	
	if (autoFocusSearch == null || autoFocusSearch != false)
		document.getElementById("searchText").focus();
	
	if (current_menu != null && current_menu != "") {
		var currMenu = document.getElementById(current_menu);
		if (currMenu != null) {
			currMenu.style.fontWeight =  "bold";
		}
	}
	
	var advSearchLabel = document.getElementById("toggle-advance-search");
	
	if (varAdvSearch == "1") {
		if (advSearchLabel != null)
			advSearchLabel.innerHTML = "Hide Advance Search";
		var headerCont = document.getElementById("header-container");
		if (headerCont != null) headerCont.style.height = "195px";
		
		var subNav2 = document.getElementById("sub-nav-2");
		if (subNav2 != null) subNav2.style.top = "195px";
		
	} else if (advSearchLabel != null) {
		advSearchLabel.innerHTML = "Advance Search";
	}
}

function doSearch(e) {
	if (!e) var e = window.event

	var searchField = document.getElementById("searchText");
		
	searchField.value = trim(searchField.value)
	if (searchField.value > "") {
		// the following uses the GET method
		//var action = varWebRoot  + "/search.jsp?searchText=" + URLencode(searchField.value);
		//document.location.href = action;
		
		document.srchfrm.action = varWebRoot + "/search.jsp";
		document.srchfrm.method = "get";
		document.srchfrm.submit();
	}
	
	// return false so Mozilla based browsers will not
	// continue to submit forms with the default method
	// handle event
	e.cancelBubble = true;
	e.returnValue = false;
	if (e.stopPropagation) e.stopPropagation();
	return false;
}

function gotoLightbox(lightboxType) {
	if (lightboxType != null && lightboxType == "lightboxcd")
		document.location.href = varWebRoot  + "/lightbox?cmd=gotoPage&pageNum=1&hid.mode=lightboxcd";
	else
		document.location.href = varWebRoot  + "/lightbox?cmd=gotoPage&pageNum=1&hid.mode=lightbox";
}

function viewLightbox(lightboxType) {
	// determine which lightbox we want to take them to first in case lightboxType is not specified
	var lightbox = readCookie("lightbox");
	var itemCount = 0;
	if (lightbox != null) itemCount = lightbox.split('|').length;
	
	var lightboxCD = readCookie("lightboxcd");
	var cdCount = 0;
	if (lightboxCD != null) cdCount = lightboxCD.split('|').length;
	
	// the following uses the GET method
	if ((lightboxType != null && lightboxType == "lightboxcd") || (itemCount == 0 && cdCount > 0))
		document.location.href = varWebRoot + "/lightbox?cmd=gotoPage&pageNum=1&hid.mode=lightboxcd";
	else
		document.location.href = varWebRoot + "/lightbox?cmd=gotoPage&pageNum=1&hid.mode=lightbox";
}

function showCartItemCount() {
	var cart = readCookie("cart");
	var cdCart = readCookie("cdcart");
	var subCart = readCookie("subcart");
	
	var itemCount = 0;
	
	if (cart != null) itemCount = cart.split('|').length;
	if (cdCart != null) itemCount = itemCount + cdCart.split('|').length;
	if (subCart != null) itemCount = itemCount + subCart.split('|').length;
	
	document.getElementById("my_cart").innerHTML = "My Cart (" + itemCount + ")";
	
	return itemCount;
}

function showLightboxCount() {
	var lightbox = readCookie("lightbox");
	var lightboxcd = readCookie("lightboxcd");
	var itemCount = 0;
	
	if (lightbox != null) itemCount = lightbox.split('|').length;
	if (lightboxcd != null) itemCount = itemCount + lightboxcd.split('|').length;
	
	if (document.getElementById("my_lightbox") != null)
		document.getElementById("my_lightbox").innerHTML = "My Lightbox (" + itemCount + ")";
}

function ajaxRefreshCart() {
	if (document.getElementById("ctrl_cart") == null) return false;
	
	var ajaxReq = new ajaxRequest(document.getElementById("ctrl_cart"), refreshCartXML);
	ajaxReq.update("shop", "cmd=refreshCartXML");
}

function couponTerms() {
	open(varWebRoot + "/learnMoreCoupons.html", "",
		"resizable=" + (varNS ? "yes" : "no") + ", status=no, width=425, height=250");
}

function learnMore(page) {
	open(varWebRoot + "/" + page, "",
		"resizable=" + (varNS ? "yes" : "no") + ", status=no, width=425, height=100, toolbar=no, location=no, menubar=no");
}

function logout () {
	var userID = document.getElementById("curr_user_id");
	if (userID == null) return;
	
	if (confirm("Logout Member " + userID.innerHTML + "?") != true) return;

	document.location.href = "accounts?cmd=logout";
}

// do we even need this anymore?
//return IE4+or W3C DOM reference for an ID
function getObject(obj){
	var theObj
	if (document.all){
		if (typeof obj =="string"){
			return document.all(obj)
		}else {
			return obj.style
		}
	}
	if (document.getElementById){
		if (typeof obj =="string"){
			return document.getElementById(obj)
		}else {
			return obj.style
		}
	}
	return null
}

function imageDetail(url, imageName, lightbox_item_id) {
	document.location.href =  varWebRoot + "/stock-photo" + url + "/" + imageName + ".html" + (lightbox_item_id == null ? "" : "?lightbox_item_id=" + lightbox_item_id);
}

function viewCDImages(cdID) {
	document.location.href =
		varWebRoot + "/cdcatalog?cmd=gotoPage&pageNum=1&cd_id=" + cdID + "&hid.mode=cdimages";
}

function getPosition(e) {
	var left = 0;
	var top  = 0;
	
	while (e.offsetParent) {
		left += e.offsetLeft + (e.currentStyle?(parseInt(e.currentStyle.borderLeftWidth)).NaN0():0);
		top  += e.offsetTop  + (e.currentStyle?(parseInt(e.currentStyle.borderTopWidth)).NaN0():0);
		e = e.offsetParent;
	}
	
	left += e.offsetLeft + (e.currentStyle?(parseInt(e.currentStyle.borderLeftWidth)).NaN0():0);
	top  += e.offsetTop  + (e.currentStyle?(parseInt(e.currentStyle.borderTopWidth)).NaN0():0);

	return {x:left, y:top};
}

function mouseCoords(ev) {
	if(ev.pageX || ev.pageY) {
		return {x:ev.pageX, y:ev.pageY};
	}
	
	return {
		x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
		y:ev.clientY + document.body.scrollTop  - document.body.clientTop
	};
}

function getMouseOffset(target, ev) {
	ev = ev || window.event;

	var docPos = getPosition(target);
					
	var mousePos  = mouseCoords(ev);
		
	return {x:mousePos.x - docPos.x, y:mousePos.y - docPos.y};
}

function StopBubble(e) {
    /* http://www.quirksmode.org/js/events_order.html */
    if (!e) e = window.event;

    e.cancelBubble = true; /* Microsoft */
    if (e.stopPropagation)
        e.stopPropagation(); /* W3C */
}

function checkXMLResponse(xmlStatus, silent, URIdecode) {
	if (xmlStatus == null || xmlStatus.length == 0) return 0;
			
	var statusCode = xmlStatus[0].getElementsByTagName("code")[0].firstChild.nodeValue;
		
	if (statusCode != "success") {
		if (silent != null && silent == false) {
			var statusMsg = xmlStatus[0].getElementsByTagName("message")[0].firstChild.nodeValue;
			
			if (URIdecode != null && URIdecode == true)
				alert("Error:\n\n" + decodeURIComponent(statusMsg));
			else
				alert("Error:\n\n" + statusMsg);
		}
		
		return 0;
		
	} else {
		var showAlert = xmlStatus[0].getAttribute("alert");
		if (showAlert != null && showAlert == "1" && silent != null && silent == false) {
			var statusMsg = xmlStatus[0].getElementsByTagName("message")[0].firstChild.nodeValue;
			
			if (URIdecode != null && URIdecode == true)
				alert(decodeURIComponent(statusMsg));
			else
				alert(statusMsg);
		}
		
		return 1;
	}
}

function imgOptOver(ev) {
	ev = ev || window.event;
	
	var img = ev.target || ev.srcElement;
	
	if (img.tagName == 'IMG') {
		if (img.getAttribute("_on") != null)
			img.src = getCachedImage(img.getAttribute("_on")).src;
		return;
	}
	
	while (!(img.tagName == 'A' || img.tagName == 'BODY'))
		img = img.parentNode;
	
	if (img.tagName == 'A') {
		if (img.getAttribute("href") == null || img.getAttribute("href") == "")
			img.style.textDecoration = "underline";
		
		for (var i = 0; i < img.childNodes.length; i++) {
			if (img.childNodes[i].tagName == "IMG") {
				img = img.childNodes[i];
				break;
				
			} else if (img.childNodes[i].tagName == 'DIV' && $(img.childNodes[i]).hasClass('icon-lightbox-0')) {
				$(img.childNodes[i]).removeClass('icon-lightbox-0');
				$(img.childNodes[i]).addClass('icon-lightbox-1');
				break;
			
			} else if (img.childNodes[i].tagName == 'DIV' && $(img.childNodes[i]).hasClass('icon-cart-0')) {
				$(img.childNodes[i]).removeClass('icon-cart-0');
				$(img.childNodes[i]).addClass('icon-cart-1');
				break;
			}
		}
	}
}

function imgOptOut(ev) {
	ev = ev || window.event;
	
	var img = ev.target || ev.srcElement;
	
	if (img.tagName == 'IMG') {
		if (img.getAttribute("_off") != null)
			img.src = getCachedImage(img.getAttribute("_off")).src;
		return;
	}
	
	while (!(img.tagName == 'A' || img.tagName == 'BODY'))
		img = img.parentNode;
		
	if (img.tagName == "A") {
		if (img.getAttribute("href") == null || img.getAttribute("href") == "")
			img.style.textDecoration = "none";
			
		for (var i = 0; i < img.childNodes.length; i++) {
			if (img.childNodes[i].tagName == "IMG") {
				img = img.childNodes[i];
				break;
				
			} else if (img.childNodes[i].tagName == 'DIV' && $(img.childNodes[i]).hasClass('icon-lightbox-1')) {
				$(img.childNodes[i]).removeClass('icon-lightbox-1');
				$(img.childNodes[i]).addClass('icon-lightbox-0');
				break;
		
			} else if (img.childNodes[i].tagName == 'DIV' && $(img.childNodes[i]).hasClass('icon-cart-1')) {
				$(img.childNodes[i]).removeClass('icon-cart-1');
				$(img.childNodes[i]).addClass('icon-cart-0');
				break;
			}
		}
	}
}

function getCachedImage(src) {
	var img = imgCache[src];

	if (img == null) {
		imgCache[src] = new Image();
		imgCache[src].src = src;
		img = imgCache[src];
	}
	
	return img;
}

function checkClosePopUp(ev) {
	ev = ev || window.event;
		
	var target = ev.target || ev.srcElement;
		
	var popupName = "lightbox-popup";
	var popupMemo = "memo-popup";
	var popupDecline = "declinereason-popup";
	var popupList = "list-popup";
	var popupCalendar = "calendar-popup";
	
	if (target) {
		do {
			if (target.id == popupName || target.id == popupMemo || target.id == popupDecline || target.id == popupList || target.id == popupCalendar) return;
			target = target.parentNode;
		} while (target);
	}
	
	hidePopup(popupName);
	hidePopup(popupMemo);
	hidePopup(popupDecline);
	hidePopup(popupList);
	hidePopup(popupCalendar);
}

function hidePopup(popupName) {
	var popup = document.getElementById(popupName);
	if (popup) {
		popup.style.display = "none";
		document.onclick = null;
	}
}

function indexColumns(tableName) {
	var columns = new Array();
	var allignments = new Array();
	
	var table = document.getElementById("tbl-grid");
	getTableColHeaders(table, columns, allignments);
	
	colMapping = new Array();
	colAlignment = new Array();
	
	for (var i = 0; i < columns.length; i++) {
		colMapping[columns[i]] = i;
		colAlignment[columns[i]] = allignments[i];
	}
}

function getTableColHeaders(table, columns, align, key, columnObj) {
	var colGroup = null;
		
	for (var i = 0; i < table.childNodes.length; i++) {
		if (table.childNodes[i].tagName == "COLGROUP") {
			colGroup = table.childNodes[i];
			break;
		}
	}
	
	if (colGroup == null) return false;
		
	for (var i = 0; i < colGroup.childNodes.length; i++) {
		if (colGroup.childNodes[i].tagName == "COL") {
			if (columns != null)
				columns[columns.length] = colGroup.childNodes[i].getAttribute("_field");
			
			if (align != null)
				align[align.length] = colGroup.childNodes[i].getAttribute("_align");
				
			if (key != null)
				key[key.length] = colGroup.childNodes[i].getAttribute("_key");
				
			if (columnObj != null)
				columnObj[columnObj.length] = colGroup.childNodes[i];
		}
	}
}

function buildTable(tableGrid, xmlPageInfo, xmlData, enableRowDblClick, displayPageNav) {
	try {
		var tableBody = getTBODY(tableGrid);
		if (tableBody == null)
			return false;

		clearTable(tableBody);
		
		setGridTableMessage(tableGrid, null);
		
		if (xmlData == null || xmlData.length == 0)
			return false;
		
		// enumerate all the table columns
		var columns = new Array();
		var align = new Array();
		var key = new Array();
		var columnObj = new Array();
		
		getTableColHeaders(tableGrid, columns, align, key, columnObj);
		
		if (enableRowDblClick == null) enableRowDblClick = true;
		
		var rowOffSet = 0;
		var numRows = "";
		var totalRows = null;
		
		if (xmlPageInfo != null) {
			rowOffSet = parseInt(nvlXML(xmlPageInfo[0].getElementsByTagName("start_row")[0]));
			if (isNaN(rowOffSet)) rowOffSet = 0;
			rowOffSet++;
			
			numRows = parseInt(nvlXML(xmlPageInfo[0].getElementsByTagName("num_rows")[0]));
			if (isNaN(numRows)) numRows = "";
			
			try {
				totalRows = parseInt(xmlPageInfo[0].getElementsByTagName("total_rows")[0].firstChild.nodeValue);
			} catch (err) {
				totalRows = null;
			}
		}
		
		if (isNaN(totalRows) || totalRows == null || totalRows == "")
			totalRows = tableGrid.getAttribute("_totalRows");

		if (isNaN(totalRows) || totalRows == null) totalRows = "";
		if (totalRows != "") tableGrid.setAttribute("_totalRows", totalRows);
		
		for (var i = 0; i < xmlData.length; i++) {
			newR = document.createElement("tr");
			
			newR.onmouseover = function(ev) { ev = ev || window.event; rowOver(ev); }
			newR.onmouseout = function(ev) { ev = ev || window.event; rowOut(ev); }
			//newR.onclick = function(ev) { ev = ev || window.event; rowClicked(ev); }
			
			if (enableRowDblClick)
				newR.ondblclick = function(ev) { ev = ev || window.event; rowDblClicked(ev); }
			
			for (var col = 0; col < columns.length; col++) {
					
				newC = document.createElement("td");
				
				if (columns[col] == "[rownum]") {
					newC.innerHTML = (i + rowOffSet);
					newC.style.textAlign = "right";
					newC.style.color = "#999999";

				} else if (columns[col] == "[check]") {
					// assign key data to cell
					try {
						newC.setAttribute("_key", nvlXML(xmlData[i].getElementsByTagName(key[col])[0]));
					} catch (err) {
						alert("Error In: buildTable\n\nUnable to get [check] XML node for " + key[col]);
						continue;
					}
					
					var chkSelect = document.createElement("input");
					chkSelect.type = "checkbox";
					chkSelect.value = nvlXML(xmlData[i].getElementsByTagName(key[col])[0]);
					
					if (columnObj[col].getAttribute("_name") != null) {
						chkSelect.name = columnObj[col].getAttribute("_name");
						chkSelect.id = columnObj[col].getAttribute("_name");
						
					} else {
						chkSelect.name = "chkSelect";
						chkSelect.id = "chkSelect";
					}
					
					chkSelect.onclick = function(ev) { ev = ev || window.event; checkBoxClicked(ev); }
						
					newC.style.textAlign = "center";
						
					if (columnObj[col].getAttribute("_chkColumn") != null) {
						var value = nvlXML(xmlData[i].getElementsByTagName(columnObj[col].getAttribute("_chkColumn"))[0]);					
						chkSelect.defaultChecked  = (value > "" ? true : false);
						
					} else				  
						chkSelect.defaultChecked  = false;
						
					chkSelect.setAttribute("_checked", chkSelect.checked);
						
					newC.appendChild(chkSelect);
					
					newC.onmouseover = function() { gridCheckboxOver(); }
					newC.onmouseout = function() { gridCheckboxOut(); }
					
				} else if (columns[col] == "[spacer]") {
					newC.innerHTML = "";
	
				} else {		
					try {						
						var value = nvlXML(xmlData[i].getElementsByTagName(columns[col])[0]);
						newC.setAttribute("_value", value);
						
						if (align[col] == "cb") {
							// convert value and display as boolean
							if (value == "1" || value == "Y")
								value = "Y";
							else
								value = "";							
						}
						
						if (columnObj[col].getAttribute("_format") != null && columnObj[col].getAttribute("_format") == "currency")
							newC.innerHTML = "<div nowrap>" + formatCurrency(value) + "</div>";
						else if (columnObj[col].getAttribute("_format") != null && columnObj[col].getAttribute("_format") == "date")
							newC.innerHTML = "<div nowrap>" + dateFormat(new Date(value), "isoDate") + "</div>";
						else
							newC.innerHTML = "<div nowrap>" + value + "</div>";
	
						if (align[col] == "c" || align[col] == "cb")
							newC.style.textAlign = "center";
							//newC.setAttribute("className", "cellDataCenter");
						else if (align[col] == "r")
							newC.style.textAlign = "right";
							//newC.setAttribute("className", "cellDataRight");
						
					} catch (err) {
						// null
					}
				}
				
				newR.appendChild(newC);
			}
			
			tableBody.appendChild(newR);
		}
		
		if (numRows > 0 && (displayPageNav == null || displayPageNav != false))
			buildPaging(rowOffSet - 1, totalRows, tableGrid.getAttribute("_pageSize"));
		
		if (document.getElementById("cell_pageInfo") != null)
			document.getElementById("cell_pageInfo").style.visibility = "visible";
			
		if (document.getElementById("cell_pageNum") != null)
			document.getElementById("cell_pageNum").style.visibility = "visible";
		
		return (totalRows - 0 > 0);
		
	} catch (err) {
		alert("Error In: buildTable\n\n" + err.message);
	}
}

function clearTable(table) {
	while (table.rows.length > 0) table.deleteRow(0);
}

function getTBODY(table) {
	var tableBody = null;
	
	// find the table <TBODY> element to append child rows to
	for (var i = 0; i < table.childNodes.length; i++) {
		if (table.childNodes[i].tagName == "TBODY") {
			tableBody = table.childNodes[i];
			break;
		}
	}
	
	if (tableBody == null)
		alert("Error: Could not find grid table element TBODY.");
	
	return tableBody;
}

function nvlXML(node, dataIfNULL) {
	try {
		return node.firstChild.nodeValue;
	} catch (err) {
		if (dataIfNULL != null)
			return dataIfNULL;
		else
			return "";
	}
}

function nvlXMLAttr(node, attributeName, dataIfNULL) {
	try {
		return node.getAttribute(attributeName);
	} catch (err) {
		if (dataIfNULL != null)
			return dataIfNULL;
		else
			return "";
	}
}

function rowOver(ev, showPointer) {
	var row = ev.target || ev.srcElement;
	
	while (row.tagName != "TR" && row.parentNode != null)
		row = row.parentNode;
		
	if (row.tagName != "TR") return false;
		
	if (curr_row != null && curr_row == row)
		row.style.background = "#E8E800";
	else
		row.style.background = "#FFFFA8";
		
	if (showPointer != null && showPointer)
		row.style.cursor = "pointer";
}

function rowOut(ev, showPointer) {
	var row = ev.target || ev.srcElement;
	
	while (row.tagName != "TR" && row.parentNode != null)
		row = row.parentNode;
		
	if (row.tagName != "TR") return false;
	
	if (curr_row != null && curr_row == row)
		row.style.background = "#E8E800";
	else
		row.style.background = "transparent";
		
	if (showPointer != null && showPointer)
		row.style.cursor = "default";
}

function gridCheckboxOver() {
	overGridCheckbox = true;
}

function gridCheckboxOut() {
	overGridCheckbox = false;
}

function buildPaging(startRow, totalRows, pageSize, paging) {
	
	if (pageSize == null) pageSize = 50;
	
	if (paging == null)
		paging = document.getElementById("cell_pageNum");
	
	var currentPage = parseInt((startRow / pageSize) + 1);
	var totalPages = Math.ceil(totalRows / pageSize);
	var pageRanges = 10;
	var minPage = 1;
	var maxPage = -1;

	// track the starting row of the current page
	paging.setAttribute("_startRow",  startRow);
	
	// if more then 10 pages then "window" the page range around the current page
	if (totalPages > pageRanges && currentPage > 0) {			
		minPage = (currentPage - (pageRanges / 2) < 1 ? 1 : currentPage - (pageRanges / 2));							
		maxPage = (minPage + (pageRanges - 1) > totalPages ? totalPages : minPage + (pageRanges - 1));
								
		// if range between min and max page rangd is less than 10 
		// then move the min page back a little so we can always present a 10 page selection range
		if (maxPage - minPage < (pageRanges - 1)) minPage = maxPage - (pageRanges - 1);
		
	} else {
		maxPage = totalPages;
	}

	while (paging.childNodes.length > 0) paging.removeChild(paging.childNodes[0]);
	
	var firstPage = document.createElement("IMG");
	firstPage.src = "images/blk_arrow_left_stop.gif";
	firstPage.align = "middle";
	firstPage.setAttribute("class", "pageArrow");
	firstPage.setAttribute("className", "pageArrow");
	firstPage.setAttribute("_startRow", 1);
	firstPage.onclick = function(ev) { ev = ev || window.event; pageData(ev); }
	paging.appendChild(firstPage);
	
	var prevPageNum = (currentPage > 1 ? currentPage - 1 : 1);
	prevPageNum = ((prevPageNum - 1) * pageSize) + 1;
	
	var prevPage = document.createElement("IMG");
	prevPage.src = "images/blk_arrow_left.gif";
	prevPage.align = "middle";
	prevPage.setAttribute("class", "pageArrow");
	prevPage.setAttribute("className", "pageArrow");
	prevPage.classname = "pageArrow";
	prevPage.setAttribute("_startRow", prevPageNum);
	prevPage.onclick = function(ev) { ev = ev || window.event; pageData(ev); }
	paging.appendChild(prevPage);
	
	for (var index = minPage; index <= maxPage; index++) {
		var pageText = document.createTextNode(" " + index + " ");
		var pageClick = document.createElement("SPAN");
		
		pageClick.appendChild(pageText);
		pageClick.setAttribute("_startRow", (index - 1) * pageSize + 1);
		pageClick.onclick = function(ev) { ev = ev || window.event; pageData(ev); }
			
		if (index == currentPage) {
			pageClick.setAttribute("class", "pageNumSel");
			pageClick.setAttribute("className", "pageNumSel");
		
		} else {
			pageClick.setAttribute("class", "pageNum");
			pageClick.setAttribute("className", "pageNum");
		}
		
		paging.appendChild(pageClick);
	}
	
	var nextPageNum = (currentPage < totalPages ? currentPage + 1 : totalPages);
	nextPageNum = ((nextPageNum - 1) * pageSize) + 1;
	
	var nextPage = document.createElement("IMG");
	nextPage.src = "images/blk_arrow_right.gif";
	nextPage.align = "middle";
	nextPage.setAttribute("class", "pageArrowRight");
	nextPage.setAttribute("className", "pageArrowRight");
	nextPage.setAttribute("_startRow", nextPageNum);
	nextPage.onclick = function(ev) { ev = ev || window.event; pageData(ev); }
	paging.appendChild(nextPage);

	var lastPage = document.createElement("IMG");
	lastPage.src = "images/blk_arrow_right_stop.gif";
	lastPage.align = "middle";
	lastPage.setAttribute("class", "pageArrowRight");
	lastPage.setAttribute("className", "pageArrowRight");
	lastPage.setAttribute("_startRow", (totalPages - 1) * pageSize + 1);
	lastPage.onclick = function(ev) { ev = ev || window.event; pageData(ev); }
	paging.appendChild(lastPage);
	
	if (document.getElementById("cell_pageInfo") != null)
		document.getElementById("cell_pageInfo").style.visibility = "visible";
		
	paging.style.visibility = "visible";
}

function pageData(ev) {
	var page = ev.target || ev.srcElement
	if (page != null) getData(page.getAttribute("_startRow") - 1, false);
}

function setGridTableMessage(tableGrid, message) {
	var tableBody = getTBODY(tableGrid);
	if (tableBody == null)
		return false;

	clearTable(tableBody);

	if (message != null && message > "") {
		var newR = document.createElement("tr");
		var newC = document.createElement("td");
		newC.setAttribute("colSpan", "6");
		newC.innerHTML = message;
		
		newR.appendChild(newC);
		tableBody.appendChild(newR);
			
		if (document.getElementById("cell_pageInfo") != null)
			document.getElementById("cell_pageInfo").style.visibility = "hidden";
			
		if (document.getElementById("cell_pageNum") != null)
			document.getElementById("cell_pageNum").style.visibility = "hidden";
	}
	
	return true;
}

function getPreviousSibling(n) {
	var x = n.previousSibling;
	
	while (x.nodeType != 1)
		x = x.previousSibling;

	return x;
}

function removeAllChildren(ele) {
	if (ele != null) {
		while (ele.childNodes.length > 0)
			ele.removeChild(ele.childNodes[0]);
	}
}

function doCookieCheck() {
	if (cookieCheck(false) == false) {
		var cell = document.createElement("div");
		cell.setAttribute("id", "cookieMsg");
		cell.innerHTML = "Cookies are DISABLED on this browser.  Cookies are required for Site Features. " +
			"Please see our <a href=\"" + varWebRoot + "/privacy.jsp\">Privacy Policy</a> if you have any concerns.";
			
		document.body.appendChild(cell);
	}
}

function toggleAdvanceSearch(ev) {
	ev = ev || window.event;
	var target = ev.target || ev.srcElement;

	var advSearch = document.getElementById("advance-search");
	var hdrCont = document.getElementById("header-container");
	var subNav2 = document.getElementById("sub-nav-2");
	var enabled = 0;

	if (advSearch == null || hdrCont == null || subNav2 == null) return false;

	if (advSearch.style.display == "none") {
		advSearch.style.display = "inline";
		target.innerHTML = "Hide Advance Search";
		hdrCont.style.height = "195px";	
		subNav2.style.top = "195px";
		
		enabled = 1;
	
	} else {
		advSearch.style.display = "none";
		target.innerHTML = "Advance Search";
		hdrCont.style.height = "155px";
		subNav2.style.top = "155px";
	}
	
	// send ajax command to set session value for advance search
	var ajaxReq = new ajaxRequest(target, null);
	ajaxReq.update("api", "cmd=set_advance_search&value=" + enabled, null, "text");
	
	var searchColors = document.getElementsByName("chk_color");
	if (searchColors != null && searchColors.length > 0) {
		for (var i = 0; i < searchColors.length; i++) {
			if (enabled == 1)
				searchColors[i].removeAttribute("disabled");
			else
				searchColors[i].setAttribute("disabled", "true");
		}
	}
	
	var searchShape = document.getElementsByName("rad_shape");
	if (searchShape != null && searchShape.length > 0) {
		for (var i = 0; i < searchShape.length; i++) {
			if (enabled == 1)
				searchShape[i].removeAttribute("disabled");
			else
				searchShape[i].setAttribute("disabled", "true");
		}
	}
}

function clearColorSearch(ev) {
	ev = ev || window.event;
	var element = ev.target || ev.srcElement;
	
	element.checked = true;
	
	var chkColors = document.getElementsByName("chk_color");
	if (chkColors != null && chkColors.length > 0) {
		for (var i = 0; i < chkColors.length; i++) {
			chkColors[i].checked = false;
		}
	}
}

function setColorSearch(ev) {
	ev = ev || window.event;
	var element = ev.target || ev.srcElement;

	var radClearColors = document.getElementById("rad_all_colors");	
	
	if (element.checked)
		radClearColors.checked = false;
		
	else {
		// scan all color checkboxes and if one checked then set All Colors
		var chkColors = document.getElementsByName("chk_color");
		radClearColors.checked = true;
		if (chkColors != null && chkColors.length > 0) {
			for (var i = 0; i < chkColors.length; i++) {
				if (chkColors[i].checked) {
					radClearColors.checked = false;
					break;
				}
			}
		}
	}
}


function addOption(selectField, option) {
  try {
    selectField.add(option, null); // standards compliant; doesn't work in IE
	
  } catch(ex) {
    selectField.add(option); // IE only
  }
}