/**
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

I stripped out a lot of the cool functionality (like variable timers and
highlighting parts of the search result). That was mainly to make this a little
easier to digest. Feel free to look at the JavaScript code that Chris Justus
reformatted (see the link above) and put back anything that's missing.

In version 1.2 support was added for capturing keypresses of arrow keys,
the enter key, and the tab key while the input field has focus.

You can use these scripts in any way you'd like, just don't pretend like
you wrote them yourself.

version 1.2
January 5, 2005
Julian Robichaux, http://www.nsftools.com

Feb 24, 2006
Added support for multiple controls
Ryan Homer
*/

var axl_qF;
var axl_ifName = "axl_iFrame"; // just some unique name for the iFrame
var axl_lastVal = new Array(); // keep track of last value typed for each control
var axl_cache = new Object();
var axl_cbFn="";
var axl_ctlCnt = 0; // keep track of number of controls on page
var axl_ctls = new Array(); // store control IDs in array
var axl_div; // current div for the corresponding control in focus
var axl_divs = new Object();
var axl_cbFns = new Object(); // callback functions
var axl_timeout = 1000;

/**
The InitQueryCode function will be called by dynamically generated java script
from the AjaxLookup .NET control.

All three parameters must be passed in this version that supports multiple controls.
These fields are:

queryFieldName = the name of the form field we're using for lookups
hiddenDivName = the name of the div tag used to show the results. If the div tag
already exists, it'll use that tag, otherwise the tag will be dynamically created.
callBackFunction = the .NET lookup function to be used

The callBack function will be expected to return an array of responses. Each response
should also be an array with a pair of responses. Example:

[ ["AZ", "Arizona"], ["CA", "California"], ["GA", "Georgia"] ]

Notice that this is different from the former implementation, which expected two separate
arrays. Then in the version used for the AjaxLookup control, this was reduced to one array.
Since it is not possible for a function to return two sets of separate results, these
results must be returned as noted above.
*/
function InitQueryCode(queryFieldName, hiddenDivName, callBackFunction)
{
  axl_qF = document.getElementById(queryFieldName);
  axl_qF.onblur = hideDiv;
  axl_qF.onkeydown = keypressHandler;
  axl_qF.onfocus = onFocusHandler;

  // 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
  axl_qF.autocomplete = "off";
  
  // Store a reference to each control in an array which will be polled
  // one at a time in the mainLoop(). Also keep track of the call back functions
  axl_ctls[axl_ctlCnt] = axl_qF;
  //axl_cbFns[axl_ctlCnt] = callBackFunction;
  axl_cbFns[queryFieldName]=callBackFunction;
  
  // Keep track of last value typed for EACH control.
  // NB: Initializing variable to "" doesn't work right here after a postback.
  // It makes the div show on the last control on the page but with the results
  // of what's currently typed in the first control.
  axl_lastVal[axl_ctlCnt] = null; 
  
  axl_ctlCnt++; // get ready for next control
  
  // fyi: axl_qF must be set before the call to getDiv
  // a call to this function will set up the div's attributes, position, etc.
  // this is only called once per control, unlike the previous implementation
  axl_div = getDiv(hiddenDivName);
  
  // The DIVs are also stored, not by index number, but by queryFieldName (hash table)
  // This is because while we know the index number of the control when we poll in the
  // mainLoop, we only know which control the user is currently at when we intercept
  // a keypress. This is set in the onfocus event for the control, so at any point,
  // we at least know the queryField's control name.
  axl_divs[queryFieldName] = axl_div;
  
  // 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
  // "blank" = queryFieldName + "" ... so that each control's results are kept track of
  // separately. We'll always search in the cache with at least the query field's ID
  // as the start of the search key
  //addToCache(queryFieldName, new Array());
  addToCache(callBackFunction, new Array());
  
  // we only need to call this once, no matter how many control are on the page
  if (axl_ctlCnt==1) { setTimeout("mainLoop()", axl_timeout); }
}

/**
This is a helper function that just adds results to our cache, to avoid
repeat lookups.
*/
function addToCache (qStr, resultArray)
{
	if(!axl_cache[qStr])
		axl_cache[qStr] = resultArray;
}

