/**
 * Based (Far Away) on "AutoComplete Field" from fromvega
 * Modified by Guillaume Cariou - Technapol
 */

function set_text( set_text_to, url, id_ref, id_name, show_name, separator){
	var base_url = location.href.substring( 0, location.href.lastIndexOf("/")+1);
	if( separator === ""){
		separator = "-";
	}
    alert(base_url + url + id_ref);
	$.getJSON( base_url + url + id_ref, function(json){
		var text = "";
		if( json[id_ref][id_name] === id_ref){
			$.each( show_name.split( '+'), function(x, acChildPart){
				text += json[id_ref][acChildPart]+separator;
			});
			text = text.substring(0, text.length - 1);
		} else {
			text = "Impossible d'identifier l'élement souhaité";
		}
		$.each( set_text_to.split( '+'), function( i, one_dom){
			$(one_dom).text( text);
			$(one_dom).val( text);
		});
	});
}

function town_autocomplete_callback( parent, item_index, label){
	displayedData="";
	$.each( parent.acItemDisplayName.split( '+'), function(x, acChildPart){
		 displayedData += parent.JSONDatas[item_index][acChildPart]+"-";
	});
	displayedData = displayedData.substring(0, displayedData.length - 1);
	parent.acSearchField.val(displayedData);
	parent.acValueField.val (parent.JSONDatas[item_index][parent.acItemValueName]);
	parent.acValueField.trigger('change');
	return;
}

function default_callback(parent, item_index, label){
	displayedData="";
	$.each( parent.acItemDisplayName.split( '+'), function(x, acChildPart){
		 displayedData += parent.JSONDatas[item_index][acChildPart]+" ";
	});
	displayedData = displayedData.substring(0, displayedData.length - 1);
	parent.acSearchField.val(displayedData);
	parent.acValueField.val (parent.JSONDatas[item_index][parent.acItemValueName]);
	return;
}

