var Complajax =  new Class({
	// Variables privadas
	_name : null,
	_listado : new Array,
	_ultimaPulsacion : null,
	_primeraPulsacion : null,
	_searchQueue : new Array(),
	_onInput : false,
	_onTable : false,
	_Ajaxhttp : false,
	isAjaxWorking : false,
	_moduleName : '',

	initialize : function(name) {
		this._name = name;
	},

	/**
	 * Establece el nombre del módulo para poder ser llamado exteriormente
	 */
	setModuleName : function(name) {
		this._moduleName = name;
	},

	/**
	 * Retorna el nombre del módulo
	 */
	getModuleName : function() {
		return this._moduleName;
	},

	setListado : function(listado) {
		this._listado = listado;
	},

	getListado : function () {
		return this._listado;
	},

	setCreateCelda : function (handler) {
		this.printDebug('setCreateCelda');
		this.createCelda = handler;
	},
	
	getCapa : function () {
		return document.getElementById('lyr' + this._name);
	},

	getTabla : function () {
		return document.getElementById('lyr' + this._name + 'Table');
	},
	
	getForm : function () {
		return document.getElementById('frm' + this._name);
	},
	
	getInput : function () {
		return document.getElementById('frm' + this._name + 'Input');
	},
	
	getControl : function () {
		return document.getElementById('frm' + this._name + 'Control');
	},
	
	getButton : function () {
		return document.getElementById('frm' + this._name + 'Button');
	},
	
	mostrarCapa : function (action) {
		var capa = this.getCapa();
		if(action) {
			capa.style.display = 'block';	
		}
		else {
			capa.style.display = 'none';
		}
	},

	borrarTabla : function () {
		var tabla = this.getTabla();
		this.borrarElemento(tabla);
	},

	borrarElemento : function(elemento) {
		var i;
		for(i=elemento.childNodes.length-1;i>=0;i--) {
			elemento.removeChild(elemento.childNodes[i]);
		}
	},
	setTextoSubmit : function (texto,value) {
		input = this.getInput();
		input.value = texto;
		this.setControlText(value);
		this.setControlButtonText("IR");
	},

	setControlText : function (texto) {
		control = this.getControl();
		control.value = texto;
	},

	setControlButtonText : function (texto) {
		control = this.getButton();
		if(control)
			control.innerHTML = texto;
	},

	investigateIndex : function () {
		elemento = this.getTabla();
		var seleccion = elemento.options[elemento.selectedIndex];
		this.setTextoSubmit(seleccion.text, seleccion.value);
	},

	onInput : function (valor) {
		if(valor) {
			this._onInput = true;
			var input = this.getInput();
			input.addEvent('keyup', this.alertkey.bindWithEvent(this));
		}
		else {
			this._onInput = false;
			var input = this.getInput();
			input.removeEvent('keyup');
		
			/*
			 * Establecemos el contador para mirar si tenemos que hacer
			 * desaparecer la capa de los resultados
			 */
			this.contadorBlur();
			//this.actionBlur(this.getModuleName());
		}
	
	},

	onTable : function (valor) {
		if(valor) {
			this._onTable = true;
			var select = this.getTabla();
			select.addEvent('keyup', this.alertkey.bindWithEvent(this));
		}
		else {
			this._onTable = false;
			var select = this.getTabla();
			select.removeEvent('keyup');

			/*
			 * Establecemos el contador para mirar si tenemos que hacer
			 * desaparecer la capa de los resultados
			 */
			this.contadorBlur();
			//this.actionBlur(this.getModuleName());
		}
	},
	
	contadorBlur : function () {
		this.actionBlur.delay(200, this);
		//setTimeout(this.actionBlur, 200, this.getModuleName());
		//var hora = this.getModuleName();
		//setTimeout(this.actionBlur, 200);
	},
	
	actionBlur : function (module) {
		//eval("mod = " + module);
		//console.log('blur: ' + mod._onInput);
		//console.log('blur: ' + mod._onTable);
		//console.log('blur: ' + this);
		if(!this._onInput && !this._onTable) {
		//if(!mod._onInput && !mod._onTable) {
			//eval(module + ".mostrarCapa(false)");
			this.mostrarCapa(false);
		}
	},

	//now create the event handler function to process the event
	alertkey : function (e) {

		//console.log('alert ' + this._onInput);
		//console.log('alert ' + this._onTable);
		if(!this._onInput && !this._onTable)
			return;
		
		//document.getElementById('debug').innerHTML += 'Pulsación: ' + e;

		if( !e ) {
			//if the browser did not pass the event information to the
			//function, we will have to obtain it from the event register
			if( window.event ) {
				//Internet Explorer
				e = window.event;
			} else {
				//total failure, we have no way of referencing the event
				return;
			}
		}
		
		if( typeof( e.keyCode ) == 'number'  ) {
			//DOM
			e = e.keyCode;
		} else if( typeof( e.which ) == 'number' ) {
			//NS 4 compatible
			e = e.which;
		} else if( typeof( e.charCode ) == 'number'  ) {
			//also NS 6+, Mozilla 0.9+
			e = e.charCode;
		}
		// MOD Fran: Firefox?
		else if( typeof( e.code ) == 'number'  ) {
			e = e.code;
		} else {
			//total failure, we have no way of obtaining the key code
			return;
		}

		// Arriba en input
		if(e == 38 && this._onInput) {
			var tabla = this.getTabla();
			if(tabla.length) {
				tabla.options[tabla.length-1].selected = true;
				tabla.options[tabla.length-1].focus();
			}
			tabla.focus();
			//console.log('arriba');
		}
		// Abajo en input
		else if(e == 40 && this._onInput) {
			var tabla = this.getTabla();
			if(tabla.length) {
				tabla.options[0].selected = true;
				tabla.options[0].focus();
			}
			tabla.focus();
			this._onTable = true;
			//console.log('abajo');
			//console.log(tabla);
			//console.log(this);
			//console.log(this._onInput);
			//console.log(this._onTable);
		}
		// Enter en Table
		else if(e == 13 && this._onTable) {
			this.mostrarCapa(false);
			input = this.getInput();
			input.focus();
		}
		// Retroceso en Table (suele ser back en los navegadores)
/*		else if(e == 8 && this._onTable) {
			input = this.getInput();
			input.focus();
			return false;
		}*/
			
	//	window.alert('The key pressed has keycode ' + e +
	//	' and is key ' + String.fromCharCode( e ) );
	},

	freeQueue : function () {
		this.printDebug('freeQueue');
		if(this._searchQueue.length > 0) {
			var elemento = this._searchQueue.pop();
			this.search(elemento);
			this._searchQueue = Array();
		}
	},

	cleanText : function (texto) {
		texto = texto.toLowerCase();

		// Trimming
		texto = texto.replace(/^ */, '');
	//	texto = texto.replace(/ *$/, '');

		// Tildes
		texto = texto.replace(/á/g, 'a');
		texto = texto.replace(/é/g, 'e');
		texto = texto.replace(/í/g, 'i');
		texto = texto.replace(/ó/g, 'o');
		texto = texto.replace(/ú/g, 'u');

	//	alert('--' + texto + '--');
		return texto;
	},

	search : function (texto) {
		this.printDebug('search');
		// Borramos la tabla
		this.borrarTabla();

		var longitud = texto.length;

		var contador = 0;

		var listado = this.getListado();
				
		if(this.isAjaxWorking)
			this._searchQueue.push(texto);
		else if(listado.childNodes && listado.childNodes.length) {
			// Insertamos las localidades
			var primero = listado.firstChild;

			var tabla = this.getTabla();

			var elemento = primero;
			
			while(elemento) {
				var id = elemento.getAttribute('id');
				var realName = elemento.getAttribute('r');
				var nombre = elemento.firstChild.nodeValue;

				/*
				 * Sólo incluimos los que coincidan con texto al inicio
				 * Considero que todos los caracteres estan en minúsculas y
				 * sin tildes
				 */
				var toca = nombre.substr(0, longitud);
				if(toca == texto) {

					if(contador++ == 0)
						this.mostrarCapa(true);

					var celda_li = this.createCelda(realName, id);
					tabla.appendChild(celda_li);

					//alert('id=' + id + ', nombre=' + nombre);

				}
				elemento = elemento.nextSibling;
			}
		}
		this.printDebug('contador: '+contador);
		if(!contador)
			this.mostrarCapa(false);
	},

	cambioBuscador : function () {
		texto = this.getInput();
		texto = texto.value;

		this.setControlText('');
		this.setControlButtonText("BUSCAR");
	
		// Limpiamos el text
		texto = this.cleanText(texto);

		//alert(texto + "==" + this._ultimaPulsacion);

		if(texto != this._ultimaPulsacion) {
	
			this._ultimaPulsacion = texto;

			var longitudTexto = texto.length;

			if(longitudTexto < 0) {
				this.printDebug('texto < 0');
				this.mostrarCapa(false);
				return false;
			}
			else if(longitudTexto == 0) {
				this.printDebug('texto = 0');
				this.mostrarCapa(false);
				this.borrarTabla();
			}
			else if(longitudTexto == 1 && this._primeraPulsacion != this._ultimaPulsacion) {
				this.printDebug('texto = 1');
				//alert('Vamos a buscar');
				this._primeraPulsacion = texto;
				if(arguments.length)
					this.doSearch(texto, arguments);
				else
					this.doSearch(texto, null);
			}
			else {
				this.printDebug('else');
				//alert('Localmente...');
				this.mostrarCapa(true);
				this.search(texto);
			}		
		}
		return false;	
		///this.printDebug('texto = <nada>');
		///this._primeraPulsacion = '';
		///this.doSearch('', null);
	},
	
	cambioBuscador2 : function () {
		texto = this.getInput();
		texto = texto.value;
		
		this.printDebug('texto = <nada>');
		this._primeraPulsacion = '';
		this.doSearch(texto, null);

		
	},

	printDebug : function (texto) {
		//document.getElementById('debug').innerHTML = document.getElementById('debug').innerHTML + texto + "<br/>";
	},

	dummyEnd : null
});