/**
 * 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 acListTotal   =  0;
var acListCurrent = -1;
var acDelay		  = 10;
var acURL		  = null;
var acSearchId	  = null;
var acResultsId	  = null;
var acSearchField = null;
var acResultsDiv  = null;
var acIsDisplayed = false;

function setAutoComplete(field_id, field_value_id, results_id, get_url){

	// initialize vars
	acSearchId  = "#" + field_id;
	acSearchValueId = "#" + field_value_id;
	acResultsId = "#" + results_id;
	acURL 		= get_url;

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

	// register mostly used vars
	acSearchField	= $(acSearchId);
	acSearchFieldValue = $(acSearchValueId);
	acResultsDiv	= $(acResultsId);

	// reposition div
	repositionResultsDiv();
	
	// on blur listener
	//acResultsDiv.bind("mouseleave",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();
		var sendForm = false;
		
		// check an treat up and down arrows
		if(updownArrow(keyCode)){
			return;
		}

		// check for an ENTER or ESC
		if(keyCode == 13 || keyCode == 27){
			if(acIsDisplayed==false && keyCode == 13){
				sendForm = true;
			}
			
			clearAutoComplete(lastVal,false);
			if(sendForm){
				$("#submitsearchbutton").click();
				return true;
			}else{
				return false;
			}
		}

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

}

// treat the auto-complete action (delayed function)
function autoComplete(lastValue)
{
	acIsDisplayed = true;
	
	// get the field value
	var part = acSearchField.val();

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

	// if it's equal the value from the time of the call, allow
	if(lastValue != part){
		return;
	}
	//alert(acURL + part+ "&callback=?");
	// get remote data as JSON
	
	$.getJSON(acURL + part + "&jsoncallback=?", function(json){
		
		// get the total of results
		var ansLength = acListTotal = json.length;
		
		// if there are results populate the results div
		if(ansLength > 0){

			var newData = '';
			
			// create a div for each result
			for(i=0; i < ansLength; i++) {
				var actRow=json[i].split('#');
				newData += '<div class="unselected" id="' + actRow[1] + '">' + actRow[0] + '</div>';
			}

			// update the results div
			acResultsDiv.html(newData);
			acResultsDiv.css("display","block");
			
			// for all divs in results
			var divs = $(acResultsId + " > 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() {
				var v=$(this).attr("id").split('@');
				//acSearchField.val(v[1]);
				acSearchFieldValue.val(v[0]);
				clearAutoComplete(v[1],true);
			});

		} else {
			clearAutoComplete(part,false);
		}
	});
}

var no_follow_changes=false;

// clear auto complete box
function clearAutoComplete(new_val,no_other)
{
	acIsDisplayed = false;
	acResultsDiv.html('');
	acResultsDiv.css("display","none");
	if(!no_follow_changes || no_other){
		$("#lokalita_name").val(new_val);
	}
	if(no_other){
		no_follow_changes=true;
	}
	
	$("#lokalita_name").change( function() { 
		$("#lokalita").val("-1");
	});
}

// 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();

	// apply the css styles - optimized for Firefox
	
	acResultsDiv.css("position","absolute");
	acResultsDiv.css("left", sf_left - 1);
	acResultsDiv.css("top", sf_top + sf_height + 3);
	acResultsDiv.css("width", sf_width + 23);
	*/
}


// treat up and down key strokes defining the next selected element
function updownArrow(keyCode) {
	if(keyCode == 40 || keyCode == 38){
		
		$("#lokalita_name").unbind('change');
		
		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);
				acSearchFieldValue.val($(this).attr("id"));
				*/
				var v=$(this).attr("id").split('@');
				acSearchFieldValue.val(v[0]);
				
				$("#lokalita_name").val(v[1]);
				no_follow_changes=true;
				
				this.className = "selected";
				
				return false;
			} else {
				this.className = "unselected";
			}
		});

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