﻿

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); 
	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(')'));
	return provincia;
}


JAMAutoComplete = function (pInputBox, pObjectName, pIdInputBox) {
    this.inputBox = pInputBox;
    this.inputBox.idInputBox = pIdInputBox;

    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;
	this.inputBox.objectName = pObjectName;

	
    var highLightedSugForeColor = "#FFFFFF";
    var highLightedSugBackColor = "#000000";
    var highLightedSugOpacity = 100;
    var nonHighLightedSugForeColor = "#000000";
    var nonHighLightedSugBackColor = "#FFFFFF";
    var nonHighLightedSugOpacity = 80;
    //var sugsDivBorder = "1px sold #ccc";
	var sugsDivBorder = "solid 1px #CCC";
    var sugsDivPadding = "5px";
    var sugsDivBackColor = "#FFFFFF";
    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 = window.top.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.textAlign = 'left';
	sugsDiv.style.zIndex = 9999999;
    sugsDiv.style.display = "none";
    sugsDiv.style.position = "absolute";
	sugsDiv.style.font =  "normal 12px Arial";
    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 () {
        //addEvent(document, "click", eval(this.objectName + '.determineIfHideSugs'));
		var myObjectName = window.top.document.ActiveJAMAC; // antes era this.inputBox;
		addEvent(document, "click", this.determineIfHideSugs);
		//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.top.document.body.appendChild(sugsDiv);
		//alert ('capa insertada');
    }
    
    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 = "/services/localidades/getLocalidades.asmx/LocalityServer"
	
	//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 = window.top.document.ActiveJAMAC;
		if (req.readyState == 4) {
			if (req.status == 200){
				xmlDoc = req.responseXML;
				//eval (this.objectName + ".parsearXML()");
				eval (myObjectName + ".parsearXML()");
			}			
		}
		
	}
	
	// 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) {
	    
	    if (window.ActiveXObject) { //si es Explorer
	        req = new ActiveXObject("Microsoft.XMLHTTP");
			IE = true;
	    } 
	    else if (window.XMLHttpRequest) { //otro explorador
		    req = new XMLHttpRequest();
		}
			var myObjectName = window.top.document.ActiveJAMAC;
		    req.onreadystatechange = eval (myObjectName + ".ManejadorEventos;");
		    req.open("GET", url, true);
		    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 () {
	    var objeto_xml = xmlDoc.documentElement;
		var i = 0; //contador para recorrer los hijos
		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
		if (IE) {
			indicePrimerHijo = 0;
		}
	    
		if (objeto_xml.childNodes[indicePrimerHijo].firstChild) {	//si tiene algun hijo
		    var objeto_hijo = objeto_xml.getElementsByTagName("Nombres")[0].firstChild;	        
	        while (objeto_hijo) {
	                       
	            if (objeto_hijo.nodeName[0] != '#') {
	                var toString = objeto_hijo.childNodes[0].nodeValue;
	                completeTextsList[i]=toString;
	                i++;
	            }
	            objeto_hijo = objeto_hijo.nextSibling;
	        }
	    }
		eval (this.objectName + ".pintaSugerencias()");//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('\u00E0','a');
		res = res.replace('\u00E8','e');
		res = res.replace('\u00EC','i');
		res = res.replace('\u00F2','o');
		res = res.replace('\u00F9','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('\u00C0',"A");
		res = res.replace('\u00C8',"E");
		res = res.replace('\u00CC',"I");
		res = res.replace('\u00D2',"O");
		res = res.replace('\u00D9',"U");
		
		res = res.replace('\u00DC',"Ü");
		res = res.replace('\u00FC',"ü");
		
		res = res.replace('\u00F1','ñ');
		res = res.replace('\u00D1','Ñ');
		
		return(res);
	}

	
	
	// Función que pinta en el cuadro de sugerencias las localidades
	JAMAutoComplete.prototype.pintaSugerencias = function() {
	    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 = "";
		
		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 (idLocalidadAqui);
			for (index = 0; index < completeTextsList.length; index++)
		    {
    			textoResaltado = completeTextsList[index].substr(0,txt.length);
				textoSinResaltar = completeTextsList[index].substr(txt.length);
			    var checker = completeTextsList[index].substr(0, txt.length).toUpperCase();
                if (txt.toUpperCase() == checker) {
					
					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.
					
					if (eval("!" + this.objectName + ".localidadSeleccionada;")) {
						localidadSeleccionada = completeTextsList[index].replace(/'/gi, "´");
						eval (this.objectName + ".localidadSeleccionada = \"" + completeTextsList[index].replace(/'/gi, "´") + "\";");
						//alert (eval (this.objectName + ".localidadSeleccionada;"));
					}
					
                    fullSetString += "<div onclick='javascript: " +  this.objectName + ".localidadSeleccionada = \"" + completeTextsList[index].replace(/'/gi, "´") + "\"; " + window.top.document.ActiveJAMAC + ".inputBox.value = \"" + completeTextsList[index].replace(/'/gi, "´") +"\"; " + window.top.document.ActiveJAMAC + ".hideSugs(); '" + 
                        "onMouseOver='javascript: "						
						+  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) + "'" +
						">" + textoResaltado + "<span style='color:" + colorNoResaltado + "'>" + textoSinResaltar + "</span>" + "</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 = window.top.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 
				
				window.top.document.getElementById(myObjectName + '_Sugerencia' + indiceup).style.color =  nonHighLightedSugForeColor;
				window.top.document.getElementById(myObjectName + '_Sugerencia' + indiceup).style.background = nonHighLightedSugBackColor;
				window.top.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.
					window.top.document.getElementById(myObjectName + '_Sugerencia' + indiceup).style.color =  nonHighLightedSugForeColor;
					window.top.document.getElementById(myObjectName + '_Sugerencia' + indiceup).style.background = nonHighLightedSugBackColor;
					window.top.document.getElementById(myObjectName + '_Sugerencia' + indiceup).style.opacity= (nonHighLightedSugOpacity);
				}
				indiceup = indiceParcial;
				
			}
			
				eval(myObjectName + '.indiceVisiblesSeleccionada =' + indiceup);
				//Coloreamos la seleccionada una vez se ha actualizado los indices.
				window.top.document.getElementById(myObjectName + '_Sugerencia' + indiceup).style.color =  highLightedSugForeColor;
				window.top.document.getElementById(myObjectName + '_Sugerencia' + indiceup).style.background = highLightedSugBackColor;
				window.top.document.getElementById(myObjectName + '_Sugerencia' + indiceup).style.opacity= highLightedSugOpacity;
				eval (myObjectName + ".localidadSeleccionada = '" + completeTextsList[indiceup-1].replace(/'/ig,"´") + "';");	
		}
	}
	//Función que se encarga de mover una posición abajo la sugerencia seleccionada.
	JAMAutoComplete.prototype.downSeleccion = function() {
		var myObjectName = window.top.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
						window.top.document.getElementById(myObjectName + '_Sugerencia' + indicedown).style.color =  nonHighLightedSugForeColor;
						window.top.document.getElementById(myObjectName + '_Sugerencia' + indicedown).style.background = nonHighLightedSugBackColor;
						window.top.document.getElementById(myObjectName + '_Sugerencia' + indicedown).style.opacity= (nonHighLightedSugOpacity );
					}
					//seleccionamos la siguiente sugerencia
					indicedown = indicedown + 1;
							
				}
			else{  
					if (indicedown = indiceParcial){//des-seleccionamos la última
						window.top.document.getElementById(myObjectName + '_Sugerencia' + indiceParcial).style.color =  nonHighLightedSugForeColor;
						window.top.document.getElementById(myObjectName + '_Sugerencia' + indiceParcial).style.background = nonHighLightedSugBackColor;
						window.top.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
				window.top.document.getElementById(myObjectName + '_Sugerencia' + indicedown).style.color =  highLightedSugForeColor;
				window.top.document.getElementById(myObjectName + '_Sugerencia' + indicedown).style.background = highLightedSugBackColor;
				window.top.document.getElementById(myObjectName + '_Sugerencia' + indicedown).style.opacity= highLightedSugOpacity ;
				eval (myObjectName + ".localidadSeleccionada = '" + completeTextsList[indicedown-1].replace(/'/ig,"´") + "';");
		}	
	}
	
    JAMAutoComplete.prototype.checkNewValues = function(evt) {
		var myObjectName;
		myObjectName = window.top.document.ActiveJAMAC;
	
		var lineaAEjecutar = "var txt = " + myObjectName + ".inputBox.value";
		eval (lineaAEjecutar);
		eval ("var txt = " + myObjectName + ".quitaTildes(txt)");
		//txt = encodeURIComponent(txt);
		txt = escape(txt);

		
        var fullSetString = "";
        var index = 0;
        var empty = true;
		
		if ((evt.keyCode == 38) || (evt.keyCode == 40)) { //Si se ha pulsado las teclas "arrows" no se hace nada.
			return false;
		}
		
		if(txt.length > 2) {
			eval (myObjectName + ".cargaXMLdoc(urlbase + '?param1=' + txt )");
		}else{	
			eval(myObjectName + '.hideSugs()'); //Si hay menos de 3 letras que la capa de sugerencias desaparezca.
		}
		
		
    }
	
	JAMAutoComplete.prototype.keyPressed = function(evt) {
		var myObjectName = window.top.document.ActiveJAMAC;
		if ((evt.keyCode == 9) || (evt.keyCode == 13)){
			eval ("var loca = " + myObjectName + ".localidadSeleccionada");
			if (loca && loca != 'undefined')
				loca=loca.replace(/´/ig,"'");
				this.value = 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()");
		}
    }
	
	//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 = window.top.document.ActiveJAMAC;
		
		if (document.all) {
		  
			if ((evt.keyCode == 9)|| (evt.keyCode == 13)){
			    
				var cadenaAEjecutar = "var loca = " + myObjectName + ".localidadSeleccionada";
				eval (cadenaAEjecutar);
				var txt = "'" + loca + "'"
				eval (myObjectName + ".onDeterminedSugsMustBeHidden();");
			}
			//Esto es para el manejo de la localidad seleccionada con las teclas arrows
			if (evt.keyCode == 38) {
					eval (myObjectName + ".upSeleccion()");
			}
			if (evt.keyCode == 40) {
					eval (myObjectName + ".downSeleccion()");
			}
		}	
	}
	
	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()');
            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
					eval(myJAMAC + '.onDeterminedSugsMustBeHidden()');
				}
			}
		}
    }
	
	JAMAutoComplete.prototype.onDeterminedSugsMustBeHidden = function (evt) {
		
		var myObjectName = window.top.document.ActiveJAMAC; //era this.objectName
		eval ("var ib = " + myObjectName + ".idInputBox");
		eval ("var localidad = " + myObjectName + ".localidadSeleccionada");
		eval ("var txt = \"" + localidad + "\"");
		if (txt != 'undefined') 
		{
			eval (myObjectName + ".inputBox.value = " + myObjectName + ".localidadSeleccionada.replace(/´/ig,\"'\");");
			eval ("var txtAssigned = " + 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 (window.frameElement && window.frameElement != element) {
			var coords = getElementCoord(window.frameElement);
			curLeft = coords[0];
			curTop = coords[1];
			//alert ("Por estar en el iframe '"+window.frameElement.id +"' le añadimos "+coords[0]+"al curLeft y "+coords[1]+" al curTop");
		}
		
		var IEOffset7 = 0; //Variable para hacer ajustes manuales en IE7 e inferiores.

        if (element.offsetParent) {
            do {
				//alert ("Por estar en el elemento '"+ element.id +"' le añadimos "+element.offsetLeft+"al curLeft y "+element.offsetTop+" al curTop");
				if (element.id == "search-box") //Los elementos de este ID de Rediseño 2010 son problemáticos, los omitimos en la cuenta para IE7-
					IEOffset7 = element.offsetLeft;
                curLeft += element.offsetLeft;
                curTop += element.offsetTop;
            } while ((element = element.offsetParent))
        }
		

		//Si estamos en IE7- o en IE8 en modo compatibilidad con IE7 aplicamos el ajsute manual.
		if (curLeft >= IEOffset7 && document.all && (!document.documentMode || document.documentMode < 8) ) {
			curLeft -= IEOffset7;
		}
		
        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;
        }
    }
}

