// Note: some functions and ideas from http://www.nsftools.com/tips/ZipLookupTest.htm

// holder for instances of suggestion processes,
// such that a single html page can have more than
// one suggestion box
var suggestions = new Array();

/*
* Initialize suggestion process using the SACK object from the ajax.js class
* Creates an ajax object and gives it the action php script to call
* and determines which js function to call after returning from that script
* Takes: 
*	sql_key: name of column in database table that wil be looking through
*	sql_table: name of database table that will be searching
*	suggest_box: the ID name in HTML of the <div> that will be the drop down box
*	query_box: the ID name in HTML of the text form element that will be autocompleted
* Returns: index number into suggestions array, i.e. which suggestion process it is
*/
function init_suggest(sql_key,sql_table,suggest_box,query_box) {
	var self;
	var index = suggestions.length;
	var suggest = new Array();
	suggestions[index] = suggest;
	
	var ajaxObj = new sack();
	
	document.getElementById(query_box).onblur = function() { showDiv(false,index); };
	//document.getElementById(query_box).onkeydown = function() { keyPressHandler (index);};
	document.getElementById(query_box).onkeydown = handlerHelper;
	
	suggest['lastVal'] = "";
	suggest['queryBox'] = query_box;
	suggest['suggestBox'] = suggest_box;
	suggest['key'] = sql_key
	suggest['table'] = sql_table;
	suggest['ajaxObj'] = ajaxObj;
	
	suggest['ajaxObj'].requestFile = "scripts/suggestion.php";
	suggest['ajaxObj'].method = "POST";
	suggest['ajaxObj'].onCompletion = function() { showResults(index); };
	
	//setTimeout("sendQuery(index)",6000);
	return index;
}

function showDiv (show,index)
{
  var div =document.getElementById(suggestions[index]['suggestBox'])
  if (show)
    div.style.visibility = "visible";
  else
    div.style.visibility = "hidden";

}

/*
function startPolling(index)
{
	var suggest = suggestions[index];
	if (suggest['interval']=="") {
		suggest['interval'] = setInterval("sendQuery(index)",500);
	}
	
}
*/

/*
* What is called on every key press or whatever
* Sets the parameters of the AJAX request and executes it
* Takes: index into suggestions array
*/	
function sendQuery(index) {
	var suggest = suggestions[index];
	query = document.getElementById(suggest['queryBox']).value;
	
	// don't run query if haven't changed query value
	if (query == suggest['lastVal'])
		return;
	else suggest['lastVal'] = query;
	suggest['ajaxObj'].setVar("query",query);	
	suggest['ajaxObj'].setVar("sql_key",suggest['key']);	
	suggest['ajaxObj'].setVar("sql_table",suggest['table']);
	suggest['ajaxObj'].runAJAX();
	//setTimeout("sendQuery(index)",100);
}

/*
* This is called automatically after the AJAX call returns (see init function)
* It locates the <div> of the drop down box and fills it with the results
*/
function showResults(index){
	var suggest = suggestions[index];
	if (suggest['ajaxObj'].responseStatus[0] != 200) return;
	var data = suggest['ajaxObj'].response.split("\n");
	var suggest_box = document.getElementById(suggest['suggestBox']);
	var query_box = document.getElementById(suggest['queryBox']);
	  var posArray = findPos(query_box);
	  suggest_box.style.left= (posArray[0]-1) + "px";
	  suggest_box.style.top = (posArray[1]+17) + "px";
	  suggest_box.innerHTML = "";
	  for(i=0; i < data.length - 1; i++) {
				//Build our element string.  This is cleaner using the DOM, but
				//IE doesn't support dynamically added attributes.
				var suggestStr = '<div onmouseover=\"javascript:suggestOver(this);\" ';
				suggestStr += 'onmouseout=\"javascript:suggestOut(this);\" ';
				suggestStr += 'onmousedown=\"javascript:setSearch('+index+',this.innerHTML);\" ';
				suggestStr += 'class=\"suggest_item\">' + data[i] + '</div>';
				suggest_box.innerHTML += suggestStr;
		}
		showDiv(true,index);
}

function suggestOver(div_value) {
	div_value.className = 'suggest_item_over';
}

function suggestOut(div_value) {
	div_value.className = 'suggest_item';
}

function setSearch(index,mainvalue) {
	var queryBox = document.getElementById(suggestions[index]['queryBox']);
	queryBox.value = mainvalue;
	queryBox.focus();
	
	//document.getElementById(suggestions[index]['suggestBox']).innerHTML = "";
	showDiv(false,index);
}

// stuff for positioning of the suggestion box beneath its appropriate textbox
function findPos(element) {
	var curleft = curtop = 0;
	if (element.offsetParent) {
		curleft = element.offsetLeft;
		curtop = element.offsetTop; 
		while (element= element.offsetParent) {
			curleft += element.offsetLeft;
			curtop += element.offsetTop;
		}
	}
	return [curleft,curtop];
}


//Get the number of the result that's currently selected/highlighted
// (the first result is 0, the second is 1, etc.)

function getSelectedSpanNum (suggestBox)
{
  var num = 0;
  var count = -1;
  var spans = suggestBox.getElementsByTagName("div"); // get <div>s within suggest div
  if (spans) {
    for (var i = 0; i < spans.length; i++) {
      count++;
      if (spans[i].className == "suggest_item_over") {
		num = count; // stop counting up when have the highlighted item
	  }
    }
  }
  return num;
  return -1;
}


//Select/highlight the result at the given position
function setSelectedSpan (suggestBox, spanNum)
{
  var count = -1;
  var thisSpan;
  var spans = suggestBox.getElementsByTagName("div");
  if (spans) {
    for (var i = 0; i < spans.length; i++) {
      if (++count == spanNum) {
        spans[i].className = "suggest_item_over";
        thisSpan = spans[i];
      } else {
        spans[i].className = "suggest_item";
      }
    }
  }
  
  return thisSpan;
}

// called on key press
// first figure out which html element generated event
// then call real key press handler
function handlerHelper(e)
{
	var targ;
		if (!e) var e = window.event;
		if (e.target) targ = e.target;
		else if (e.srcElement) targ = e.srcElement;
		if (targ.nodeType == 3) // defeat Safari bug
			targ = targ.parentNode;
	for(var i=0; i<suggestions.length; i++)
	{
		if(targ.id == suggestions[i]['queryBox'])
			keyPressHandler(e,i);
	}
}

/**
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,index)
{
	
  // don't do anything if the div is hidden
  var div = document.getElementById(suggestions[index]['suggestBox']);
  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)
    	setSearch(index,selSpan.innerHTML);
    evt.cancelBubble=true;
    return false;
  } else {
    if (key == KEYUP)
    	selSpan = setSelectedSpan(div, selNum - 1);
    if (key == KEYDOWN)
    	selSpan = setSelectedSpan(div, selNum + 1);
    if (selSpan)
      suggestOver(selSpan);
  }
  
  showDiv(true,index);
  return true;

}