/**
Get the <DIV> we're using to display the lookup results, and create the
<DIV> if it doesn't already exist.

20060223: This procedure now only gets called ONCE for EACH control on the page.
When a reference to the div is needed later, the axl_divs[] array is referenced directly.
This function now only does the initial setup of the DIVs.
*/
function getDiv (divID)
{
	var newNode = null;
	var div;
	
    // if the div doesn't exist on the page already, create it
	if (!document.getElementById(divID)) {
		newNode = document.createElement("div");
		newNode.setAttribute("id", divID);
		document.body.appendChild(newNode);
    }
    
    // set the globalDiv reference
    div = document.getElementById(divID);
        
    // add some formatting to the div
	//eval("div.style.backgroundColor="+axl_qF.id+"DIV_BG_COLOR;");
	//eval("div.style.fontFamily="+axl_qF.id+"DIV_FONT;");
	//eval("div.style.padding="+axl_qF.id+"DIV_PADDING;");
	//eval("div.style.border="+axl_qF.id+"DIV_BORDER;");
	//eval("div.style.width="+axl_qF.id+"DIV_WIDTH;");
	//eval("div.style.fontSize="+axl_qF.id+"FONT_SIZE;");
	div.style.backgroundColor=eval(axl_qF.id+"DIV_BG_COLOR;");
	div.style.fontFamily=eval(axl_qF.id+"DIV_FONT;");
	div.style.padding=eval(axl_qF.id+"DIV_PADDING;");
	div.style.border=eval(axl_qF.id+"DIV_BORDER;");
	div.style.width=eval(axl_qF.id+"DIV_WIDTH;");
	div.style.fontSize=eval(axl_qF.id+"FONT_SIZE;");
  
	if (newNode) {
  		// we're only setting the x,y coords if we created the div ourselves.
		// otherwise, we're assuming that the webpage designed wanted it in 
		// a specific position.  
		// figure out where the top corner of the div should be, based on the
		// bottom left corner of the input field
		var x = axl_qF.offsetLeft;
		var y = axl_qF.offsetTop + axl_qF.offsetHeight;
		
		var qwidth = (axl_qF.offsetWidth - 6);
		
		var parent = axl_qF;
		while (parent.offsetParent) {
			parent = parent.offsetParent;
			x += parent.offsetLeft;
			y += parent.offsetTop;
		}
		div.style.position = "absolute";
		div.style.left = x + "px";
		div.style.top = y + "px";
	}
    div.style.visibility = "hidden";
    div.style.zIndex = 10000;
    
    div.style.fontSize = "11"; 
    div.style.fontStyle = "normal";
    div.style.width = qwidth + "px" ;    
    div.style.textAlign = "left";

	return div;
}


/**
This function is called by the mainLoop, when results are returned
from the callback function
*/
function showQueryDiv (qStr, results, index)
{
  if (!results) return;
  
  var div = axl_divs[axl_qF.id];
  
  // 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 resultArray
  for (var i = 0; i < results.length; i++)
  {
	if (results[i][0] == "!more")
	{
		var result = document.createElement("div");
		result.style.cursor = "not-allowed";
		//eval("result.style.borderBottom="+axl_qF.id+"ITEMSTYLE_BORDERBOTTOM;");
		//eval("result.style.padding="+axl_qF.id+"ITEMSTYLE_PADDING;");
		result.style.borderBottom=eval(axl_qF.id+"ITEMSTYLE_BORDERBOTTOM;");
		result.style.padding=eval(axl_qF.id+"ITEMSTYLE_PADDING;");
		_unhighlightResult(result);
		var r = document.createElement("span");
		r.className = "r";
		r.style.textAlign = "right";
		r.innerHTML = results[i][1];
		result.appendChild(r);
		div.appendChild(result);
		
		// exit loop
		i=results.length;
	}
	else
	{
		// each result will be contained within its own div
		var result = document.createElement("div");
		result.style.cursor = "pointer";
		//eval("result.style.borderBottom="+axl_qF.id+"ITEMSTYLE_BORDERBOTTOM;");
		//eval("result.style.padding="+axl_qF.id+"ITEMSTYLE_PADDING;");
		result.style.borderBottom=eval(axl_qF.id+"ITEMSTYLE_BORDERBOTTOM;");
		result.style.padding=eval(axl_qF.id+"ITEMSTYLE_PADDING;");

		_unhighlightResult(result);
		result.onmousedown = selectResult;
		result.onmouseover = highlightResult;
		result.onmouseout = unhighlightResult;

		var result1 = document.createElement("span");
		result1.className = "result1"+index;
		result1.style.textAlign = "left";
		//eval("result1.style.fontWeight="+axl_qF.id+"FONT_WEIGHT;");
		//result1.style.fontWeight=eval(axl_qF.id+"FONT_WEIGHT;");
		//result1.innerHTML = results[i][0];
		result1.innerHTML = results[i];

		var result2 = document.createElement("span");
		result2.className = "result2";
		//result2.style.textAlign = "right";
		//eval("result2.style.paddingLeft="+axl_qF.id+"ITEMSTYLE_SPACING;");
		result2.style.paddingLeft=eval(axl_qF.id+"ITEMSTYLE_SPACING;");
		//result2.innerHTML = results[i][1];
		result2.innerHTML = results[i];

		result.appendChild(result1);
		//result.appendChild(result2);
		div.appendChild(result);
    }
  }
  
  // if this resultset isn't already in our cache, add it
  //var cacheKey = axl_qF.id+qStr;
  var cacheKey = axl_cbFn+qStr;
  var isCached = axl_cache[cacheKey];
  if (!isCached)
    addToCache(cacheKey, results)
  
  // display the div if we had at least one result
  showDiv(results.length > 0);
}


