var xmlURL = "product_data.xml";
var xmlDoc = null; // parsed XML passed to merge function; initially a duplicate of the full set
var xmlStorage = null; // duplicate of XML content; used to repopulate the original after it has been
						// parsed and possibly depleted
var firstUse = true; // flag to know if form has been activated yet; needed for onload

// use a library to load XML and XSL into XML document objects, referring to the callbacks defined below
window.onload = function() {
	productPane = document.getElementById("product_pane");
	new net.ContentLoader(xmlURL, onXmlLoad);
	new net.ContentLoader(xmlURL, onXmlStorageLoad); 
}

function onXmlLoad() {
// alert("onXmlLoad()");
	xmlDoc = this.req.responseXML;
	xmlDoc = xmlDoc.getElementsByTagName("hardware")[0];
}

function onXmlStorageLoad() {
// alert("onXmlStorageLoad()");
	xmlStorage = this.req.responseXML;
	xmlStorage = xmlStorage.getElementsByTagName("hardware")[0];
	if (firstUse == true) {
		firstUse = false;
		document.getElementById("data_controls").style.visibility = "visible";
		doMerge();
	}
}


// for subsequent data parsing, repopulate the data so full set is available at the outset
function transferData(source, destination) {
// alert("transferData()");
	// clear destination first
	while (destination.hasChildNodes()) {
		destination.removeChild(destination.firstChild);
	}
	// now copy nodes from source into destination
	for (i = 0 ; i < source.childNodes.length; ++i) {
		var newNode = source.childNodes[i].cloneNode(true);
		destination.appendChild(newNode);
	}
}

// pass the XML through the stylesheet, and append the results to the div in the body of the HTML page
function doMerge() {
	productPane.innerHTML = "";
	if (xmlDoc == null) {
		alert("Please try again in a moment; the product information is still being downloaded from the Internet.");
		return false;
	} 
	if (xmlDoc.getElementsByTagName("item").length > 0) { // be sure there is something in the data set
		var categories = xmlDoc.getElementsByTagName("category");
		table = document.createElement("table");
		table.className = "form_light";
		table.width = "90%";
		for (x = 0; x < categories.length; ++x) {
			var category = categories[x];
			var items = category.getElementsByTagName("item");
			if (items.length > 0) {
			thead = document.createElement("thead");
			row = document.createElement("tr");
			thead.appendChild(row);
			cell = document.createElement("th");
			cell.colSpan = "3";
			row.appendChild(cell);
			text = document.createTextNode(category.getElementsByTagName("name")[0].firstChild.nodeValue);
			cell.appendChild(text);
			table.appendChild(thead);
			for (y = 0; y < items.length; ++y ) {
				var product = items[y];
				tbody = document.createElement("tbody");
				var row1 = document.createElement("tr");
				if (y % 2 == 1) {
					row1.style.backgroundColor = "#efefef";
				}
				tbody.appendChild(row1);

				var title = product.getElementsByTagName("model")[0].firstChild.nodeValue;
				var titleCell = document.createElement("td");
				titleCell.colSpan = "3";
				var titleBold = document.createElement("b");
				titleText = document.createTextNode(title + ": ");
				titleBold.appendChild(titleText);
				titleCell.appendChild(titleBold);
				var summary = "";
				var wanType = product.getElementsByTagName("wanType")[0].firstChild.nodeValue; // variable to build composite description from various data fields
				if (wanType != "N/A") {
					summary = summary + wanType + "; ";	
				}
				numPorts = product.getElementsByTagName("ports")[0].firstChild.nodeValue;
				if (parseInt(numPorts) > 0) {
					summary = summary + numPorts + " Ethernet port";
					if (parseInt(numPorts) != 1) {
						summary = summary + "s";
					}
				} else {
					summary = summary + "Ethernet ports: N/A";	
				}
				if (product.getElementsByTagName("USB")[0] && product.getElementsByTagName("USB")[0].firstChild.nodeValue >= '1') {
					summary = summary + "; " + product.getElementsByTagName("USB")[0].firstChild.nodeValue + " USB port";
					if (product.getElementsByTagName("USB")[0].firstChild.nodeValue > 1) {
						summary = summary + "s";	
					}
				}
				if (product.getElementsByTagName("wirelessType")[0]) {
					summary = summary + "; " + product.getElementsByTagName("wirelessType")[0].firstChild.nodeValue + " wireless";
				}
				connectivityOptions = product.getElementsByTagName("connectivityType");
				if (connectivityOptions.length > 0) {
						var text = "";
					for (z = 0; z < connectivityOptions.length; ++z) {
						if (text.length > 0 ) {
							text = text + ", ";
						}
						text = text + connectivityOptions[z].firstChild.nodeValue;
					}
					summary = summary + "; " + text;
				}
				var summaryText = document.createTextNode(summary);
				titleCell.appendChild(summaryText);

				if (product.getElementsByTagName("description")[0].firstChild) {
					titleCell.appendChild(document.createElement("br"));
					var description = product.getElementsByTagName("description")[0].firstChild.nodeValue;
					var descriptionText = document.createTextNode(description);
					titleCell.appendChild(descriptionText);
				}
				titleCell.appendChild(document.createElement("br"));
				var hasWebPage = false;
				if (product.getElementsByTagName("productWebPageURL")[0]) {
					pageLink = document.createElement("a");
					pageLink.href = product.getElementsByTagName("productWebPageURL")[0].firstChild.nodeValue;
					linkText = document.createTextNode("More Information");
					pageLink.appendChild(linkText);
					titleCell.appendChild(pageLink);
					hasWebPage = true;
				}
				if (product.getElementsByTagName("productDatasheetURL")[0] && product.getElementsByTagName("productDatasheetURL")[0].firstChild) {
					if (hasWebPage) {
						spacer = document.createTextNode(" | ");
						titleCell.appendChild(spacer);
					}
					datasheetLink = document.createElement("a");
					datasheetLink.href = product.getElementsByTagName("productDatasheetURL")[0].firstChild.nodeValue;
					datasheetLink.target = "_blank";
					datasheetText = document.createTextNode("Datasheet");
					datasheetLink.appendChild(datasheetText);
					titleCell.appendChild(datasheetLink);
				}
				row1.appendChild(titleCell);
				table.appendChild(tbody);
			}
		}
		}
		productPane.appendChild(table);
	} else {
		productPane.innerHTML = "<p>There are no products that match your requirements. " +
		"You may want to try setting fewer specific requirements to find close matches.</p>";
	}
}

