/**
 * AutoComplete Field - JavaScript Code
 *
 * This is a sample source code provided by fromvega.
 * Search for the complete article at http://www.fromvega.com
 *
 * Enjoy!
 *
 * @author fromvega
 *
 */

// global variables
var XacListTotal   =  0;
var XacListCurrent = -1;
var XacDelay		  = 500;
var XacURL		  = null;
var XacSearchId	  = null;
var XacResultsId	  = null;
var XacSearchField = null;
var XacResultsDiv  = null;

function XsetAutoComplete(field_id, results_id, get_url){

	
	//alert(field_id+results_id+get_url);
	// initialize vars
	XacSearchId  = "#" + field_id;
	XacResultsId = "#" + results_id;
	XacURL 		= get_url;

	// create the results div
	$("body").append('<div id="' + results_id + '"></div>');

	// register mostly used vars
	XacSearchField	= $(XacSearchId);
	XacResultsDiv	= $(XacResultsId);

	// reposition div
	XrepositionResultsDiv();
	
	// on blur listener
	XacSearchField.blur(function(){ setTimeout("XclearAutoComplete()", 200) });

	// on key up listener
	XacSearchField.keyup(function (e) {

		// get keyCode (window.event is for IE)
		var keyCode = e.keyCode || window.event.keyCode;
		var lastVal = XacSearchField.val();

		// check an treat up and down arrows
		if(XupdownArrow(keyCode)){
			return;
		}

		// check for an ENTER or ESC
		if(keyCode == 13 || keyCode == 27){
			XclearAutoComplete();
			return;
		}

		// if is text, call with delay
		setTimeout(function () {XautoComplete(lastVal)}, XacDelay);
	});
}

// treat the auto-complete action (delayed function)
function XautoComplete(lastValue)
{
	// get the field value
	var part = XacSearchField.val();

	// if it's empty clear the resuts box and return
	if(part == ''){
		XclearAutoComplete();
		return;
	}

	// if it's equal the value from the time of the call, allow
	if(lastValue != part){
		return;
	}
	XcallAjaxTable(part);
}

// clear auto complete box
function XclearAutoComplete()
{
	XacResultsDiv.html('');
	XacResultsDiv.css("display","none");
}

// reposition the results div accordingly to the search field
function XrepositionResultsDiv()
{
	// get the field position
	var sf_pos    = XacSearchField.offset();
	var sf_top    = sf_pos.top;
	var sf_left   = sf_pos.left;

	// get the field size
	var sf_height = XacSearchField.height();
	var sf_width  = XacSearchField.width();

	// apply the css styles - optimized for Firefox
	XacResultsDiv.css("position","absolute");
	XacResultsDiv.css("left", sf_left - 2);
	XacResultsDiv.css("top", sf_top + sf_height + 5);
	XacResultsDiv.css("width", sf_width - 2);
}


// treat up and down key strokes defining the next selected element
function XupdownArrow(keyCode) {
	if(keyCode == 40 || keyCode == 38){

		if(keyCode == 38){ // keyUp
			if(XacListCurrent == 0 || XacListCurrent == -1){
				XacListCurrent = XacListTotal-1;
			}else{
				XacListCurrent--;
			}
		} else { // keyDown
			if(XacListCurrent == XacListTotal-1){
				XacListCurrent = 0;
			}else {
				XacListCurrent++;
			}
		}

		// loop through each result div applying the correct style
		XacResultsDiv.children().each(function(i){
			if(i == XacListCurrent){
				XacSearchField.val(this.childNodes[0].nodeValue);
				this.className = "selected";
			} else {
				this.className = "unselected";
			}
		});

		return true;
	} else {
		// reset
		XacListCurrent = -1;
		return false;
	}
}

function XcallAjaxTable(part)
{
	xmlHttp=GetXmlHttpObject();
	if (xmlHttp==null)
	{
		alert ("Your browser does not support AJAX!");
		return;
	} 
	var url="autocomplete.php?part="+part;
	xmlHttp.onreadystatechange=XresponseAjaxTable;
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
}
function XresponseAjaxTable() 
{ 
	if (xmlHttp.readyState==4)
	{ 		
		var x=xmlHttp.responseText; //alert(x);
		
		if(x!='')
		{
			// update the results div
			XacResultsDiv.html(x);
			XacResultsDiv.css("display","block");
			
			// for all divs in results
			var divs = $(XacResultsId + " > div");
		
			// on mouse over clean previous selected and set a new one
			divs.mouseover( function() {
				divs.each(function(){ this.className = "unselected"; });
				this.className = "selected";
			})
		
			// on click copy the result text to the search field and hide
			divs.click( function() {
				XacSearchField.val(this.childNodes[0].nodeValue);
				setDirections();
				XclearAutoComplete();
			});
		}
		else 
		{
			XclearAutoComplete();
		}
	}
}
function GetXmlHttpObject()
{
	var xmlHttp=null;
	try
	{
		// Firefox, Opera 8.0+, Safari
		xmlHttp=new XMLHttpRequest();
	}
	catch (e)
	{
		// Internet Explorer
		try
		{
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e)
		{
			xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
		}
	}
	return xmlHttp;
}