/**
Modifed by Jeff Crossett 7/15/05
Dynamic XMLHttp lookups based on Google Suggest XMLRPC code. See:
http://serversideguy.blogspot.com/2004/12/google-suggest-dissected.html
http://www.fastbugtrack.com/misc/google/ac.js
http://www.google.com/webhp?complete=1&hl=en
This work is based upon Julian Robichaux's work at http://www.nsftools.com.
I simply revamped it to work with a true XML stream (this version is designed for
the "ReadViewEntries" xml view) and changed the behavior of the
Enter key when highlighting a user name/number.  If you click on, or press enter 
with an entry highlighted, the browser will change to a detail page for that employee.
The page is dependent upon the employee id that is included in the xml stream.
Customizations of this script to get it to work with your XML stream will involve the 
detailPage global object, the getLookupURL function, and the showQueryDiv function.
*/
var queryField;
var lookupURL;
var divName;
var ifName;
var lastVal = "";
var val = ""
var xmlHttp;
var cache = new Object();
var searching = false;
var globalDiv;
var globalDom;
var divFormatted = false;
var DIV_BG_COLOR = "#e3f7ee";
var DIV_HIGHLIGHT_COLOR = "#2DBAC3";
var detailPage = "detailPage.foo?empId=";
var dbPath = 'pets4homes/home.nsf';
/**
The InitQueryCode function should be called by the <body onload> event, where queryFieldName = 
the name of the form field we're using for lookups
For example:
<body onload="InitQueryCode('lookupField')">
The above example will monitor the input box called "lookupField" on this page,
and when it changes the contents of the field will be passed to lookupserver like by using the 
getLookupURL function which will need to be customized for your query
The reponse from the query should be XML and the navigation of that domDocument
needs to be customized in the showQueryDiv function. 
*/
function InitQueryCode (queryFieldName, lookupURLPrefix, hiddenDivName){
	queryField = document.getElementsByName(queryFieldName).item(0);
	queryField.onblur = hideDiv;
	queryField.onkeydown = keypressHandler;
  
	// for some reason, Firefox 1.0 doesn't allow us to set autocomplete to off
	// this way, so you should manually set autocomplete="off" in the input tag
	// if you can -- we'll try to set it here in case you forget
	queryField.autocomplete = "off";
  
	if (hiddenDivName)
		divName = hiddenDivName;
	else
		divName = "querydiv";
	ifName = "queryiframe";
  
	// add a blank value to the cache (so we don't try to do a lookup when the
	// field is empty) and start checking for changes to the input field
	addToCache("","");
	setTimeout("mainLoop()", 100);
}
/**
This is a helper function that just adds results to our cache, to avoid repeat lookups.
*/
function addToCache (queryString, resultDom){
	cache[queryString] = resultDom;
}
/**
This is the function that monitors the queryField, and calls the lookup
functions when the queryField value changes.
*/
mainLoop = function() {
	val = escape(queryField.value);
	// if the field value has changed and we're not currently waiting for
	// a lookup result to be returned, do a lookup (or use the cache, if we can)
	if(lastVal != val && val != "" && searching == false){
		var cacheResult = cache[val];
		if (cacheResult){
			globalDom = cacheResult;
			showQueryDiv(val);
		}else{
			doRemoteQuery(val);
		}
		lastVal = val;
	}
	setTimeout("mainLoop()", 100);
	return true;
};
/**
Get the <DIV> we're using to display the lookup results, and create the
<DIV> if it doesn't already exist.
*/
function getDiv (divID){
	if (!globalDiv) {
		// if the div doesn't exist on the page already, create it
		if (!document.getElementById(divID)) {
			var newNode = document.createElement("div");
			newNode.setAttribute("id", divID);
			document.body.appendChild(newNode);
		}
    
		// set the globalDiv reference
		globalDiv = document.getElementById(divID);
		// figure out where the top corner of the div should be, based on the
		// bottom left corner of the input field
		var x = queryField.offsetLeft;
		var y = queryField.offsetTop + queryField.offsetHeight;
		var parent = queryField;
		while (parent.offsetParent) {
			parent = parent.offsetParent;
			x += parent.offsetLeft;
			y += parent.offsetTop;
		}
    
		// add some formatting to the div, if we haven't already
		if (!divFormatted) {
			globalDiv.style.backgroundColor = DIV_BG_COLOR;
			globalDiv.style.fontFamily = "Verdana, Geneva, Arial, Helvetica, sans-serif";
			globalDiv.style.padding = "4px";
			globalDiv.style.border = "1px solid black";
			globalDiv.style.fontSize = "90%";
  
  			globalDiv.style.position = "absolute";
			globalDiv.style.left = x + "px";
			globalDiv.style.top = y + "px";
			globalDiv.style.visibility = "hidden";
			globalDiv.style.zIndex = 10000;
			divFormatted = true;
		}
	}
	return globalDiv;
}
/**
This is the function that should be returned by the XMLHTTP call. It will
format and display the lookup results.
*/
function showQueryDiv(queryString){
	var div = getDiv(divName);
	// to debug in FF
	//alert(new XMLSerializer().serializeToString(globalDom));
	// to debug in IE
	//alert(globalDom.xml);
  	// remove any results that are already there
	while (div.childNodes.length > 0)
		div.removeChild(div.childNodes[0]);
	// add an entry for each of the results in the domDoc
	var entryNodes = globalDom.getElementsByTagName('viewentry');
	if(entryNodes.length > 0){
		// check to see if we have any results
		for (var i = 0; i < entryNodes.length; i++){
			valueNodes = entryNodes[i].getElementsByTagName('entrydata')
			// each result will be contained within its own div
			var result = document.createElement("div");
			result.style.cursor = "pointer";
			result.style.borderBottom = "1px solid #777777";
			result.style.padding = "3px 0px 3px 0px";
			_unhighlightResult(result);
			result.onmousedown = selectResult;
			result.onmouseover = highlightResult;
			result.onmouseout = unhighlightResult;
			var result1 = document.createElement("span");
			result1.className = "result1";
			result1.style.textAlign = "left";
			nodeLastName=valueNodes[0].getElementsByTagName('text')[0];
			result1.innerHTML = nodeLastName.firstChild.nodeValue;
    
			// Let's use a physical table instead of concatenated spans
			oTable = document.createElement("table");
			oTable.setAttribute("width","251");
			oRow = oTable.insertRow(oTable.rows.length);
			oCell = oRow.insertCell(oRow.cells.length);
			oCell.appendChild(result1);
			result.appendChild(oTable);
			div.appendChild(result);
		}
	}else{
		// if there are no results then show a courtesy message
		var result1 = document.createElement("span");
		result1.className = "result1";
		result1.style.textAlign = "left";
		result1.innerHTML = 'No Results Found';
		oTable = document.createElement("table");
		oRow = oTable.insertRow(oTable.rows.length);
		oCell = oRow.insertCell(oRow.cells.length);
		oCell.appendChild(result1);
		div.appendChild(oTable);
	}
  
	// if this resultset isn't already in our cache, add it
	var isCached = cache[queryString];
	if (!isCached)
		addToCache(queryString, globalDom);
  	// display the div if we had at least one result
	showDiv(1);
}
/**
This is called whenever the user clicks one of the lookup results.
It puts the value of the result in the queryField and hides the lookup div.
*/
function selectResult(){
	_selectResult(this);
}
/** This actually fills the field with the selected result and hides the div */
function _selectResult(item){
	var spans = item.getElementsByTagName("span");
	if (spans) {
		for (var i = 0; i < spans.length; i++) {
			if (spans[i].className == "result1") {
				queryField.value = spans[i].innerHTML;
				lastVal = val = escape(queryField.value);
				searching = false;
				mainLoop();
				queryField.focus();
				showDiv(false);
				return;
			}
		}
	}
}
/**
This is called when a user mouses over a lookup result
*/
function highlightResult(){
	_highlightResult(this);
}
/** This actually highlights the selected result */
function _highlightResult(item){
	item.style.backgroundColor = DIV_HIGHLIGHT_COLOR;
}
/**
This is called when a user mouses away from a lookup result
*/
function unhighlightResult(){
	_unhighlightResult(this);
}
/** This actually unhighlights the selected result */
function _unhighlightResult(item){
	item.style.backgroundColor = DIV_BG_COLOR;
}
/**
This either shows or hides the lookup div, depending on the value of
the "show" parameter.
*/
function showDiv (show){
	var div = getDiv(divName);
	if (show)
		div.style.visibility = "visible";
	else
		div.style.visibility = "hidden";
	adjustiFrame();
}
/**
We originally used showDiv as the function that was called by the onBlur
event of the field, but it turns out that Firefox will pass an event as the first
parameter of the function, which would cause the div to always be visible.
So onBlur now calls hideDiv instead.
*/
function hideDiv (){
	showDiv(false);
}
/**
Use an "iFrame shim" to deal with problems where the lookup div shows up behind
selection list elements, if they're below the queryField. The problem and solution are
described at:
http://dotnetjunkies.com/WebLog/jking/archive/2003/07/21/488.aspx
http://dotnetjunkies.com/WebLog/jking/archive/2003/10/30/2975.aspx
*/
function adjustiFrame(){
	if (!document.getElementById(ifName)) {
		var newNode = document.createElement("iFrame");
		newNode.setAttribute("id", ifName);
		newNode.setAttribute("src", "javascript:false;");
		newNode.setAttribute("scrolling", "no");
		newNode.setAttribute("frameborder", "0");
		document.body.appendChild(newNode);
	}
  
	iFrameDiv = document.getElementById(ifName);
	var div = getDiv(divName);
  
	try {
		iFrameDiv.style.position = "absolute";
		iFrameDiv.style.width = div.offsetWidth;
		iFrameDiv.style.height = div.offsetHeight;
		iFrameDiv.style.top = div.style.top;
		iFrameDiv.style.left = div.style.left;
		iFrameDiv.style.zIndex = div.style.zIndex - 1;
		iFrameDiv.style.visibility = div.style.visibility;
	} catch(e) {
	}
}
/**
This sets up the XMLHTTP object we're using for the dynamic lookups.
*/
function getXMLHTTP(){
	var A = null;
  
	try{
		A = new ActiveXObject("Msxml2.XMLHTTP");
	}catch(e){
		try{
			A = new ActiveXObject("Microsoft.XMLHTTP");
		} catch(oc){
			A = null;
		}
	}
  
	if(!A && typeof XMLHttpRequest != "undefined") {
		A = new XMLHttpRequest();
	}
	return A;
}
/**
This actually sends the lookup request (as a URL with a query string) to a
server in the background. When a response comes back from the server, the
function attached to the onReadyStateChange event is fired off.
*/
function doRemoteQuery(queryString){
	searching = true;
	if(xmlHttp && xmlHttp.readyState != 0) {
		xmlHttp.abort()
	}
  
	xmlHttp=getXMLHTTP();
	if(xmlHttp){
		xmlHttp.open("GET", getLookupURL(queryString), true);
    
		// What do we do when the response comes back?
		xmlHttp.onreadystatechange = function() {
			if (xmlHttp.readyState == 4 && xmlHttp.responseText && searching) {
				searching = false;
				globalDom = xmlHttp.responseXML;
				showQueryDiv(val);
			}
		} ;
    
		xmlHttp.send(null);
	}
}
/**
This is the key handler function, for when a user presses the up arrow,
down arrow, tab key, or enter key from the input field.
*/
function keypressHandler (evt){
	// don't do anything if the div is hidden
	var div = getDiv(divName);
	if (div.style.visibility == "hidden")
		return true;
  
	// make sure we have a valid event variable
	if(!evt && window.event) {
		evt = window.event;
	}
	var key = evt.keyCode;
  
	// if this key isn't one of the ones we care about, just return
	var KEYUP = 38;
	var KEYDOWN = 40;
	var KEYENTER = 13;
	var KEYTAB = 9;
  
	if ((key != KEYUP) && (key != KEYDOWN) && (key != KEYENTER) && (key != KEYTAB))
		return true;
  
	// get the span that's currently selected, and perform an appropriate action
	var selNum = getSelectedSpanNum(div);
	var selSpan = setSelectedSpan(div, selNum);
  
	if ((key == KEYENTER) || (key == KEYTAB)) {
		if (selSpan)
			_selectResult(selSpan);
		evt.cancelBubble=true;
		return false;
	} else {
		if (key == KEYUP)
			selSpan = setSelectedSpan(div, selNum - 1);
		if (key == KEYDOWN)
			selSpan = setSelectedSpan(div, selNum + 1);
		if (selSpan)
			_highlightResult(selSpan);
	}
  	showDiv(true);
	return true;
}
/**
Get the number of the result that's currently selected/highlighted
(the first result is 0, the second is 1, etc.)
*/
function getSelectedSpanNum (div){
	var count = -1;
	var spans = div.getElementsByTagName("div");
	if (spans) {
		for (var i = 0; i < spans.length; i++) {
			count++;
			if (spans[i].style.backgroundColor != div.style.backgroundColor)
				return count;
		}
	}
	return -1;
}
/**
Select/highlight the result at the given position
*/
function setSelectedSpan (div, spanNum){
	var count = -1;
	var thisSpan;
	var spans = div.getElementsByTagName("div");
	if (spans) {
		for (var i = 0; i < spans.length; i++) {
			if (++count == spanNum) {
				_highlightResult(spans[i]);
				thisSpan = spans[i];
			} else {
				_unhighlightResult(spans[i]);
			}
		}
	}
	return thisSpan;
}
// function that allows URL customization
function getLookupURL(queryString){
	var strURL = 'http://www.pets4homes.co.uk/pets4homes/Location.nsf/Locations?readviewentries&startKey=' + queryString + '&untilKey=' + queryString + 'z&count=10';
	return strURL;
}
