///////////////////////////////////////////////////////////
// Class Livesearch
// uses scriptaculous Ajax.Autocompleter
///////////////////////////////////////////////////////////

var LiveSearch = Class.create({
	
	///////////////////////////////////////////////////////////
	// initialize
	///////////////////////////////////////////////////////////
	
	initialize:function(id, results, arrow) {
		typeof id == 'string' ? this.id = $(id) : this.id = id;
		typeof results == 'string' ? this.results = $(results) : this.results = results;
		typeof arrow == 'string' ? this.arrow = $(arrow) : this.arrow = arrow;
		
		//new Ajax.Autocompleter(this.id, this.results, '/static/inc/livesearch.html', 	{ callback: this.showResults.bind(this) });
		new Ajax.Autocompleter(this.id, this.results, '/includes/livesearch.php', {});
		this.arrow.hide();
		this.results.hide()
		
		this.id.observe('focus', this.onFieldFocus.bind(this));
		this.id.observe('blur', this.onFieldBlur.bind(this));
		
		log('----- LiveSearch constructor finished for: #'+id+' -----');
	},
	
	///////////////////////////////////////////////////////////
	// show & hide the results
	///////////////////////////////////////////////////////////
	
	showResults:function(e){
		log('----- show results ------')
		this.arrow.show();
		this.results.observe('mouseout', this.onResultsMouseOut.bind(this))
	},
	
	clearResults:function(e){
		log('----- clear results ------')
		this.arrow.hide();
		this.results.hide();
	},
	
	
	///////////////////////////////////////////////////////////
	// mouse events
	///////////////////////////////////////////////////////////

	onResultsMouseOut:function(e){
		var e = Event.element(e).nodeName.toLowerCase();
		
		// if the element is a link, list item or ul
		if(e == 'a' || e == 'li' || e == 'ul'){
			// remove the timeout 
			this.killTimeout();
		}else{	
			// or else, set a new timeout
			this.setNewTimeout();
		}
	},
	
	
	///////////////////////////////////////////////////////////
	// timeouts
	///////////////////////////////////////////////////////////
	
	setNewTimeout:function(){
		clearTimeout(this.toID);
		this.toID = setTimeout(this.clearResults.bind(this), 1000);
	},
	
	killTimeout:function(){
		clearTimeout(this.toID);
	},
	
	
	
	///////////////////////////////////////////////////////////
	// on field focus & blur
	///////////////////////////////////////////////////////////

	onFieldFocus:function(e){
		var e = Event.element(e);
		
		if($F(e) == e.defaultValue){
			e.value = '';
		}
	},
	
	onFieldBlur:function(e){
		var e = Event.element(e);
		this.arrow.hide();
		
		if($F(e) == ''){
			e.value = e.defaultValue;
		}
	}
})
