update = false;
highlight = -1;
added = false;

function live_search (p_term,event) {
	switch(event.keyCode) {
		case 40:
			highlight++;
			break;
		case 38:
			highlight--;
			if (highlight < 0) highlight = 0;
			break;
		case 13:
			box = document.getElementById('searchBox');
			p_term.value = box.childNodes[highlight].innerHTML;
			box.parentNode.removeChild(box);
			added = false;
			break;
		case 27:
			box = document.getElementById('searchBox');
			highlight = -1;
			box.parentNode.removeChild(box);
			added = false;
			break;
		default:
			update = true;
			highlight = -1;
	}
	
	if (update) {
		var request = new XMLHttpRequest();
		request.onreadystatechange = function() {
			if (request.readyState == 4) {
				if (request.status == 200) {
					if (added) { // remove old results
						p_term.parentNode.parentNode.removeChild(p_term.parentNode.nextSibling);
						added = false;
					}
					
					if (p_term.value != '') { //only if actual query
						index = 0;
						specArray = (request.responseText).split("::");
					
						if (specArray.length > 1) { //only if results
							box = document.createElement("div");
							box.id = 'searchBox';
							box.className = 'container';
					
							specArray.sort();
							for (var i in specArray) {
								specDiv = document.createElement("div");
								specDiv.innerHTML = specArray[i];
								specDiv.setAttribute("onclick", "this.parentNode.previousSibling.firstChild.value = this.innerHTML;" +
												"if(added) { this.parentNode.parentNode.removeChild(this.parentNode); added = false; }");
								specDiv.className = (index++ % 2 == 0) ? 'second' : 'first';
								box.appendChild(specDiv);
							}
							p_term.parentNode.parentNode.insertBefore(box, p_term.parentNode.nextSibling);
							added = true;
						} //end no results
					} //end null search term
				} else {
					alert(request.status);
				} //endif
			} //endif
		} //end function callback

		request.open("GET", "/scripts/searchResults.php?mode=spec&term="+p_term.value,true);
		request.send(null);
		
		update = false;
	} //endif update
	
	if (highlight >=0) {
		document.getElementById('searchBox').childNodes[highlight].className = 'highlight';
		
		document.getElementById('searchBox').childNodes[highlight+1].className = (highlight % 2 == 0) ? 'first' : 'second';
		document.getElementById('searchBox').childNodes[highlight-1].className = (highlight % 2 == 0) ? 'first' : 'second';
	}
	
}

function addSpec(searchId, contId) {
	var clone = document.getElementById(searchId).parentNode.cloneNode(true);
	clone.firstChild.value = "";
	var del = clone.lastChild;
	del.setAttribute("onclick", "this.parentNode.parentNode.removeChild(this.parentNode)");
	document.getElementById(contId).appendChild(clone);

}