/**
This is called whenever the user clicks one of the lookup results.
It puts the value of the result in the axl_qF 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++) {
	  var spanName = spans[i].className;
	  var spanLen = spanName.length;
	  var spanNameL = spanName.substring(0,7);
	  //var spanIndex = spanName.substring(7,spanLen)+0;
      if (spanNameL == "result1") {
        axl_qF.value = spans[i].innerHTML;
        //axl_lastVal[spanIndex] = val = escape(axl_qF.value);
        //searching = false;
        mainLoop();
        axl_qF.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)
{
  //eval("item.style.backgroundColor="+axl_qF.id+"DIV_HIGHLIGHT_COLOR;");
  item.style.backgroundColor=eval(axl_qF.id+"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)
{
  //eval("item.style.backgroundColor="+axl_qF.id+"DIV_BG_COLOR;");
  item.style.backgroundColor=eval(axl_qF.id+"DIV_BG_COLOR;");
}


/**
This either shows or hides the lookup div, depending on the value of
the "show" parameter.
*/
function showDiv (show)
{
  if (show)
    axl_div.style.visibility = "visible";
  else
    axl_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 axl_qF. 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(axl_ifName)) {
    var newNode = document.createElement("iFrame");
    newNode.setAttribute("id", axl_ifName);
    newNode.setAttribute("src", "javascript:false;");
    newNode.setAttribute("scrolling", "no");
    newNode.setAttribute("frameborder", "0");
    document.body.appendChild(newNode);
  }
  
  iFrameDiv = document.getElementById(axl_ifName);
  try {
    iFrameDiv.style.position = "absolute";
    iFrameDiv.style.width = axl_div.offsetWidth;
    iFrameDiv.style.height = axl_div.offsetHeight;
    iFrameDiv.style.top = axl_div.style.top;
    iFrameDiv.style.left = axl_div.style.left;
    iFrameDiv.style.zIndex = axl_div.style.zIndex - 1;
    iFrameDiv.style.visibility = axl_div.style.visibility;
  } catch(e) {
  }
}


/**
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
  if (axl_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(axl_div);
  var selSpan = setSelectedSpan(axl_div, selNum);
  
  if ((key == KEYENTER) || (key == KEYTAB)) {
    if (selSpan)
      _selectResult(selSpan);
    evt.cancelBubble=true;
    return false;
  } else {
    if (key == KEYUP)
      selSpan = setSelectedSpan(axl_div, selNum - 1);
    if (key == KEYDOWN)
      selSpan = setSelectedSpan(axl_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]);
      }
    }
    if (spanNum==spans.length) _highlightResult(spans[count]); // don't go past last one
  }
  
  return thisSpan;
};

/**
This is the function that monitors the axl_qF, and calls the lookup
functions when the queryField value changes.
*/
mainLoop = function() {
	var i, val;
	var ss;
	for (i=0; i<axl_ctlCnt; i++) {
		var currQueryField = axl_ctls[i];
		val = currQueryField.value;	
		//ss = new String(val);
		//ss.replace("'","''");	
		val = val.replace("'","");
		if(axl_lastVal[i] != val /*&& searching == false*/){
			//var cacheKey = currQueryField.id+val;
			var cacheKey = axl_cbFns[currQueryField.id]+val;
			var cacheResult = axl_cache[cacheKey];
			if (cacheResult)
				showQueryDiv(val, cacheResult, i);
			else {
				//var response = eval(axl_cbFns[i]+"('"+val+"');");				
				var response = eval(axl_cbFns[currQueryField.id]+"('"+ val +"');");
				showQueryDiv(val, response.value, i);
			}
			axl_lastVal[i] = val;
		}
	}
	setTimeout("mainLoop()", axl_timeout);
	return true;
}

function onFocusHandler(evt)
{
	var ctlId;
	if (ie) {
		ctlId = event.srcElement.id;
	} else {
		ctlId = evt.target.id;
	}
	axl_qF = this;
	axl_div = axl_divs[ctlId];
	axl_cbFn = axl_cbFns[ctlId];
}