﻿

function localidadASug (cadena) {
	//Guardamos en el array los caracteres que hay hasta el primer paréntesis. El formato de la entrada es: caso1: ALCUDIA (VALENCIA) caso2: ABREIRO (OCENSE) (PONTEVEDRA) (ejemplos inventados....)
	
	var localidad = cadena.substr(0,cadena.indexOf('(') - 1); 
	//localidad = localidad.replace("-"," ");
	return localidad;
}

function provinciaASug (cadena) {
	//Guardamos en el array los caracteres que hay desde el ultimo '(' hasta el ultimo ')'
	var provincia = cadena.substring (cadena.lastIndexOf('(') +1, cadena.lastIndexOf(')'));
	//provincia = provincia.replace("-"," ");
	return provincia;
}


JAMAutoComplete = function (pIdInputBox, pObjectName,tipo) {

	
	//alert('se ha creado el objeto '+pObjectName)
	this.idInputBox = pIdInputBox;
	//var cadenaAEjecutar = "document.getElementById('" + pIdInputBox + "').idInputBox = '" + pIdInputBox + "';";
	//eval (cadenaAEjecutar);
    this.inputBox = document.getElementById(pIdInputBox);
	//alert('obtenido el objeto '+this.inputBox);
    var completeTextsList = new Array(); // array dinámico donde guardamos la información devuelta por el servicio web
	var parcialTextsList = new Array(); //array dinámico donde guardamos las sugerencias que se muestran.
    this.objectName = pObjectName;
	//cadenaAEjecutar = "document.getElementById('" + pIdInputBox + "').objectName = '" + pObjectName + "'";
	//alert(cadenaAEjecutar);
	//eval (cadenaAEjecutar);

	var tipojama="";
    var highLightedSugForeColor = "#FFFFFF"; // color del sombreado al posicionarte sobre la opcion
    var highLightedSugBackColor = "#B2C0CB";
    var highLightedSugOpacity = 100;
    var nonHighLightedSugForeColor = "#000000"; // Color de las letras del cuadro para busquedas de 1 campo
    var nonHighLightedSugBackColor = "#edecea";
	//var nonHighLightedSugBackColor = "#FFFFFF";
    var nonHighLightedSugOpacity = 80;
	var sugsDivBorder = "1px #FBA807";
	//var sugsDivBorder = "solid 1px #67a370";
    var sugsDivPadding = "1px"; // ancho del borde de las opciones
    var sugsDivBackColor = "#A2A19F"; // color Borde del cuadro de opciones
    var sugsDivOpacity = 95;
	var colorNoResaltado = "#969696";
	var colorNoResaltado = "#666";
	var numeroSugerencias = 0;	
    //var indiceSugerenciaSeleccionada = -1; //Indica el indice de la sugerencia resaltada
    //var existeSugerenciaSeleccionada = 0; //Indica si se ha seleccionado alguna sugerencia
	
	var localidadSeleccionada = ""; // localidad que tiene el foco, en su defecto será la primera.
	var indiceVisiblesSeleccionada = 0; //indice dentro del array  parcialTextsList que esta seleccionada.
	var indiceParcial = 0; //indice para rellenar el array parcial con las sugerencias que se muestran.
	

	
    var idSugsDiv = pIdInputBox + "Sugs";
    var sugsDiv = document.createElement("DIV");
    

    var req = null; //Para peticion AJAX
	var IE = false; //Para saber si se navega por explorer o por otro.
	var activar = true; // Para activar o no la petición del xml (por ej. cuando de 4 letras se pasa a 3, no hace falta pedir. Cuando se pasa de 2 a 3 si)
	
    sugsDiv.id = idSugsDiv;
    sugsDiv.style.border = sugsDivBorder;
	sugsDiv.style.position = "absolute";
	sugsDiv.style.width="700px";	
	sugsDiv.style.height="10px";	
	sugsDiv.style.left="";
	sugsDiv.style.top="";
	sugsDiv.style.textAlign ="left";
	sugsDiv.style.zIndex = 9999;
    sugsDiv.style.display = "none";    
	sugsDiv.style.font =  "normal 11px verdana";
    sugsDiv.style.background = sugsDivBackColor;
    sugsDiv.style.padding = sugsDivPadding;
    setOpacity (sugsDiv, sugsDivOpacity);
	

    var parent = this.inputBox.parentNode;
	//while (parent.parentNode && parent.parentNode.parentNode && parent.parentNode.parentNode.parentNode) parent = parent.parentNode;
	//if (parent.parentNode) parent = parent.parentNode.parentNode;
    //parent.appendChild(sugsDiv);
	
	if (!document.todosLosJAMACs) {
		document.todosLosJAMACs = new Array();
	}
	var indiceAUsar = document.todosLosJAMACs.length - 1;
	if (indiceAUsar < 0) indiceAUsar = 0;
	document.todosLosJAMACs[indiceAUsar] = pObjectName;

	JAMAutoComplete.prototype.initEvents = function (elemento) {
        //addEvent(document, "click", eval(this.objectName + '.determineIfHideSugs'));
		//alert('ejecuta con elemento'+elemento);
		//var vuelta=vuelta;
		var myObjectName = document.ActiveJAMAC; // antes era this.inputBox;
		
		var ref=document.getElementById(elemento);
		
		//alert('elemento es '+elemento);
		if (ref != null)
		{
			//alert('ref es'+myObjectName);
			addEvent(document,"click", eval(myObjectName + '.checkNewValues',false));
			if (elemento == 'exit_total')
			{
				addEvent(window, "unload", eval(myObjectName + '.checkNewValues',false));
			}
			
			
		}
		
		//addEvent(window, "unload", eval(myObjectName + '.checkNewValues'));
		
		//addEvent(this.inputBox, "blur",  eval(this.objectName + '.determineIfHideSugs'));
        //addEvent(this.inputBox, "keyup", eval(this.objectName + '.checkNewValues'));
		//addEvent(this.inputBox, "keypress", eval(this.objectName + '.keyPressed'));  // Da error cuando solo hay un resultado.
		//addEvent(this.inputBox, "keydown", eval(this.objectName + '.keyDowned'));
		
		if (document.all) {
			addEvent (window, "load", eval(this.objectName + '.insertSugsDivIntoDocument'));
			
		} else {
			eval(this.objectName + '.insertSugsDivIntoDocument();');
		}
    }

  
   
    
	
	JAMAutoComplete.prototype.insertSugsDivIntoDocument = function () {
		window.document.body.appendChild(sugsDiv);
		//alert ('capa insertada '+sugsDiv.id);
		//fullSetString="<div>hola</div>";
		//sugsDiv.innerHTML = fullSetString;
		 
    }
    
    JAMAutoComplete.prototype.informarTeclaLevantada = function () {
        //alert ("Tecla levantada");
    }

	
	
	
	// *****************************************   CARGA DEL XML ******************************************************    

	// variable que guarda el comienzo de la url del servicio web al cual se hace la petición para que devuelva el xml con las localidades.
	// A esta función hay que añadirle los parámetros específicos para cada consulta.
	//var urlbase = "http://callejero.paginasamarillas.es/services/localidades/getLocalidades.asmx/LocalityServer"
		var urlbase = "quick_dep_aut_def.asp"
	
	//función que se encarga de asegurarse que la conexión se ha realizado satisfactoriamente, y en ese caso,  realiza las tareas
	// deseadas mediante la funcion parsearXML.
	JAMAutoComplete.prototype.ManejadorEventos = function () 
    {
		var myObjectName = document.ActiveJAMAC;
		//alert("readystate" + req.readyState); 
		
		
		if (req.readyState == 4) {
			//alert("status" + req.status); 
			//alert("status" + req.responseText); 
			if (req.status == 200){
				//alert("status" + req.responseText); 
				 if (req.responseText.indexOf('invalid') == -1) {
					//results = req.responseText.split(",");
					//alert('resultado es '+req.responseText);
					encuesta=req.responseText
					len_encuesta=encuesta.lenght
					var accion = req.responseText.substring (0,4);
					//alert('accion es'+accion);
					if (accion != "" && accion == 'stop')
					{						
						encuesta= req.responseText.substring (4,len_encuesta);						
					}
					//alert('encuesta es'+encuesta);
					eval(encuesta);
					if (accion == 'stop')
					{
						//alert('le devuelve un false');
						return false;
					}
				}
			}
		
		}
		
	}
	
	// función que crea y lanza la conexión, y asíncronamente lanza el proceso ManejadorEventos cuando la conexión se haya realizado	
	JAMAutoComplete.prototype.cargaXMLdoc = function (url,fin) {
		
		
		//alert(url);
	    if (window.ActiveXObject) { //si es Explorer
	        req = new ActiveXObject("Microsoft.XMLHTTP");
			IE = true;
	    } 
	    else if (window.XMLHttpRequest) { //otro explorador
		    req = new XMLHttpRequest();
		}
			var myObjectName = document.ActiveJAMAC;
			//req.objectName = this.objectName;
			//req.objectName = myObjectName;		    
			req.open("GET", url, false);
			req.onreadystatechange = eval (myObjectName + ".ManejadorEventos;");			
		    req.send("");
	      
	}

	JAMAutoComplete.prototype.inicializaComplete = function (){
		var index;
		for (index = 0; index<completeTextsList.length; index++){
			completeTextsList[index] = "";
		}
		 	
		
	}

	 
	//función que recoge el documento XML devuelto por el servicio web, y guarda en la variable completeTextsList las localidades que se incluyen en él.
	JAMAutoComplete.prototype.parsearXML = function (){
		//function parsearXML () {
	   
		//alert('vamos a parsear');
		var objeto_xml = xmlDoc.documentElement;
		//alert('elemento es'+objeto_xml);
		//alert("jj"+ objeto_xml.getElementsByTagName('ReturnValue').length);
		// Hay que inicializar las variables para ese elemento.

		sugsDiv.style.left="";
		var tipojama=tipo;
		highLightedSugForeColor = "#FFFFFF"; // color del sombreado al posicionarte sobre la opcion
		nonHighLightedSugForeColor = "#000000"; // Color de las letras del cuadro para busquedas de 1 campo
		sugsDivPadding = "1px"; // ancho del borde de las opciones
		sugsDivBackColor = "#A2A19F"; // color Borde del cuadro de opciones
		
		
		
		//var numerolocalidades = objeto_xml.childNodes[1].childNodes.length ;
		var i = 0; //contador para recorrer los hijos
		var j= 0; //contador para recorrer x e y
		var l= 0; // contador para recorrer variables iniciales.


		var indicePrimerHijo = 1;//variable para acceder al primer hijo Explorer = 0, firefox = 1
        
		eval(this.objectName + '.inicializaComplete()');//inicializamos el array para que no guarde resultados que alteren las sugerencias
		//alert("jj"+ objeto_xml.getElementsByTagName('ReturnValue').length);
		if (IE) {
			indicePrimerHijo = 0;
		}
	    
		//if (objeto_xml.getElementsByTagName('anyType').length > 0){
		//alert("jj"+ objeto_xml.getElementsByTagName('Nombres').length);
		if (objeto_xml.childNodes[indicePrimerHijo].firstChild) {	//si tiene algun hijo
			var objeto_tipo = objeto_xml.getElementsByTagName("tipo")[0].firstChild;	        
	        while (objeto_tipo) {	                  
	            if (objeto_tipo.nodeName[0] != '#') {
	                tipojama = objeto_tipo.childNodes[0].nodeValue;					
	                l++;
	            }
	            objeto_tipo = objeto_tipo.nextSibling;
	        }
			 //alert('vuelta es '+tipojama);
			 //var ventana=tipojama.substr(0,3);
			 //if (ventana == "open")
			 //{
				//alert('ventana es '+ventana);
				//upr=tipojama.substr(0,tipojama.lenght);
				//var url_open="window.open('"+ upr + "');"
			 //}
			 eval(tipojama);
			 if (objeto_xml.getElementsByTagName("posicion")[0])
	        {	        
		    var objeto_posicion = objeto_xml.getElementsByTagName("posicion")[0].firstChild;	        
	       
			while (objeto_posicion) {	                       
				//alert(objeto_posicion.childNodes[0].nodeValue);
	            if (objeto_posicion.nodeName[0] != '#') {
	                var toString = objeto_posicion.childNodes[0].nodeValue;
					if (j == 0) 
					{
						  sugsDiv.style.top = toString + "px";						  
            
					}
					else
					{
						sugsDiv.style.left = toString + "px";
					}
					//toString = toString.replace('Ñ','\u00D1');
	                //completeTextsList[i]=toString;
					//alert("jj"+ toString);
	               j++;
	            }
	            objeto_posicion= objeto_posicion.nextSibling;
				}
	        }
			var objeto_hijo = objeto_xml.getElementsByTagName("Nombres")[0].firstChild;	        
	        while (objeto_hijo) {
	            //alert("ii"+ objeto_hijo.nodeName[0]);            
	            if (objeto_hijo.nodeName[0] != '#') {
	                var toString = objeto_hijo.childNodes[0].nodeValue;
					toString = toString.replace('Ñ','\u00D1');
	                completeTextsList[i]=toString;
					//alert("ii"+ toString);
	                i++;
	            }
	            objeto_hijo = objeto_hijo.nextSibling;
	        }
	        
	    }
		
		eval (this.objectName + ".pintaSugerencias(tipojama)");//tanto si tiene hijos como sino pinto los resultados, ya que sino tiene hijos, pintaresultados se encarga de esconder las sugerencias.
	    
}

	JAMAutoComplete.prototype.quitaTildes = function(cadena) {
		var res;
		res = cadena.replace('\u00E1','a');
		res = res.replace('\u00E9','e');
		res = res.replace('\u00ED','i');
		res = res.replace('\u00F3','o');
		res = res.replace('\u00FA','u');
		
		res = res.replace('\u00C1',"A");
		res = res.replace('\u00C9',"E");
		res = res.replace('\u00CD',"I");
		res = res.replace('\u00D3',"O");
		res = res.replace('\u00DA',"U");
		
		res = res.replace('\u00DC',"U");
		res = res.replace('\u00FC',"u");
		
		//res = res.replace('\u00F1','ñ');
		return(res);
	}

	
	
	// Función que pinta en el cuadro de sugerencias las localidades
	JAMAutoComplete.prototype.pintaSugerencias = function(tipojama) {
	    var txt = this.inputBox.value.replace('\u00D3',"o");
		eval ("var txt = " + this.objectName + ".quitaTildes(txt)");
		var fullSetString = "";
	    var index = 0;
	    var empty = true;
    	var textoResaltado = "";
		var textoSinResaltar = "";
		var textomedio = "";
		var textoSinResaltarfinal="";

		numeroSugerencias = 0; 
		if (txt.length > 2) {
		    eval(this.objectName + '.showSugs(true)');
			eval (this.objectName + ".localidadSeleccionada = '';");
			
			indiceParcial = 0; //cuando entramos del bucle ponemos el indice a 0, ya que  cuando entremos, habrá que sobreescribir
							   //los resultados anteriores
			eval(this.objectName + '.indiceVisiblesSeleccionada =' + 0);
			eval("var idLocalidadAqui = " + this.objectName + ".idInputBox");
			//alert (completeTextsList.length);
			for (index = 0; index < completeTextsList.length; index++)
		    {
    			
				var comp='astroc';
			    var checker = completeTextsList[index].substr(0, completeTextsList[index].lenght).toUpperCase();
				//alert("uper" + txt.toUpperCase());
                //if (txt.toUpperCase() == checker)
				
				//if (checker.indexOf(txt.toUpperCase())!="") {
				if (checker != "")
				{
					
					//alert('checker' + checker);
					var pos_inicial="";
					var pos_final="";
					var pos_med="";				
					posini=checker.indexOf(txt.toUpperCase());
					posinipos=posini+txt.length;
					//alert("posinicial" + posini);
					//alert("posfinal" + posinipos);
					//alert("longitud" + checker.length);
					if(posini == 0){
					pos_inicial=1;
					textoResaltado = completeTextsList[index].substr(0,txt.length);
					textoSinResaltar = completeTextsList[index].substr(txt.length,checker.length);
					}
					if(posinipos == checker.length){
						pos_final=1;
						textoSinResaltar = completeTextsList[index].substr(0,posini-1);
						textoResaltado = completeTextsList[index].substr(posini,txt.length);
					}
					if(pos_inicial == "" && pos_final =="")
					{
						//textoSinResaltar = completeTextsList[index].substr(0,posini);
						//textoSinResaltarfinal = completeTextsList[index].substr(posini+txt.length,checker.length);
						//textomedio = completeTextsList[index].substr(posini,txt.length);
						textoSinResaltar = completeTextsList[index];
						bloques_texto=textoSinResaltar.split("|");
						n_campos=bloques_texto.length;
						
						textoSinResaltar=textoSinResaltar.replace(/{/gi,"<");
						textoSinResaltar=textoSinResaltar.replace(/}/gi,">");
						
						
						pos_med=1;
					}

					posinipos=posini+txt.length;
					/*alert("posinicial" + pos_inicial);
					alert("posfinal" + pos_final);
					alert("posmedio" + pos_med);				
					
					alert("texto resaltado"+textoResaltado);					
					alert("texto sinresaltar "+textoSinResaltar);
					alert("texto sin resaltar final "+textoSinResaltarfinal);
					alert("texto medio "+textomedio);*/

					numeroSugerencias = numeroSugerencias + 1;
					parcialTextsList[indiceParcial] = completeTextsList[index];//guardo en el array parcial el resultado 
				
					indiceParcial = indiceParcial +1; //aumento el indice de los resultados parciales que se muestran, esto es util para saber el numero de localidades que se muestran, ya que el array siempre va a tener 10, aunque algunas sean vacias.
					
					enlace="portada_dep.asp";
					//alert(n_campos);
					//tipojama=2;
					//alert(tipojama);
					if (tipojama ==2)
					
					{
						fullSetString += "<div onclick='javascript: enlaceMenu(enlace); " + this.objectName + ".localidadSeleccionada = \"" + completeTextsList[index] + "\"; " + "document.getElementById(\""+idLocalidadAqui+"\").value = \"" + completeTextsList[index] +"\"; '" + //objectName + ".hideSugs(); '" 
							"onMouseOver='javascript: "						
							//+  objectName + ".localidadSeleccionada = \"" + completeTextsList[index] + "\"; " + // Guardar en la variable la localidad por la que pasa el raton.
							+  this.objectName + ".indiceVisiblesSeleccionada = " + indiceParcial //Las sugerencias que se muestran, pueden no ser las que se recogieron al princio, este indice contabiliza las que se muestran actualmente. Esto era util si no se pide al webservice un nuevo array con cada letra,.
							+ "; this.style.color = \""+highLightedSugForeColor+"\"; this.style.background = \""+highLightedSugBackColor+"\";"+ (document.all ? "this.style.filter=\"alpha(opacity=" + highLightedSugOpacity + ")\";'" : "this.style.opacity=" + (highLightedSugOpacity / 100) + ";'") + //Modifica los colores del div de la localidad.
							"onMouseOut ='javascript: this.style.color = \"" + nonHighLightedSugForeColor + "\"; this.style.background = \""+nonHighLightedSugBackColor+"\";" + 
							(document.all ? "this.style.filter=\"alpha(opacity=" + nonHighLightedSugOpacity + ")\";'" : "this.style.opacity=" + (nonHighLightedSugOpacity) + ";'") +
							"style='cursor: pointer; color: " + nonHighLightedSugForeColor+"; background-color: "+nonHighLightedSugBackColor+ ";" +(document.all ? ("filter:alpha(opacity=" + nonHighLightedSugOpacity + ");'") : ("opacity=" + (nonHighLightedSugOpacity ) + ";'")) + "id='" + this.objectName + "_Sugerencia" + (index+1) + "'" +
							">" + textoSinResaltar + "<span style='color:" + colorNoResaltado + "'>" + textoResaltado+ "</span>" + "</div>" ;
						empty = false;
					
					}
					else
					{
					
						blanco="#B2C0CB";
						if (n_campos == 1)
						{
							
							fullSetString += "<div>" + textoSinResaltar +"</div>" ;
							empty = false;	
							
							
						}
						else
						{
							if (n_campos == 2)
							{
								fullSetString += "<div  onclick='javascript: " +  this.objectName + ".localidadSeleccionada = \"" + completeTextsList[index] + "\"; " + "document.getElementById(\""+idLocalidadAqui+"\").value = \"" + completeTextsList[index] +"\"; '" + //objectName + ".hideSugs();'" +
								"onMouseOver='javascript: "						
								//+  objectName + ".localidadSeleccionada = \"" + completeTextsList[index] + "\"; " + // Guardar en la variable la localidad por la que pasa el raton.
								+  this.objectName + ".indiceVisiblesSeleccionada = " + indiceParcial //Las sugerencias que se muestran, pueden no ser las que se recogieron al princio, este indice contabiliza las que se muestran actualmente. Esto era util si no se pide al webservice un nuevo array con cada letra,.
								+ "; this.style.color = \""+highLightedSugForeColor+"\"; this.style.background = \""+blanco+"\";"+ (document.all ? "this.style.filter=\"alpha(opacity=" + highLightedSugOpacity + ")\";'" : "this.style.opacity=" + (highLightedSugOpacity / 100) + ";'") + //Modifica los colores del div de la localidad.
								"onMouseOut ='javascript: this.style.color = \"" + nonHighLightedSugForeColor + "\"; this.style.background = \""+nonHighLightedSugBackColor+"\";" + 
								(document.all ? "this.style.filter=\"alpha(opacity=" + nonHighLightedSugOpacity + ")\";'" : "this.style.opacity=" + (nonHighLightedSugOpacity) + ";'") +
								"style='cursor: pointer; color: " + nonHighLightedSugForeColor+"; background-color: "+nonHighLightedSugBackColor+ ";" +(document.all ? ("filter:alpha(opacity=" + nonHighLightedSugOpacity + ");'") : ("opacity=" + (nonHighLightedSugOpacity ) + ";'")) + "id='" + this.objectName + "_Sugerencia" + (index+1) + "'" +
								"><table width='100%' border='0'><tr><td width='50%' class='MenuItem'>" + bloques_texto[0] + "</td>" + "<td width='50%' class='MenuItem1'>" + bloques_texto[1] + "</td></tr></table></div>" ;
								empty = false;
				
							}
							else
							{
								if (n_campos == 3)
								{
									fullSetString += "<div  onclick='javascript: " +  this.objectName + ".localidadSeleccionada = \"" + completeTextsList[index] + "\"; " + "document.getElementById(\""+idLocalidadAqui+"\").value = \"" + completeTextsList[index] +"\"; '" + //objectName + ".hideSugs();'" +
									"onMouseOver='javascript: "						
									//+  objectName + ".localidadSeleccionada = \"" + completeTextsList[index] + "\"; " + // Guardar en la variable la localidad por la que pasa el raton.
									+  this.objectName + ".indiceVisiblesSeleccionada = " + indiceParcial //Las sugerencias que se muestran, pueden no ser las que se recogieron al princio, este indice contabiliza las que se muestran actualmente. Esto era util si no se pide al webservice un nuevo array con cada letra,.
									+ "; this.style.color = \""+highLightedSugForeColor+"\"; this.style.background = \""+blanco+"\";"+ (document.all ? "this.style.filter=\"alpha(opacity=" + highLightedSugOpacity + ")\";'" : "this.style.opacity=" + (highLightedSugOpacity / 100) + ";'") + //Modifica los colores del div de la localidad.
									"onMouseOut ='javascript: this.style.color = \"" + nonHighLightedSugForeColor + "\"; this.style.background = \""+nonHighLightedSugBackColor+"\";" + 
									(document.all ? "this.style.filter=\"alpha(opacity=" + nonHighLightedSugOpacity + ")\";'" : "this.style.opacity=" + (nonHighLightedSugOpacity) + ";'") +
									"style='cursor: pointer; color: " + nonHighLightedSugForeColor+"; background-color: "+nonHighLightedSugBackColor+ ";" +(document.all ? ("filter:alpha(opacity=" + nonHighLightedSugOpacity + ");'") : ("opacity=" + (nonHighLightedSugOpacity ) + ";'")) + "id='" + this.objectName + "_Sugerencia" + (index+1) + "'" +
									"><table width='100%' border='0'><tr><td width='33%' class='MenuItem'>" + bloques_texto[0] + "</td>" + "<td width='33%' class='MenuItem1'>" + bloques_texto[1] + "</td>" + "<td width='33%' class='MenuItem2' >" + bloques_texto[2] + "</td></tr></table></div>" ;
									empty = false;
								
								}
								else
								{
								
									if (n_campos == 4)
									{
										fullSetString += "<div  onclick='javascript: " +  this.objectName + ".localidadSeleccionada = \"" + completeTextsList[index] + "\"; " + "document.getElementById(\""+idLocalidadAqui+"\").value = \"" + completeTextsList[index] +"\"; '" + //objectName + ".hideSugs();'" +
											"onMouseOver='javascript: "						
											//+  objectName + ".localidadSeleccionada = \"" + completeTextsList[index] + "\"; " + // Guardar en la variable la localidad por la que pasa el raton.
											+  this.objectName + ".indiceVisiblesSeleccionada = " + indiceParcial //Las sugerencias que se muestran, pueden no ser las que se recogieron al princio, este indice contabiliza las que se muestran actualmente. Esto era util si no se pide al webservice un nuevo array con cada letra,.
											+ "; this.style.color = \""+highLightedSugForeColor+"\"; this.style.background = \""+nonHighLightedSugBackColor+"\";"+ (document.all ? "this.style.filter=\"alpha(opacity=" + highLightedSugOpacity + ")\";'" : "this.style.opacity=" + (highLightedSugOpacity / 100) + ";'") + //Modifica los colores del div de la localidad.
											"onMouseOut ='javascript: this.style.color = \"" + nonHighLightedSugForeColor + "\"; this.style.background = \""+blanco+"\";" + 
											(document.all ? "this.style.filter=\"alpha(opacity=" + nonHighLightedSugOpacity + ")\";'" : "this.style.opacity=" + (nonHighLightedSugOpacity) + ";'") +
											"style='cursor: pointer; color: " + blanco+"; background-color: "+blanco+ ";" +(document.all ? ("filter:alpha(opacity=" + nonHighLightedSugOpacity + ");'") : ("opacity=" + (nonHighLightedSugOpacity ) + ";'")) + "id='" + this.objectName + "_Sugerencia" + (index+1) + "'" +
											"><table width='100%' border='0'><tr><td width='25%' class='MenuItem'>" + bloques_texto[0] + "</td>" + "<td width='25%' class='MenuItem1'>" + bloques_texto[1] + "</td>" + "<td width='25%' class='MenuItem2' >" + bloques_texto[2] + "</td>"+ "<td width='25%' class='MenuItem'>" + bloques_texto[3] + "</td>"+ "<td width='25%' class='MenuItem' >" + bloques_texto[4] + "</td></tr></table></div>" ;
											empty = false;
									
									}
									else
									{
									

											fullSetString += "<div  onclick='javascript: " +  this.objectName + ".localidadSeleccionada = \"" + completeTextsList[index] + "\"; " + "document.getElementById(\""+idLocalidadAqui+"\").value = \"" + completeTextsList[index] +"\"; '" + //objectName + ".hideSugs();'" +
											"onMouseOver='javascript: "						
											//+  objectName + ".localidadSeleccionada = \"" + completeTextsList[index] + "\"; " + // Guardar en la variable la localidad por la que pasa el raton.
											+  this.objectName + ".indiceVisiblesSeleccionada = " + indiceParcial //Las sugerencias que se muestran, pueden no ser las que se recogieron al princio, este indice contabiliza las que se muestran actualmente. Esto era util si no se pide al webservice un nuevo array con cada letra,.
											+ "; this.style.color = \""+highLightedSugForeColor+"\"; this.style.background = \""+nonHighLightedSugBackColor+"\";"+ (document.all ? "this.style.filter=\"alpha(opacity=" + highLightedSugOpacity + ")\";'" : "this.style.opacity=" + (highLightedSugOpacity / 100) + ";'") + //Modifica los colores del div de la localidad.
											"onMouseOut ='javascript: this.style.color = \"" + nonHighLightedSugForeColor + "\"; this.style.background = \""+blanco+"\";" + 
											(document.all ? "this.style.filter=\"alpha(opacity=" + nonHighLightedSugOpacity + ")\";'" : "this.style.opacity=" + (nonHighLightedSugOpacity) + ";'") +
											"style='cursor: pointer; color: " + blanco+"; background-color: "+blanco+ ";" +(document.all ? ("filter:alpha(opacity=" + nonHighLightedSugOpacity + ");'") : ("opacity=" + (nonHighLightedSugOpacity ) + ";'")) + "id='" + this.objectName + "_Sugerencia" + (index+1) + "'" +
											"><table width='100%' border='0'><tr><td width='10%' class='MenuItem'>" + bloques_texto[4] + "</td>" + "<td width='30%' class='MenuItem1'>" + bloques_texto[2] + "</td>" + "<td width='10%' class='MenuItem2' >" + bloques_texto[0] + "</td>"+ "<td width='10%' class='MenuItem2'>" + bloques_texto[3] + "</td>"+ "<td width='15%' class='MenuItem' >" + bloques_texto[1] + "</td>"+ "<td width='15%' class='MenuItem1' ></td></tr></table></div>" ;
											empty = false;								
										
																		
									}
								
								}
							
							}
						
						}

					}
                    
					//alert (fullSetString);
					
			    }   //document.getElementById(\"" + objectName + "_Sugerencia"+ (1)	+ "\").style.color = \"" + nonHighLightedSugForeColor + "\"; document.getElementById(\"" + objectName + "_Sugerencia"+ (1)	+ "\").style.background = \""+nonHighLightedSugBackColor+"\";"  +           
		    }
					
					
									   
			/*Queremos que nuestro div con las sugerencias sea dínamico respecto al número de sugerencias que alberga
			    por lo tanto, cuando el numero de sugerencias sea muy elevado, le ponemos un tamaño a la capa y activamos el scroll
			   en caso contrario, le asignamos a la capa 16 pixeles por cada sugerencia y desactivamos el scroll
			*/
			
			/*if (numeroSugerencias > 9) {
				sugsDiv.style.height = "160px";
				sugsDiv.style.overflow = "scroll";
				//sugsDiv.style.overflow = "auto";
				
			}
			else{
				sugsDiv.style.overflow = "hidden";
				sugsDiv.style.height = numeroSugerencias*16 +"px";
			}
			*/
			
			
	    } else {
			 eval(this.objectName + '.hideSugs()');
	    }
		
	    if (empty == true){
			eval(this.objectName + '.hideSugs()');
			
		}
	    sugsDiv.innerHTML = fullSetString;

    	
	}
	
//**********************************************************************************************************************

	//Función que se encarga de mover una posición arriba la sugerencia seleccionada.
    JAMAutoComplete.prototype.upSeleccion = function() {
		
		var myObjectName = document.ActiveJAMAC; //anteriormente era this.objectName
		var indiceup = eval(myObjectName + '.indiceVisiblesSeleccionada');
	    if(indiceParcial > 0){ //en el caso de que haya alguna sugerencia se realizan las operaciones.
			if (indiceup > 1) { //Si esta seleccionada cualquiera menos la primera, se des-selecciona, y se selecciona la anterior 
				
				document.getElementById(myObjectName + '_Sugerencia' + indiceup).style.color =  nonHighLightedSugForeColor;
				document.getElementById(myObjectName + '_Sugerencia' + indiceup).style.background = nonHighLightedSugBackColor;
				document.getElementById(myObjectName + '_Sugerencia' + indiceup).style.opacity= (nonHighLightedSugOpacity );
				indiceup = indiceup -1;
				
			}
			else{ //si se encuentra en la primera o no hay ninguna seleccionada, que la seleecionada pase a ser la última.
				 
				if (indiceup = 1) { //si esta seleccionada la primera la des-seleccionamos. La otra posibilidad es darle "up" sin tener ninguna seleccionada aun.
					document.getElementById(myObjectName + '_Sugerencia' + indiceup).style.color =  nonHighLightedSugForeColor;
					document.getElementById(myObjectName + '_Sugerencia' + indiceup).style.background = nonHighLightedSugBackColor;
					document.getElementById(myObjectName + '_Sugerencia' + indiceup).style.opacity= (nonHighLightedSugOpacity);
				}
				indiceup = indiceParcial;
				
			}
			
				eval(myObjectName + '.indiceVisiblesSeleccionada =' + indiceup);
				//Coloreamos la seleccionada una vez se ha actualizado los indices.
				document.getElementById(myObjectName + '_Sugerencia' + indiceup).style.color =  highLightedSugForeColor;
				document.getElementById(myObjectName + '_Sugerencia' + indiceup).style.background = highLightedSugBackColor;
				document.getElementById(myObjectName + '_Sugerencia' + indiceup).style.opacity= highLightedSugOpacity;
				eval (myObjectName + ".localidadSeleccionada = '" + completeTextsList[indiceup-1] + "';");	
		}
	}
	//Función que se encarga de mover una posición abajo la sugerencia seleccionada.
	JAMAutoComplete.prototype.downSeleccion = function() {
		var myObjectName = document.ActiveJAMAC; //anteriormente era this.objectName
		var indicedown = eval(myObjectName + '.indiceVisiblesSeleccionada');
		if(indiceParcial > 0){ //en el caso de que haya alguna sugerencia se realizan las operaciones.
			if (indicedown < indiceParcial){ //Si no estamos en el ultimo elemento
					if (indicedown > 0 ){//Si alguna sugerencia seleccionada se des-selecciona
						document.getElementById(myObjectName + '_Sugerencia' + indicedown).style.color =  nonHighLightedSugForeColor;
						document.getElementById(myObjectName + '_Sugerencia' + indicedown).style.background = nonHighLightedSugBackColor;
						document.getElementById(myObjectName + '_Sugerencia' + indicedown).style.opacity= (nonHighLightedSugOpacity );
					}
					//seleccionamos la siguiente sugerencia
					indicedown = indicedown + 1;
							
				}
			else{  
					if (indicedown = indiceParcial){//des-seleccionamos la última
						document.getElementById(myObjectName + '_Sugerencia' + indiceParcial).style.color =  nonHighLightedSugForeColor;
						document.getElementById(myObjectName + '_Sugerencia' + indiceParcial).style.background = nonHighLightedSugBackColor;
						document.getElementById(myObjectName + '_Sugerencia' + indiceParcial).style.opacity= (nonHighLightedSugOpacity );
					}
					//seleccionamos la primera
					indicedown = 1;
			}
			
				//actualizamos el valor de la variable global 
				eval(myObjectName + '.indiceVisiblesSeleccionada =' + indicedown);
				//en cualquier caso coloreamos la seleccionada como le corresponde
				document.getElementById(myObjectName + '_Sugerencia' + indicedown).style.color =  highLightedSugForeColor;
				document.getElementById(myObjectName + '_Sugerencia' + indicedown).style.background = highLightedSugBackColor;
				document.getElementById(myObjectName + '_Sugerencia' + indicedown).style.opacity= highLightedSugOpacity ;
				eval (myObjectName + ".localidadSeleccionada = '" + completeTextsList[indicedown-1] + "';");
		}	
	}
	
	
    JAMAutoComplete.prototype.checkNewValues = function(evt) {
		var myObjectName;
		myObjectName = document.ActiveJAMAC;
		//alert('evt'+evt.type);
		//alert('urlbase '+urlbase);
		//alert('evt'+evt.srcElement.name);
		//alert('location'+document.location.pathname);
		href=window.location.pathname;
		//alert('path es '+href);
		leaving = (((href.indexOf("://") > -1) || (href.indexOf("www.") > -1)) && (href.indexOf(window.location.host) == -1));
		var docElWidth = document.documentElement.clientWidth;
        var docBodWidth = document.body.clientWidth;
        var realW = 0;
		//alert('docElWidth'+docElWidth);
		//alert('docBodWidth'+docBodWidth);
		//alert('evt.clientY'+evt.clientY);
		//alert('evt.clientX'+evt.clientX);
        if(docElWidth <= docBodWidth)
		{
          realW = docElWidth;
		}
        else
		{
          realW = docBodWidth;
       }
	   //alert('leaving '+leaving);
       if (evt.clientY < 0 && realW < evt.clientX)
	   {
			//alert('Se va a cerrar la pagina');		
			eval (myObjectName + ".cargaXMLdoc(urlbase + '?param1=' + myObjectName,1 )");
			
	   }
		else
		{
			if (leaving)
			{
				//alert('cambiamos de pagina');
				eval (myObjectName + ".cargaXMLdoc(urlbase + '?param1=' + myObjectName + '&cambia_pagina=1',1)");
				
			}
			else
			{
				if (evt.type == 'unload')
				{
					//alert('aparentemente cambia pagina, pero no');
					return false;
				}
				else
				{
					//alert('llegamos a la carga');
					eval (myObjectName + ".cargaXMLdoc(urlbase + '?param1=' + myObjectName,0)");
				}
			}
		}
		
		
		//alert('evt '+evt.srcElement.name);
		//alert('location'+vuelta);
		//alert('vuelta'+vuelta);
		
		
		
		if (vuelta != '')
		{
			eval(vuelta);			
		}
				
		
		
		var lineaAEjecutar = "var txt = " + myObjectName + ".inputBox.value";

		eval (lineaAEjecutar);
		eval ("var txt = " + myObjectName + ".quitaTildes(txt)");
		txt = encodeURIComponent(txt);

		

		
        var fullSetString = "";
        var index = 0;
        var empty = true;

		//alert('tecla '+evt.keyCode);
		
		if ((evt.keyCode == 38) || (evt.keyCode == 40)) { //Si se ha pulsado las teclas "arrows" no se hace nada.
			enlaceMenu('portada_dep.asp');
			return false;
		}
		
		if (evt.keyCode != 38 && evt.keyCode != 40 )
		{
		
			if(txt.length > 6) {
				//alert("veamos");
				//if ((evt.keyCode == 123)); tecla de f12
				//{	
					document.ActiveJAMAC.evento=evt.keyCode;
					//alert('objectname'+myObjectName);
					//eval (myObjectName + ".cargaXMLdoc(urlbase + '?quickname=' + txt + '&param1=' + myObjectName )");
				//}
			}else{	
				eval(myObjectName + '.hideSugs()'); //Si hay menos de 3 letras que la capa de sugerencias desaparezca.
			}
		}
		
    }
	
	JAMAutoComplete.prototype.keyPressed = function(evt) {
		var myObjectName = document.ActiveJAMAC;
		
		
		if ((evt.keyCode == 9) || (evt.keyCode == 13)){
			//eval ("var loca = " + this.objectName + ".localidadSeleccionada");
			eval ("var loca = " + myObjectName + ".localidadSeleccionada");
			if (loca && loca != 'undefined')
				this.value = loca;
			//eval (this.objectName + ".onDeterminedSugsMustBeHidden();");
			eval (myObjectName + ".onDeterminedSugsMustBeHidden();");
		}
		
		//Esto es para el manejo de la localidad seleccionada con las teclas arrows
		if (evt.keyCode == 38) {
				//eval (this.objectName + ".upSeleccion()");
				eval (myObjectName + ".upSeleccion()");
		}
		if (evt.keyCode == 40) {
				//eval (this.objectName + ".downSeleccion()");
				eval (myObjectName + ".downSeleccion()");
		}
    }
	
	//IE no reconoce el evento keyPressed, pero reconoce el keyDowned.  Furefox, reconoce los dos, por lo tanto para que el codigo no se ejecute dos veces en
	//firefox, utilizamos la variable document.all que solo existe si se utiliza I.Explorer.
	
	JAMAutoComplete.prototype.keyDowned = function(evt) {
		var myObjectName = document.ActiveJAMAC;
	
		
		if (document.all) {
		  
			//alert('el evento es '+evt.keyCode);
			if ((evt.keyCode == 9)|| (evt.keyCode == 13)){
				
			    
				//eval (this.objectName + ".onDeterminedSugsMustBeHidden();");
				var cadenaAEjecutar = "var loca = " + myObjectName + ".localidadSeleccionada";
				//alert (cadenaAEjecutar);
				eval (cadenaAEjecutar);
				//alert (loca);
				//document.getElementById(myObjectName.idInputBox).value = loca;
				//myObjectName.inputBox.value = loca;
				var txt = "'" + loca + "'"
				//if (txt != 'undefined')
					//eval (myObjectName + ".setValue('" + loca + "');");
				eval (myObjectName + ".onDeterminedSugsMustBeHidden();");
			}
			//Esto es para el manejo de la localidad seleccionada con las teclas arrows
			if (evt.keyCode == 38) {
					//eval (this.objectName + ".upSeleccion()");	
					eval (myObjectName + ".upSeleccion()");
			}
			
			if (evt.keyCode == 40) {
					//eval (this.objectName + ".downSeleccion()");
					
					eval (myObjectName + ".downSeleccion()");
			}
		}
			//alert("llega aqui")  
	}
	
	
	JAMAutoComplete.prototype.setValue = function (txtValue) {
		
        this.inputBox.value = txtValue;
    }

    JAMAutoComplete.prototype.hideSugs = function () {
        sugsDiv.style.display = 'none';
    }

    JAMAutoComplete.prototype.showSugs = function (vengoDeCheckNewValues) {
        if (sugsDiv.style.display != 'block')
        {
            sugsDiv.style.display = 'block';
            if (!vengoDeCheckNewValues) eval(this.objectName + '.checkNewValues()');
				if (sugsDiv.style.left =='')
				{
					var position = getElementCoord(this.inputBox);
					var altura = (position[1] + this.inputBox.offsetHeight) + 5;
					sugsDiv.style.left = position[0] + "px";
					sugsDiv.style.top = altura + "px";
				}
            
        }
    }

    JAMAutoComplete.prototype.determineIfHideSugs = function (evt) {
		var index = 0;
		for (index = 0; index < document.todosLosJAMACs.length; index ++) {
			var myJAMAC = document.todosLosJAMACs[index];
			if( clickedOutsideElements(idSugsDiv, this.idInputBox, evt) ) { // || ( !eval(this.objectName + '.inputBoxHasFocus()')  && !eval(this.objectName + '.sugsDivHasFocus()' ) ) ) {
				if (sugsDiv.style.display == 'block') { //si la capa de las sugerencias  se esta mostrando que muestre la sugerencia seleccionada
					//document.getElementById(idInputBox).value = eval(this.objectName + ".localidadSeleccionada;");// localidadSeleccionada; //eval(this.objectName + ".localidadSeleccionada;");
					//if ( ( !eval(this.objectName + '.inputBoxHasFocus()')  && !eval(this.objectName + '.sugsDivHasFocus()' ) ) && (clickedOutsideElements(idSugsDiv, idInputBox, evt)) ) eval(this.objectName + '.hideSugs()');
					//document.getElementById(idInputBox).value = completeTextsList[indiceSugerenciaSeleccionada];
					//document.getElementById(idInputBox).value = localidadSeleccionada;
					eval(myJAMAC + '.onDeterminedSugsMustBeHidden()');
					//JAMAutoComplete.prototype.onDeterminedSugsMustBeHidden();
				}
			}
		}
    }
	
	JAMAutoComplete.prototype.onDeterminedSugsMustBeHidden = function (evt) {
		
		var myObjectName = document.ActiveJAMAC; //era this.objectName
		eval ("var ib = " + myObjectName + ".idInputBox");
		eval ("var localidad = " + myObjectName + ".localidadSeleccionada");
		//document.getElementById(ib).value = eval(this.objectName + ".localidadSeleccionada;");
		//eval (this.objectName + ".inputBox.value = '" + localidad + "'");
		eval ("var txt = '" + localidad + "'");
		if (txt != 'undefined') 
		{
			eval (myObjectName + ".inputBox.value = " + myObjectName + ".localidadSeleccionada");
			eval ("var txtAssigned = " + myObjectName + ".inputBox.value");
			//if (txtAssigned == 'undefined')
			//	eval (myObjectName + ".inputBox.value = ''");
		}
		eval (myObjectName + '.hideSugs()');
	}
	

	JAMAutoComplete.prototype.inputBoxHasFocus = function () {
		var hf;
		// IE uses activeElement
		if ( document.activeElement ) hf = document.activeElement;
		// Firefox uses focusNode
		else hf = document.focusNode;
		
		return hf == this.inputBox;
	}
	
		JAMAutoComplete.prototype.sugsDivHasFocus = function () {
		var hf;
		// IE uses activeElement
		if ( document.activeElement ) hf = document.activeElement;
		// Firefox uses focusNode
		else hf = document.focusNode;
		
		return hf == sugsDiv;
	}
	
	

    /****************** Funciones de estilo ***********************/
    JAMAutoComplete.prototype.getHighLightedSugForeColor = function () {
        return highLightedSugForeColor;
    }
    JAMAutoComplete.prototype.setHighLightedSugForeColor = function (color) {
        highLightedSugForeColor = color;
    }
    JAMAutoComplete.prototype.getHighLightedSugBackColor = function () {
        return highLightedSugBackColor;
    }
    JAMAutoComplete.prototype.setHighLightedSugBackColor = function (color) {
        highLightedSugBackColor = color;
    }
    JAMAutoComplete.prototype.getHighLightedSugOpacity = function () {
        return highLightedSugOpacity;
    }
    JAMAutoComplete.prototype.setHighLightedSugOpacity = function (opacity) {
        highLightedSugOpacity = opacity;
    }
    JAMAutoComplete.prototype.getNonHighLightedSugForeColor = function () {
        return nonHighLightedSugForeColor;
    }
    JAMAutoComplete.prototype.setNonHighLightedSugForeColor = function (color) {
        nonHighLightedSugForeColor = color;
    }
    JAMAutoComplete.prototype.getNonHighLightedSugBackColor = function () {
        return nonHighLightedSugBackColor;
    }
    JAMAutoComplete.prototype.setNonHighLightedSugBackColor = function (color) {
        nonHighLightedSugBackColor = color;
    }
    JAMAutoComplete.prototype.getNonHighLightedSugOpacity = function () {
        return nonHighLightedSugOpacity;
    }
    JAMAutoComplete.prototype.setNonHighLightedSugOpacity = function (opacity) {
        nonHighLightedSugOpacity = opacity;
    }

    JAMAutoComplete.prototype.getSugsDivBorder = function () {
        return sugsDivBorder;
    }
    JAMAutoComplete.prototype.setSugsDivBorder = function (border) {
        sugsDivBorder = border;
        sugsDiv.style.border = sugsDivBorder;
    }
    JAMAutoComplete.prototype.getSugsDivPadding = function () {
        return sugsDivPadding;
    }
    JAMAutoComplete.prototype.setSugsDivPadding = function (padding) {
        sugsDivPadding = padding;
        sugsDiv.style.padding = padding;
    }
    /**
     * Esta funcion devuelve el color de fondo de la capa de sugerencias
     * @return El color de fondo de la capa de sugerencias, como String
     * @type String
     */
    JAMAutoComplete.prototype.getSugsDivBackColor = function () {
        return sugsDivBackColor;
    }
    JAMAutoComplete.prototype.setSugsDivBackColor = function (color) {
        sugsDivBackColor = color;
        sugsDiv.style.background = color;
    }
    JAMAutoComplete.prototype.getSugsDivOpacity = function () {
        return sugsDivOpacity;
    }
    JAMAutoComplete.prototype.setSugsDivOpacity = function (opacity) {
        sugsDivOpacity = opacity;
        setOpacity(sugsDiv, opacity);
    }


    JAMAutoComplete.prototype.getSugsDiv = function () {
        return sugsDiv;
    }


    /****************** Funciones Auxiliares **********************/
	
    function getElementCoord(element) {
        var curTop = 0;
        var curLeft = 0;

        if (element.offsetParent) {
            do {
                curLeft += element.offsetLeft;
                curTop += element.offsetTop;
            } while ((element = element.offsetParent))
        }
        return [curLeft, curTop];
    }
	


    function getEventTarget(evt) {
        var targ = (evt.target) ? evt.target : evt.srcElement;
        if(targ != null && targ.nodeType == 3) targ = targ.parentNode;
        return targ;
    }

    function clickedOutsideElements(elemId1, elemId2, evt) {
		if (!elemId1 || !elemId2 || !evt) return true;
        var theElem = '';
        if(window.event) theElem = getEventTarget(window.event);
        else theElem = getEventTarget(evt);
        while(theElem != null) {
            if(theElem.id == elemId1 || theElem.id == elemId2) return false;
            theElem = theElem.parentNode;
        }
        return true;
    }

    function addEvent(obj, evType, fn){
        if (obj.addEventListener){
			obj.addEventListener(evType, fn, false);
            return true;
        } else if (obj.attachEvent) {
			var r = obj.attachEvent("on"+evType, fn);
            return r;
        } else {
			return false;
        }
    }

    function setOpacity (element, opacity) {
        if (document.all) {
            element.style.filter="alpha(opacity=" + opacity + ")";
        } else {
            element.style.opacity = opacity / 100;
        }
    }
	
	function URLEncode (clearString) {
	  var output = '';
	  var x = 0;
	  clearString = clearString.toString();
	  var regex = /(^[a-zA-Z0-9_.]*)/;
	  while (x < clearString.length) {
		var match = regex.exec(clearString.substr(x));
		if (match != null && match.length > 1 && match[1] != '') {
			output += match[1];
		  x += match[1].length;
		} else {
		  if (clearString[x] == ' ')
			output += '+';
		  else {
			var charCode = clearString.charCodeAt(x);
			var hexVal = charCode.toString(16);
			output += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase();
		  }
		  x++;
		}
	  }
	  return output;
	}


}

