/**
 * ydcompleter class
 * @description tested in FF3,Chrome,IE8,IE7
 * @subpackage prototype
 * @author basil suter
 * @date 25-05-2009
 * @version v1.3b - different keys added for disabler array
 */

// ydcompleter class creation
var ydcompleter = Class.create ({
	
	// init method
	initialize: function(form_id,container_div,input_id,ajax,frequenz){
		// write class vars
		this.form_id = form_id;
		this.container_div = container_div;
		this.input_id = input_id;
		this.ajax = ajax;
		this.frequenz = frequenz || 1;
		this.query = null;
		this.key_disabler = new Array(0,9,13,16,17,18,19,20,27,33,34,35,36,37,38,39,40,45);
		// start to observ
		this.observe();
	},
	
	// settle the keydown observe for input field
	observe: function(){
		// observe keyup event
		$(this.input_id).observe('keyup', function(event){
			if(this.observer){
				clearTimeout(this.observer);
			}
			this.kd = event.keyCode;
      		this.observer = setTimeout(this.action.bind(this), this.frequenz*1000);
      		
		}.bind(this));
		
		$(this.form_id).focusFirstElement();
	},
	
	// what should happen if the key is up
	action: function(){
		this.query = $F(this.input_id);
		if(this.query == ''){
			if($(this.container_div).style.display != 'none'){
				$(this.container_div).hide();
			}
		}else{
			if(this.in_array(this.kd,this.key_disabler) != true){
				this.keydown();
			}
		}
	},
	
	// is an item available in this array
	in_array: function(item,arr) {
		for(p=0;p<arr.length;p++){
			if (item == arr[p]){
				return true;
			}
		}
	},
	
	// keydown/up event
	keydown: function(){
		new Ajax.Request(this.ajax,{
			method		: 'get',
			parameters	: {query: this.query},
			onLoading	: function(){
				$(this.container_div).update('<img src="http://www.spipe.com/theme/dionysos/images/icons/loader.gif" alt="loading" />').show(); // w��ks, static
			}.bind(this),
			onSuccess	: function(transport){
				$(this.container_div).update(transport.responseText);
			}.bind(this)
		});
	}
});

// init class by loading dom
document.observe('dom:loaded',function(){
	
	/**
	 * ydcompleter config
	 * @param the form id name for focusing the input field
	 * @param the name of the container div where the results will be displayed in
	 * @param the ID of the input field for getting search keys
	 * @param the name to the ajax file ex. ajax.php or to call a function use ajax.php?function=myresponse - search value: $_GET['query']
	 * @param frequenz for the reaction delay
	 */
	 cmp_form_id			= 'searchfrm';
	 cmp_div_container 		= 'container_div';
	 cmp_input_completer 	= 'completer';
	 cmp_ajax_file_list 	= '/ajax.php';
	 cmp_frequenz_react 	= '0.8';
	 
	if(document.getElementById(cmp_div_container) && document.getElementById(cmp_input_completer)){
		completer = new ydcompleter(cmp_form_id,cmp_div_container,cmp_input_completer,cmp_ajax_file_list,cmp_frequenz_react);
	}
});