// Created by: schimmi[1stein.org], John Nunemaker
// Modificated by: RStankov[next.pixeldepo.com]
// Last Update: 08.01.2008
var ls = {
	url: '',
	init:function(){
		if (!$('livesearchpopup_results')) return;

		this.results_box		= $('livesearchpopup_box').hide();
		this.selected_result	= undefined;
		
		var s = $('s');
		s.setAttribute('autocomplete','off');
		s.setAttribute('placeholder','Rechercher');
		s.onkeypress = this.noEnter.bind(this);
		s.observe('keypress',	this.handleKeypress.bind(this));
		s.observe('blur',		this.lostFocus.bind(this));
		s.observe('change',		this.lostFocus.bind(this));
		s.observe('focus',		this.focus.bind(this));
		
		new Form.Element.Observer(s, 1.0, this.showResults.bind(this));
		
		this.results_box.observe('mousemove', this.updateSelection.bind(this, null));		
		this.showPage(s.value, 1);
	},
	noEnter: function(e){
		return (e.keyCode || e.which) != 13;
	},
	lostFocus:function(){
		Element.hide.delay(.5, this.results_box);
	},
	focus:function(){
		var value = $F('s');
		if (value.length > 0) this.showPage(value, 1);
	},
	handleKeypress:function(e){
		switch (e.which || e.keyCode) {
			case Event.KEY_ESC:
				return this.close();
			
			case Event.KEY_UP:
				return this.updateSelection(-1); 
				
			case Event.KEY_DOWN:
				return this.updateSelection(+1);
				
			case Event.KEY_RETURN:
				if (this.selected_result != undefined)
					document.location = $('resultlist').down('a', this.selected_result).href;
				else
					$('s').up('form').submit();
		}
	},
	updateSelection:function(diff) {
		if (!$('resultlist')) return;
			
		var children = $('resultlist').childElements();
		
		if (!diff) {
			this.selected_result = undefined;
			children.each(function(child, i){ child.className = 'resultlistitem'; });
		} else {
			var num = 0;
			if (this.selected_result == undefined) {
				num = diff > 0 ? diff - 1 : children.length + diff;
			} else {
				num = Math.min(Math.max(this.selected_result + diff, 0), children.length - 1);
			}
			
			this.selected_result = num;
			children.each(function(child, i){ child.className = i == num ? 'resultlistitem_selected' : 'resultlistitem'; });
		}
	},
	showResults:function(element, value){
	   this.showPage(value, 1);
	},
	showPage:function(s, page){
		if (s == '' || s == 'Rechercher') {
			this.results_box.hide();
		} else {
			window.clearTimeout();
			this.results_box.show();
			new Ajax.Updater('livesearchpopup_results', this.url, { 
				method: 'get', 
				parameters: {s: s, paged: page}
			});
		}

		this.updateSelection(); 
	},
	close:function(){
		$('s').clear();
		this.results_box.hide();
	}
};
Event.observe(window, 'load', ls.init.bind(ls));
