var listadoLocalidades = null;
var ultimaPulsacion = null;
var ultimaMerindad = null;
var primeraPulsacion = null;
var searchQueue = new Array();
var onInput = false;
var onTable = false;
var tmp;

/* this next line tells the browser to detect a keyup
event over the whole document and when it detects it,
it should run the event handler function 'alertkey' */
document.onkeyup = alertkey;

function getTabla() {
	return document.getElementById('lyrSearchInformanteTable');
}

function getCapa() {
	return document.getElementById('lyrSearchInformante');
}

function mostrarCapaLocalidades(action) {
	var capa = getCapa();
	if(action)
		capa.style.display = 'block';
	else
		capa.style.display = 'none';
}

function borrarTablaLocalidades() {
	var tabla = getTabla();
	borrarElemento(tabla);
}

function doSearchLocalidad(nombre, wid, nid) {

	if (!isAjaxWorking && Ajaxhttp) {
		// Url de trabajo
		url = "/publisher/backend/src/searchInformante.php?nombre=" + nombre + "&wid=" + wid + "&nid=" + nid;
		
		Ajaxhttp.open("GET", url , true);
		Ajaxhttp.onreadystatechange = handleSearchLocalidad;
		isAjaxWorking = true;

		// Mostramos el aviso
		//mostrarAvisoAvailableNodes(1);

		// Enviamos
		Ajaxhttp.send(null);
	}
	else
		searchQueue.push(nombre);
}

function handleSearchLocalidad() {
	if (Ajaxhttp.readyState == 4) {
		if (Ajaxhttp.responseText.indexOf('invalid') == -1) {
			// Use the XML DOM to unpack the city and state data
			listadoLocalidades = Ajaxhttp.responseXML;

			// Borramos la tabla
			borrarTablaLocalidades();

			var tabla = getTabla();

			// Insertamos las localidades (lo hago así por el p*** iexplorer)
//			var primero = listadoLocalidades.firstChild.firstChild;
			var primero = listadoLocalidades.getElementsByTagName('search').item(0).firstChild;

			elemento = primero;
			//alert(elemento);
			
			// Mostramos la tabla
			if(primero)
				mostrarCapaLocalidades(true);

			while(elemento) {
				var id = elemento.getAttribute('id');
				var realName = elemento.getAttribute('r');
				var nombre = elemento.firstChild.nodeValue;

				celda_li = createCelda(realName, id);
				tabla.appendChild(celda_li);

				//alert('id=' + id + ', nombre=' + nombre);

				elemento = elemento.nextSibling;
			}

			isAjaxWorking = false;

			// Ahora llamamos al programa que libere la cola de busquedas
			freeQueue();
		}
	}
}

function setTextoLocalidad(texto,value) {
	document.getElementById('frmSearchInformanteInput').value = texto;
	setControlText(value);
	setControlButtonText("IR");
//	mostrarCapaLocalidades(false);
}

function setControlText(texto) {
	document.getElementById('frmSearchInformanteControl').value = texto;
}

function setControlButtonText(texto) {
	document.getElementById('frmSearchInformanteButton').innerHTML = texto;
}

function investigateIndex(elemento) {
	var seleccion = elemento.options[elemento.selectedIndex];
	setTextoLocalidad(seleccion.text, seleccion.value);
}

function createCelda(nombre, valor) {
	var celda_li = document.createElement('option');
	celda_li.setAttribute('value', valor);
	celda_li.setAttribute('onclick', 'mostrarCapaLocalidades(false);');
	celda_li.appendChild(document.createTextNode(nombre));

	return celda_li;
}

function onLocalidadInput(valor) {
	if(valor)
		onInput = true;
	else
		onInput = false;
	
	/*
	 * Establecemos el contador para mirar si tenemos que hacer
	 * desaparecer la capa de los resultados
	 */
	contadorBlur();
}

function onLocalidadTable(valor) {
	if(valor)
		onTable = true;
	else
		onTable = false;

	/*
	 * Establecemos el contador para mirar si tenemos que hacer
	 * desaparecer la capa de los resultados
	 */
	contadorBlur();
}

function contadorBlur() {
	setTimeout(actionBlur, 200);
}

function actionBlur() {
	if(!onInput && !onTable) {
		mostrarCapaLocalidades(false);
	}
}

//now create the event handler function to process the event
function alertkey(e) {
	if(!onInput && !onTable)
		return;

	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;
	} else {
		//total failure, we have no way of obtaining the key code
		return;
	}

	// Arriba en input
	if(e == 38 && onInput) {
		var tabla = getTabla();
		if(tabla.length) {
			tabla.options[tabla.length-1].selected = true;
			tabla.options[tabla.length-1].focus();
		}
		tabla.focus();
	}
	// Abajo en input
	else if(e == 40 && onInput) {
		var tabla = getTabla();
		if(tabla.length) {
			tabla.options[0].selected = true;
			tabla.options[0].focus();
		}
		tabla.focus();
	}
	// Enter en Table
	else if(e == 13 && onTable) {
		mostrarCapaLocalidades(false);
		document.getElementById('frmSearchInformanteInput').focus();
	}
	// Retroceso en Table (suele ser back en los navegadores)
/*	else if(e == 8 && onTable) {
		document.getElementById('frmSearchInformanteInput').focus();
		return false;
	}*/
		
//	window.alert('The key pressed has keycode ' + e +
//	' and is key ' + String.fromCharCode( e ) );
}

function freeQueue() {
	if(searchQueue.length > 0) {
		searchLocalidad(searchQueue.pop());
		searchQueue = array();
	}
}

function cleanText(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;
}

function searchLocalidad(texto) {
	// Borramos la tabla
	borrarTablaLocalidades();

	var longitud = texto.length;

	// Insertamos las localidades
	var primero = listadoLocalidades.firstChild.firstChild;

	var tabla = getTabla();

	elemento = primero;

	contador = 0;

	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)
				mostrarCapaLocalidades(true);

			celda_li = createCelda(realName, id);
			tabla.appendChild(celda_li);

			//alert('id=' + id + ', nombre=' + nombre);

		}
		elemento = elemento.nextSibling;
	}
	if(!contador)
		mostrarCapaLocalidades(false);
}

function cambioBuscador() {
	texto = document.getElementById('frmSearchInformanteInput').value;
	merindad = document.getElementById('frmSearchInformanteMerindad').value;

	setControlText('');
	setControlButtonText("BUSCAR");
	
	// Limpiamos el text
	texto = cleanText(texto);

	//alert(texto + "==" + ultimaPulsacion);

	if(texto != ultimaPulsacion || merindad != ultimaMerindad) {
	
		ultimaPulsacion = texto;

		var longitudTexto = texto.length;

		if(longitudTexto < 0) {
			mostrarCapaLocalidades(false);
			return false;
		}
		else if(longitudTexto == 0) {
			mostrarCapaLocalidades(false);
			borrarTablaLocalidades();
		}
		else if(longitudTexto == 1 && (primeraPulsacion != ultimaPulsacion || ultimaMerindad != merindad) || ultimaMerindad != merindad) {
			//alert('Vamos a buscar');
			primeraPulsacion = texto;
			doSearchLocalidad(texto, '1', merindad);
		}
		else {
			//alert('Localmente...');
			mostrarCapaLocalidades(true);
			searchLocalidad(texto);
		}

		// Falta por cambiar la merindad
		ultimaMerindad = merindad;
	}
}