function autoCompleteObject( 	append_to, 			//id of the form where i append the results
								results_id, 		//id of the result div
								field_display_id, 	//id of the html object where the display is done
								item_display_name, 	//name of element to display from json return 
								field_value_id, 	//id of the html object where the value is set
								item_value_name, 	//name of element to set in the value of the html objet
								get_url,			//url of the json function to call
								separator,
								callback,			//name of javascript function to call once an item is clicked
								autocomplete_type
							){
	// initialization of vars
	this.acListTotal		=  0;
	this.acListCurrent		= -1;
	this.acDelay			= 500;
	this.acURL				= null;
	this.acSearchId			= null;
	this.acResultsId		= null;
	this.acSearchField		= null;
	this.acResultsDiv		= null;
	this.acValueField		= null;
	this.acAppendTo			= null;
	this.acValueId			= null;
	this.JSONDatas			= null;
	this.acCallback			= default_callback;
	this.acItemValueName	= "id";
	this.acItemDisplayName	= "name";
	// register mostly used vars
	this.acAppendTo 		= "#" + append_to;
	this.acResultsId 		= this.acAppendTo+" #" + results_id;
	this.acSearchId  		= this.acAppendTo+" #" + field_display_id;
	this.acURL 				= get_url;
	this.acSearchField		= $(this.acSearchId);
	$(this.acAppendTo).append('<div class="autocomplete" id="' + results_id + '"></div>');
	this.acResultsDiv		= $(this.acResultsId);
	if( autocomplete_type == ""){
		this.autocomplete_type = 'town';
	} else {
		this.autocomplete_type  = autocomplete_type;
	}
	// remove browsers autocomplete
	this.acSearchField.attr("autocomplete", "off");
	
	if( item_display_name !== ""){
		this.acItemDisplayName = item_display_name;
	}
	if( field_value_id == ""){
		this.acValueId = this.acSearchId
	} else {
		this.acValueId = "#" + field_value_id;
	}

	if( separator != ""){
		this.separator		= separator;
	} else {
		this.separator		= " ";
	}
	
	this.acValueField   	= $(this.acValueId);
	
	if( item_value_name == ""){
		this.acItemValueName = this.acItemDisplayName;
	} else {
		this.acItemValueName = item_value_name;
	}
	if( callback !== ""){
		this.acCallback = callback;
	}
	
// treat up and down key strokes defining the next selected element
autoCompleteObject.prototype.updownArrow = function (parent, e) {
	var keyCode = e.keyCode || window.event.keyCode;
	if(keyCode == 40 || keyCode == 38){
		if(keyCode == 38){ // keyUp
			if(parent.acListCurrent == 0 || parent.acListCurrent == -1){
				parent.acListCurrent = parent.acListTotal-1;
			}else{
				parent.acListCurrent--;
			}
		} else { // keyDown
			if(parent.acListCurrent == parent.acListTotal-1){
				parent.acListCurrent = 0;
			}else {
				parent.acListCurrent++;
			}
		}
		// loop through each result div applying the correct style
		parent.acResultsDiv.children().each(function(i){
			if(i == parent.acListCurrent){
				//parent.acSearchField.val(this.getElementsByTagName("label")[0].innerHTML);
				this.className = "selected";
			} else {
				this.className = "unselected";
			}
		});
		return true;
	} else {
		// reset
		parent.acListCurrent = -1;
		return false;
	}
}

autoCompleteObject.prototype.setAutoComplete = function(){
	// reposition div
	this.repositionResultsDiv();
	// on blur listener

	this.acSearchField.bind( 'blur', {parent: this}, function(){
		setTimeout("this.clearAutoComplete()", 200)
	});
	// on key up listener
	this.acSearchField.bind( 'keyup', {parent: this}, function(e){
		//if( e.data.parent.acValueField.val() != ""){
		//	e.data.parent.acSearchField.val("");
		//	e.data.parent.acValueField.val("");
		//}
		// get keyCode (window.event is for IE)
		var keyCode = e.keyCode || window.event.keyCode;
		var lastVal = e.data.parent.acSearchField.val();
		// check an treat up and down arrows
		if(e.data.parent.updownArrow(e.data.parent, e)){
			return;
		}
		// check for ESC
		if( keyCode == 27){
			e.data.parent.clearAutoComplete();
			return;
		}
		e.data.parent.autoComplete( e.data.parent, lastVal);
	});
}

// treat the auto-complete action (delayed function)
autoCompleteObject.prototype.autoComplete = function (parent, lastValue){
	var curr_parent = parent;
	// get the field value
	var part = parent.acSearchField.val();
	// if it's empty clear the resuts box and return
	if(part == ''){
		parent.clearAutoComplete();
		return;
	}
	// if it's equal the value from the time of the call, allow
	if(lastValue != part){
		return;
	}
	switch( parent.autocomplete_type){
			case 'email':
				var mail_filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
				var valid_email = mail_filter.test(part);
				if( !valid_email){
					return;
				}
				break;
			case 'tel':
				if( part.length < 10 ){
					return;
				}
				break;
	}
	//prepare url
	var base_url = location.href.substring( 0, location.href.lastIndexOf("/")+1);
	var final_url = base_url + parent.acURL + part;
	if( parent.autocomplete_type == 'notaire'){
		var id_town = parent.acSearchField.parent().parent().find("#sausalito_notaire_id_town").val();
		if( id_town != "" ){
			final_url += "&id_town="+id_town;
		}
	}
	// get remote data as JSON
	$.getJSON( final_url, function(json){
		// get the total of results
		var ansLength = curr_parent.acListTotal = json.length;
		curr_parent.JSONDatas = json;
		// if there are results populate the results div
		if( ansLength > 0){
			var newData = '';
			var displayedData = "";
			// create a div for each result
			$.each(json, function(i,item){
				displayedData="";
				$.each( curr_parent.acItemDisplayName.split( '+'), function(x, acChildPart){
					 displayedData += item[acChildPart]+curr_parent.separator;
				});
				displayedData = displayedData.substring(0, displayedData.length - 1);
				newData += '<div class="unselected"><span id="lbl_results" title="'+i+'">'+ displayedData +'</span></div>';

			});
			// update the results div
			curr_parent.acResultsDiv.html(newData);
			curr_parent.acResultsDiv.css("display","block");
			// for all divs in results
			curr_parent.divs = $(curr_parent.acResultsId + " > div");
			// on mouse over clean previous selected and set a new one
			curr_parent.divs.mouseover( function() {
				curr_parent.divs.each(function(){this.className = "unselected";});
				this.className = "selected";
			});
			// on click copy the result text to the search field and hide
			curr_parent.divs.click( function() {
				curr_parent.acCallback( curr_parent, this.getElementsByTagName("span")[0].title, this.getElementsByTagName("span")[0].innerHTML);
				curr_parent.clearAutoComplete();
			});

			curr_parent.acSearchField.bind( 'keypress', {parent: this}, function(e){
				var keyCode = e.keyCode;
				if( keyCode == 13){ // ENTER key keycode
					e.preventDefault();
					parent.acCallback( parent,  $(this).parents('div').find('.selected').children('span')[0].title, $(this).parents('div').find('.selected').children('span')[0].innerHTML);
					parent.clearAutoComplete();
				}
			});


		} else {
			curr_parent.clearAutoComplete();
		}
	});
}

// clear auto complete box
autoCompleteObject.prototype.clearAutoComplete = function ()
{
	this.acResultsDiv.html('');
	if( this.acSearchField.val() == ''){
		this.acValueField.val('');
	}
	this.acResultsDiv.css("display","none");
}

// reposition the results div accordingly to the search field
autoCompleteObject.prototype.repositionResultsDiv = function ()
{
	// get the field position
	var sf_pos    = this.acSearchField.offset();
	var sf_top    = sf_pos.top;
	var sf_left   = sf_pos.left;
	// get the field size
	var sf_height = this.acSearchField.height();
	var sf_width  = this.acSearchField.width()+15;
	// apply the css styles - optimized for Firefox
	this.acResultsDiv.css("position","absolute");
	this.acResultsDiv.css("left", sf_left - 2);
	this.acResultsDiv.css("top", sf_top + sf_height + 3);
	this.acResultsDiv.css("width", sf_width+2);
}
	this.setAutoComplete();
}
