
var elementoSeleccionado = -1;
var sugerencias = null;
var cacheSugerencias = {};

		Array.prototype.formateaLista = function() {
		codigoHtml = "<table style=\"cursor:pointer;\" width=\"100%\" cellpadding=\"0\" cellspacing=\"0\">";
		for(var i=0; i<this.length; i++) {
			if(i == elementoSeleccionado) {
				codigoHtml += "<tr><td class=\"seleccionado\"> "+this[i]+"</td></tr>";
			}
			else {
				codigoHtml += "<tr><td onMouseOver=\"limpia_over();this.bgColor='blue';this.style.color='#ffffff';\" onMouseOut=\"this.bgColor='#ffffff';this.style.color='#000000';\" onclick=\"selecciona_r('"+i+"');\"> "+this[i]+"</td></tr>";
			}
		}
		codigoHtml += "</table>";

		return codigoHtml;
		
		};

		Array.prototype.formateaLista2 = function() {
		codigoHtml = "<table style=\"cursor:pointer;\" width=\"100%\" cellpadding=\"0\" cellspacing=\"0\">";
		for(var i=0; i<this.length; i++) {
			if(i == elementoSeleccionado) {
				codigoHtml += "<tr><td class=\"seleccionado\"> "+this[i]+"</td></tr>";
			}
			else {
				codigoHtml += "<tr><td onMouseOver=\"limpia_over2();this.bgColor='blue';this.style.color='#ffffff';\" onMouseOut=\"this.bgColor='#ffffff';this.style.color='#000000';\" onclick=\"selecciona_r2('"+i+"');\"> "+this[i]+"</td></tr>";
			}
		}
		codigoHtml += "</table>";

		return codigoHtml;
		
		};
	
	function autocompleta() {
		var elEvento = arguments[0] || window.event;
		var tecla = elEvento.keyCode;
			if(tecla == 40) { // Flecha Abajo
				
				if(elementoSeleccionado+1 < sugerencias.length) {
					elementoSeleccionado++;
				}
				muestraSugerencias();

			}else if(tecla == 38) { // Flecha Arriba
			
				if(elementoSeleccionado > 0) {
					elementoSeleccionado--;
				}
				muestraSugerencias();

			}
			else if(tecla == 13) { // ENTER o Intro
				seleccionaElemento();
				borraLista();
				
			}else{
				var texto = document.oForm4.nombre_ciudad.value;
				var provincia = document.oForm4.provincia_carta.value;
				var pais = document.oForm4.pais_carta.value;
			
					// Si es la tecla de borrado y el texto es vacío, ocultar la lista
					if(tecla == 8 && texto == "") {
						borraLista();
						return;
					}
					
					//if(cacheSugerencias[texto] == null) {

						var date = new Date();
						var timestamp = date.getTime();
						var parameters = "texto=" + texto + "&provincia=" + provincia + "&pais=" + pais + "&time=" + timestamp;
						ajax = ajaxobj();
						ajax.open("POST", "/inc/ajax/desplegable_ciudades.php");
						ajax.onreadystatechange=function(){
							if (ajax.readyState==4){
								sugerencias = eval('('+ajax.responseText+')'); ;
								if(sugerencias.length == 0) {
									sinResultados(provincia);
								}else {

									cacheSugerencias[texto] = sugerencias;
									//alert("1" + sugerencias);
									actualizaSugerencias();
								} 
							}
						}
						ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;');
						ajax.send(parameters);
					/*}else{
						sugerencias = cacheSugerencias[texto];
						//alert("2");
						actualizaSugerencias(sugerencias);
					}*/
					
			}
	}
	function autocompleta2() {
		var elEvento = arguments[0] || window.event;
		var tecla = elEvento.keyCode;
			if(tecla == 40) { // Flecha Abajo
				
				if(elementoSeleccionado+1 < sugerencias.length) {
					elementoSeleccionado++;
				}
				muestraSugerencias2();

			}else if(tecla == 38) { // Flecha Arriba
			
				if(elementoSeleccionado > 0) {
					elementoSeleccionado--;
				}
				muestraSugerencias2();

			}
			else if(tecla == 13) { // ENTER o Intro
				seleccionaElemento2();
				borraLista2();
				
			}else{
				var texto = document.oForm4.nombre_ciudad2.value;
				var provincia = document.oForm4.provincia_carta2.value;
				var pais = document.oForm4.pais_carta2.value;
			
					// Si es la tecla de borrado y el texto es vacío, ocultar la lista
					if(tecla == 8 && texto == "") {
						borraLista2();
						return;
					}
					
					//if(cacheSugerencias[texto] == null) {

						var date = new Date();
						var timestamp = date.getTime();
						var parameters = "texto=" + texto + "&provincia=" + provincia + "&pais=" + pais + "&time=" + timestamp;
						ajax = ajaxobj();
						ajax.open("POST", "/inc/ajax/desplegable_ciudades.php");
						ajax.onreadystatechange=function(){
							if (ajax.readyState==4){
								sugerencias = eval('('+ajax.responseText+')'); ;
								if(sugerencias.length == 0) {
									sinResultados2(provincia);
								}else {

									cacheSugerencias[texto] = sugerencias;
									//alert("1" + sugerencias);
									actualizaSugerencias2();
								} 
							}
						}
						ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;');
						ajax.send(parameters);
					/*}else{
						sugerencias = cacheSugerencias[texto];
						//alert("2");
						actualizaSugerencias(sugerencias);
					}*/
					
			}
	}
	function sinResultados(provincia) {
		if(provincia!="0"){				
			document.getElementById("sugerencias").innerHTML = "<p class=\"input\">No existen municipios que empiecen con ese texto</p>";
			document.getElementById("sugerencias").style.display = "block";
		}else{
			document.getElementById("sugerencias").innerHTML = "<p class=\"input\">Por favor, seleccione País y Província</p>";
			document.getElementById("sugerencias").style.display = "block";
		}
	}
	function sinResultados2(provincia) {
		if(provincia!="0"){				
			document.getElementById("sugerencias2").innerHTML = "<p class=\"input\">No existen municipios que empiecen con ese texto</p>";
			document.getElementById("sugerencias2").style.display = "block";
		}else{
			document.getElementById("sugerencias2").innerHTML = "<p class=\"input\">Por favor, seleccione País y Província</p>";
			document.getElementById("sugerencias2").style.display = "block";
		}
	}

	function actualizaSugerencias() {
		elementoSeleccionado = -1;
		//alert("go");
		muestraSugerencias();
	}

	function actualizaSugerencias2() {
		elementoSeleccionado = -1;
		//alert("go");
		muestraSugerencias2();
	}

	function selecciona_r(ciudad){
		elementoSeleccionado = ciudad
		seleccionaElemento();
		borraLista();
	}

	function selecciona_r2(ciudad){
		elementoSeleccionado = ciudad
		seleccionaElemento2();
		borraLista2();
	}

	function seleccionaElemento(){
		if(sugerencias[elementoSeleccionado]) {
			//reemplazamos "&ntilde;" por "Ñ"
			city = sugerencias[elementoSeleccionado].replace(/&ntilde;/,"ñ");
			document.oForm4.nombre_ciudad.value = city;
			//document.oForm4.action = "http://" + document.oForm.nombre_ciudad.value + ".callejero.net/tiempo/";
			//document.oForm.submit();
			
		}
	}

	function seleccionaElemento2(){
		if(sugerencias[elementoSeleccionado]) {
			//reemplazamos "&ntilde;" por "Ñ"
			city = sugerencias[elementoSeleccionado].replace(/&ntilde;/,"ñ");
			document.oForm4.nombre_ciudad2.value = city;
			//document.oForm4.action = "http://" + document.oForm.nombre_ciudad.value + ".callejero.net/tiempo/";
			//document.oForm.submit();
			
		}
	}

	function muestraSugerencias() {
		var zonaSugerencias = document.getElementById("sugerencias");
		//alert("AQUI - "+sugerencias);
		zonaSugerencias.innerHTML = sugerencias.formateaLista();
		zonaSugerencias.style.display = 'block';	
	}

	function muestraSugerencias2() {
		var zonaSugerencias = document.getElementById("sugerencias2");
		//alert("AQUI - "+sugerencias);
		zonaSugerencias.innerHTML = sugerencias.formateaLista2();
		zonaSugerencias.style.display = 'block';	
	}

	function borraLista() {
		document.getElementById("sugerencias").innerHTML = "";
		document.getElementById("sugerencias").style.display = "none";
	}

	function borraLista2() {
		document.getElementById("sugerencias2").innerHTML = "";
		document.getElementById("sugerencias2").style.display = "none";
	}

	window.onload = function() {
		document.oForm4.nombre_ciudad.onkeyup = autocompleta;
	}

	function enviar_form(){
	
		var texto = document.oForm4.nombre_ciudad.value;
		var provincia = document.oForm4.provincia_carta.value;
		var pais = document.oForm4.pais_carta.value;

		var parameters = "texto=" + texto + "&provincia=" + provincia + "&pais=" + pais;
		ajax = ajaxobj();
		ajax.open("POST", "/inc/ajax/desplegable/desplegable_ciudades.php");
		ajax.onreadystatechange=function(){
			if (ajax.readyState==4){
				var datos = ajax.responseText;
				//alert(datos);
			}
		}
		ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;');
		ajax.send(parameters);
	}

	function limpia_over(){
		if(elementoSeleccionado != -1){
			elementoSeleccionado = -1;
			muestraSugerencias();

			//alert(elementoSeleccionado)
		}
		
	}
	function limpia_over2(){
		if(elementoSeleccionado != -1){
			elementoSeleccionado = -1;
			muestraSugerencias2();

			//alert(elementoSeleccionado)
		}
		
	}

	function noenter(obj,e) {
		opc = true;
		tecla = (document.all) ? e.keyCode : e.which;
		
		if (tecla == 13){
			opc = false;
		}

		return opc;
	}

	function verifica_ciudad_existe(frm){
		
		var date = new Date();
		var timestamp = date.getTime();
		var nombre_ciudad = frm.nombre_ciudad.value;
		var id_provincia = frm.provincia_carta.value;
	
		var parameters = "nombre_ciudad=" + nombre_ciudad + "&id_provincia=" + id_provincia + "&time=" + timestamp;
		ajax3 = ajaxobj();
		ajax3.open("POST", "/inc/ajax/verifica_ciudad.php");
		ajax3.onreadystatechange=function(){
			if (ajax3.readyState==4){
				var datos3 = ajax3.responseText;
				if(datos3=="demasiados_resultados"){
					alert("Varias ciudades coinciden con su búsqueda, por favor, sea mas concreto.");
				}else if(datos3==""){
					alert("No hay ninguna ciudad con ese nombre.")
				}else{
					desg = datos3.split('---');
					frm.nombre_ciudad.value = desg[0];
					frm.id_ciudad.value = desg[1];
					//alert("enviamos form");
					frm.submit();
				}
				
				
			}
		}
		ajax3.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;');
		ajax3.send(parameters);
	
	}

	function verifica_ciudad_existe78(frm){
		var date = new Date();
		var timestamp = date.getTime();
		var nombre_ciudad = frm.nombre_ciudad.value;
		var id_provincia = frm.provincia_carta.value;
	
		var parameters = "nombre_ciudad=" + nombre_ciudad + "&id_provincia=" + id_provincia + "&time=" + timestamp;
		ajax3 = ajaxobj();
		ajax3.open("POST", "/inc/ajax/verifica_ciudad.php");
		ajax3.onreadystatechange=function(){
			if (ajax3.readyState==4){
				var datos3 = ajax3.responseText;
				//alert(datos3);
				if(datos3=="demasiados_resultados"){
					alert("Varias ciudades coinciden con su búsqueda, por favor, sea mas concreto.");
				}else if(datos3==""){
					alert("No hay ninguna ciudad con ese nombre.")
				}else{
					desg = datos3.split('---');
					frm.nombre_ciudad.value = desg[0];
					frm.id_ciudad.value = desg[1];
					
					if(frm.latitud1.value=="" && frm.latitud2.value=="" && frm.longitud1.value=="" && frm.longitud2.value==""){
						verifica_coordenadas2b(frm);
					}

				}
				
				
			}
		}
		ajax3.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;');
		ajax3.send(parameters);
	
	}



	function verifica_ciudad_existe3(frm){
		
		var date = new Date();
		var timestamp = date.getTime();
		var nombre_ciudad = frm.nombre_ciudad.value;
		var id_provincia = frm.provincia_carta.value;
	
		var parameters = "nombre_ciudad=" + nombre_ciudad + "&id_provincia=" + id_provincia + "&time=" + timestamp;
		ajax = ajaxobj();
		ajax.open("POST", "/inc/ajax/verifica_ciudad.php");
		ajax.onreadystatechange=function(){
			if (ajax.readyState==4){
				var datos = ajax.responseText;
				if(datos=="demasiados_resultados"){
					alert("Varias ciudades coinciden con su búsqueda, por favor, sea mas concreto.");
				}else if(datos==""){
					alert("No hay ninguna ciudad con ese nombre.")
				}else{
					//alert(datos);
					desg = datos.split('---');
					frm.nombre_ciudad.value = desg[0];
					frm.id_ciudad.value = desg[1];
					verifica_ciudad_existe4(frm);
				}
				
				
			}
		}
		ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;');
		ajax.send(parameters);
	
	}

	function verifica_ciudad_existe4(frm){
		var date = new Date();
		var timestamp = date.getTime();
		var nombre_ciudad = frm.nombre_ciudad2.value;
		var id_provincia = frm.provincia_carta2.value;

		var parameters = "nombre_ciudad=" + nombre_ciudad + "&id_provincia=" + id_provincia + "&time=" + timestamp;
		ajax = ajaxobj();
		ajax.open("POST", "/inc/ajax/verifica_ciudad.php");
		ajax.onreadystatechange=function(){
			if (ajax.readyState==4){
				var datos = ajax.responseText;
				if(datos=="demasiados_resultados"){
					alert("Varias ciudades coinciden con su búsqueda, por favor, sea mas concreto.");
				}else if(datos==""){
					alert("No hay ninguna ciudad con ese nombre.")
				}else{
					desg = datos.split('---');
					frm.nombre_ciudad2.value = desg[0];
					frm.id_ciudad2.value = desg[1];
					frm.submit();
				}
				
				
			}
		}
		ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;');
		ajax.send(parameters);
	
	}