//thank you fromvega.com, for the vast majority of this code

// global variables
var acListTotal   =  0;
var acListCurrent = -1;
var acDelay		  = 200;
var acURL		  = null;
var acSearchId	  = null;
var acResultsId	  = null;
var acSearchField = null;
var acResultsDiv  = null;
var search_text_left = 0;
var search_text_top = 0;
var search_text_width = 0;

function setAutoComplete(field_id, results_id){

	// initialize vars
	acSearchId  = "#" + field_id;
	acResultsId = "#" + results_id;

	// create the results div
	$("body").append('<div id="' + results_id + '"></div>').append('<iframe id="changeTest" style="position:absolute;top:-5000px;width:100em;"></iframe>');
	// register mostly used vars
	acSearchField	= $(acSearchId);
	acResultsDiv	= $(acResultsId);  
	// reposition div
	repositionResultsDiv();
	//check for real-time repositioning
    window.onresize = repositionResultsDiv;
  if (navigator.appName.indexOf("Microsoft") != -1) document.getElementById('changeTest').onresize = repositionResultsDiv;
	else document.getElementById('changeTest').contentWindow.onresize = repositionResultsDiv;
	
	document.getElementById(field_id).onfontresize = repositionResultsDiv;
	// on blur listener
	acSearchField.blur(function(){ setTimeout("clearAutoComplete()", 200) });

	// on key up listener
	acSearchField.keyup(function (e) {

		// get keyCode (window.event is for IE)
		var keyCode = e.keyCode || window.event.keyCode;
		var lastVal = acSearchField.val();

		// check an treat up and down arrows
		if(updownArrow(keyCode)){
			return;
		}

		// check for an ENTER or ESC
		if(keyCode == 13 || keyCode == 27){
		  //if ENTER, we must cancel the incoming hollerBack doing the number search
		  if (keyCode == 13) CancelVisDebug = true;
			clearAutoComplete();
			return;
		}

		// if is text, call with delay
		setTimeout(function () {autoComplete(lastVal)}, acDelay);
	});
}

// treat the auto-complete action (delayed function)
function autoComplete(lastValue) {
	// get the field value
	var part = acSearchField.val();

	// if it's empty clear the resuts box and return
	if(part == ''){
		clearAutoComplete();
		return;
	}

	// if it's equal the value from the time of the call, allow
	if(lastValue != part){
		return;
	}
  new holler('GET','main.do?1=1','module=ajax.ajax_search_suggests&search_query='+lastValue,'displaySuggests(xmlhttp.responseText)');
}

// clear auto complete box
function clearAutoComplete()
{
  acResultsDiv.html('');
	acResultsDiv.css("display","none");
}

// reposition the results div accordingly to the search field
function repositionResultsDiv() {
  // get the field position
	var sf_pos = acSearchField.offset();
	var sf_top = search_text_top = sf_pos.top;
	var sf_left = search_text_left = sf_pos.left;

	// get the field size
	var sf_height = acSearchField.height();
	var sf_width  = search_text_width = acSearchField.width();

	// apply the css styles - optimized for Firefox
	acResultsDiv.css("position","absolute");
	acResultsDiv.css("left", sf_left - 2);
	acResultsDiv.css("top", sf_top + sf_height + 5);
	acResultsDiv.css("width", sf_width - 2);
	acResultsDiv.css('opacity', 0.7);
}


// treat up and down key strokes defining the next selected element
function updownArrow(keyCode) {
	if(keyCode == 40 || keyCode == 38){

		if(keyCode == 38){ // keyUp
			if(acListCurrent == 0 || acListCurrent == -1){
				acListCurrent = acListTotal-1;
			}else{
				acListCurrent--;
			}
		} else { // keyDown
			if(acListCurrent == acListTotal-1){
				acListCurrent = 0;
			}else {
				acListCurrent++;
			}
		}

		// loop through each result div applying the correct style
		acResultsDiv.children().each(function(i){
			if(i == acListCurrent){
				acSearchField.val(this.childNodes[0].nodeValue);
				this.className = "selected";
			} else {
				this.className = "unselected";
			}
		});

		return true;
	} else {
		// reset
		acListCurrent = -1;
		return false;
	}
}

function checkResultsDivPos(){
  var field = document.getElementById(acSearchId.slice(1));  
  alert(field.width);
  alert(search_text_width);
  if (field.width == search_text_width /*&& acSearchField.offset() == "{"++"}"*/) {
    return;
  }
  //check if these vars are correct
  else {
    alert(false);
    repositionResultsDiv();
  }
}

function displaySuggests(){
  var args = eval(arguments[0]); //evaluates to an array made of the suggest values
  if (args.length > 0) {
    var newData = '';
    for (i=0; i < args.length; i++) {
      newData += '<div class="unselected">' + args[i] + '</div>';
    }
    acListTotal = args.length;
    acResultsDiv.css("visibility","visible");
    acResultsDiv.css('border','1px solid black')
    acResultsDiv.html(newData);
    acResultsDiv.css("display","block");
    //for all divs in results
    var divs = $(acResultsId + " > div");
    divs.mouseover( function() {
        divs.each(function(){ this.className = "unselected";});
        this.className = "selected";
      })
    divs.click( function() {
      acSearchField.val(this.childNodes[0].nodeValue);
      clearAutoComplete();
    });
  }
  else {
    clearAutoComplete();
  }
}

