// global variables
var acListTotal   =  0;
var acListCurrent = -1;
var acDelay		  = 0;
var acURL		  = null;
var acSearchId	  = null;
var acResultsId	  = null;
var acSearchField = null;
var acResultsDiv  = null;
var minLength	  = 2;
var focusedField  = null;
var classField = null;
var searchType = null;

function updateAutoComplete(stype)
{
	searchType = stype;
}

function setAutoComplete(field_id, results_id, fclass, get_url, stype)
{
	if(focusedField == results_id)
	{	
		return;		
	}
	
	focusedField = results_id;
		
	if(acResultsDiv != null)
	{
		clearAutoComplete();
	}
					
	// initialize vars
	acSearchId  = "#" + field_id;
	acResultsId = "#" + results_id;
	classField  = fclass;
	searchType = stype;
	acURL 		= get_url;
	var just_created = false;		
	
	
	// create the results div		
	if(document.getElementById(field_id) != null && document.getElementById(results_id) == null)
	{	
		just_created = true;			
		//jQuery(acSearchId).after('<div id="' + results_id + '" class="' + classField + '"></div>');			
		jQuery('#header').after('<div id="' + results_id + '" class="' + classField + '"></div>');
	}

	// register mostly used vars
	acSearchField	= jQuery(acSearchId);
	acResultsDiv	= jQuery(acResultsId);

	// reposition div
	repositionResultsDiv();
	
	if(just_created)
	{		
		// on blur listener
		acSearchField.blur(function(){ setTimeout("clearAutoComplete()", 200) });
	
		// on key down listener - for tab and for enter 
		acSearchField.keydown(function(e){
			
			// get keyCode (window.event is for IE)
			var keyCode = e.keyCode || window.event.keyCode;
			var lastVal = acSearchField.val();
			
			if(keyCode == 13 || keyCode == 9)
			{					
				var divs_text = jQuery(acResultsId + " div");				
				divs_text.each(function(i){
					if(i == acListCurrent+1) 
					{ 												
						acSearchField.val(this.childNodes[0].nodeValue);		
					}					
				});
									
				clearAutoComplete();
				return;
			}
		});
	
		// 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){			
				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 == '' || part.length < minLength){
		clearAutoComplete();
		return;
	}

	// if it's equal the value from the time of the call, allow
	if(lastValue != part){
		return;
	}
	
	type_par = "";
	
	if(searchType != null)
	{
		type_par = "/" + searchType; 
	}
	
	var mybrowser = "notdetected";
	jQuery.each(jQuery.browser, function(i, val) {
  		if(i=="mozilla" && val==true) mybrowser = i;
  		if(i=="safari" && val==true) mybrowser = i;
  		if(i=="opera" && val==true) mybrowser = i;
  		if(i=="msie" && val==true) mybrowser = i;
	});
		
	// get remote data as JSON		
	jQuery.getJSON(acURL + part + type_par, {browser:mybrowser}, function(json){
		
		var ansLength = acListTotal = json.length;
				
		// if there are results populate the results div		
		if(ansLength > 0){

			var newData = '<div class="search_frame_up"><ul>';

			// create a div for each result
			for(i=0; i < ansLength; i++) {
				newData += '<li class="unselected"><div class="search_text">' + json[i] + '</div></li>';
			}
			newData += '</ul></div>';
			// update the results div
											
			acResultsDiv.html(newData);		
			// css for results div	
			cssForResultsDiv();
						
			acResultsDiv.css("display","block");
			
			// for all divs in results
			var divs = jQuery(acResultsId + " li");
			
			/*divs.each(function(){ 
				//alert(this);
				this.keydown(function(){
					var keyCode = e.keyCode || window.event.keyCode;
					var lastVal = acSearchField.val();
					alert("3");
					if(keyCode == 9){
						alert("2");			
						clearAutoComplete();					
					}
				})*/
				
			//divs.keydown(function(){				 	
				//var keyCode = e.keyCode || window.event.keyCode;
				//var lastVal = acSearchField.val();
				//alert("3");
				//if(keyCode == 9){
				//	alert("2");			
				//	clearAutoComplete();					
				//}				
			//})
			
		
			// on mouse over clean previous selected and set a new one
			divs.mouseover( function() {
				divs.each(function(){ 
				this.className = "unselected";
				});
				this.className = "selected";
			})
			
			var divs_text = jQuery(acResultsId + " div");
			// on click copy the result text to the search field and hide
			divs_text.click( function() {
				acSearchField.val(this.childNodes[0].nodeValue);
				clearAutoComplete();
			});
						
		} else {
			clearAutoComplete();
		}
	});
	
}

// clear auto complete box
function clearAutoComplete()
{
	acResultsDiv.html('');
	acResultsDiv.css("display","none");		
}

// css for the results 
function cssForResultsDiv()
{	
}


// reposition the results div accordingly to the search field
function repositionResultsDiv()
{
	// get the field position
	var sf_pos    = acSearchField.offset();
	var sf_top    = sf_pos.top;
	var sf_left   = sf_pos.left;

	// get the field size
	var sf_height = acSearchField.height();
	var sf_width  = acSearchField.width();
	
	if(classField == 'ac_results_search')
	{			
		/*acResultsDiv.css("position","absolute");	
		acResultsDiv.css("top", sf_height - 4); //25
		acResultsDiv.css("left",-3);		
		acResultsDiv.css("width",sf_width+2);
		acResultsDiv.css("z-index", 999);*/
		acResultsDiv.css("display", "none");
		
	}
	else if(classField == 'ac_results_ingredients')
	{				
		//apply the css styles - optimized for Firefox
		/*
		acResultsDiv.css("position","absolute");	
		acResultsDiv.css("left", sf_left - 10);
		acResultsDiv.css("top", sf_top - sf_height -9);
		acResultsDiv.css("width", sf_width + 8);
		acResultsDiv.css("display", "none");
		*/
		
		//acResultsDiv.css("position","absolute");	
		//acResultsDiv.css("left", sf_left - 10);
		acResultsDiv.css("top", sf_top - sf_height -9);
		acResultsDiv.css("width", sf_width + 8);
		acResultsDiv.css("display", "none");
	}
}

// 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++;
			}
		}

		// for all divs in results
		var divs = jQuery(acResultsId + " li");
		divs.each(function(i){
			if(i != acListCurrent)
			{ 
				this.className = "unselected";
			}
			else
			{
				this.className = "selected";
			}
		});
				
		// 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;
	}
}