function updateData(control) {
//alert("updateData()");
	if (control[control.selectedIndex].value == "") {
		var remove = /\sspecified/;
		control.className = control.className.replace(remove, "");
	} else {
		control.className += " specified";
	}
	var wanFilter = document.getElementById("wanType").value;
	var portsFilter = document.getElementById("ports").value;
	var wirelessFilter = document.getElementById("wirelessType").value;
	var USBFilter = document.getElementById("USB").value;
	var RJ11Filter = document.getElementById("rj11").value;
	var connectivityFilter = document.getElementById("connectivityType").value;
	transferData(xmlStorage, xmlDoc);
	
	if (wanFilter != "") {
		filterXml(xmlDoc, "wanType", wanFilter);
	}
	if (portsFilter != "") {
		filterXml(xmlDoc, "ports", portsFilter);
	}	
	if (wirelessFilter != "") {
		filterXml(xmlDoc, "wirelessType", wirelessFilter);
	}
	if (USBFilter != "") {
		filterXml(xmlDoc, "USB", USBFilter);
	}
	if (RJ11Filter != "") {
		filterXml(xmlDoc, "rj11", RJ11Filter);	
	}
	if (connectivityFilter != "") {
		filterXml(xmlDoc, "connectivityType", connectivityFilter);
	}

	doMerge();
	
}

/*
filterXml pulls out nodes from an XML doc that do not have 
*/
function filterXml(doc, elementName, elementValue) {
//	alert ("Root is now " + doc.nodeName);
	var filterMatch = false;
	var categories = doc.childNodes;
	for (x = 0; x < categories.length; ++x ) {
		var category = categories[x];
		var items = category.childNodes;
		for (i = 0; i < items.length; ++i) {
			if (items[i].nodeType == 1) {
				if (items[i].nodeName == "name") { // not actually an item needing filtering
					filterMatch = true;
				} else {
					matchingNodes = items[i].getElementsByTagName(elementName);
					inner: for (j = 0; j < matchingNodes.length; ++j) {
//					alert ("Checking for match at item " + i + ", list entry " + j + " for value " + elementValue + " against " + matchingNodes[j].firstChild.nodeValue);
						if (matchingNodes[j].firstChild && (matchingNodes[j].firstChild.nodeValue.toUpperCase() == elementValue.toUpperCase() || matchingNodes[j].firstChild.nodeValue.toUpperCase() == "N/A")) { // "N/A" case is for accessories and post-WAN add-ons
//							alert ("Match");
							filterMatch = true;
							break inner;
						}
					}
				}
				if (! filterMatch) {
//					alert ("Attempt to remove node " + i);
//					alert("Removing node " + nodes[i].getElementsByTagName("model")[0].value);
					category.removeChild(items[i]);
					--i;
				} else {
					filterMatch = false;
				}
			} else { // clean house, removing non-element nodes, which are not relevant and confuse things.
				category.removeChild(items[i]);
				--i;
			}
		}
	}
}
