function asignaVariables()
{
	// Funcion que asigna variables que se usan a lo largo de las funciones	
	v=1; nuevaBusqueda=1; busqueda=null; ultimaBusquedaNula=null;
	divLista=document.getElementById("lista");
	inputLista=document.getElementById("phrase");
	elementoSeleccionado=0;
	ultimoIdentificador=0;
	banderitamia = 0;
	timet=document.getElementById("t");
	
}

function acentos(Text)
{
var cadena="";
var codigo="";
for (var j = 0; j < Text.length; j++)
{
var Char=Text.charCodeAt(j);
switch(Char)
{
case 225:
cadena+="a";
break;
case 233:
cadena+="e";
break;
case 237:
cadena+="i";
break;
case 243:
cadena+="o";
break;
case 250:
cadena+="u";
break;
case 193:
cadena+="A";
break;
case 201:
cadena+="E";
break;
case 205:
cadena+="I";
break;
case 211:
cadena+="O";
break;
case 218:
cadena+="U";
break;
case 241:
cadena+="N";
break;
case 209:
cadena+="n";
break;
default:
cadena+=Text.charAt(j);
break;
}
codigo+="_"+Text.charCodeAt(j);
}
return cadena;
}

function nuevoAjax()
{ 
	/* Crea el objeto AJAX. Esta funcion es generica para cualquier utilidad de este tipo, por
	lo que se puede copiar tal como esta aqui */
	var xmlhttp=false; 
	try 
	{ 
		// Creacion del objeto AJAX para navegadores no IE
		xmlhttp=new ActiveXObject("Msxml2.XMLHTTP"); 
	}
	catch(e)
	{ 
		try
		{ 
			// Creacion del objet AJAX para IE 
			xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
		} 
		catch(E) { xmlhttp=false; }
	}
	if (!xmlhttp && typeof XMLHttpRequest!="undefined") { xmlhttp=new XMLHttpRequest(); } 

	return xmlhttp; 
}

function eliminaEspacios(cadena)
{
	var x=0, y=cadena.length-1;
	while(cadena.charAt(x)==" ") x++;	
	while(cadena.charAt(y)==" ") y--;	
	return cadena.substr(x, y-x+1);
}


function formateaLista(valor)
{
	// Funcion encargada de ir colocando en negrita las palabras y asignarle un ID a los elementos
	var x=0, verificaExpresion=new RegExp("^("+valor+")", "i");
	
	while(divLista.childNodes[x]!=null)
	{
		// Asigo el ID para reconocerlo cuando se navega con el teclado
		divLista.childNodes[x].id=x+1;
		// Coloco en cada elemento de la lista en negrita lo que se haya ingresado en el input
		divLista.childNodes[x].innerHTML=divLista.childNodes[x].innerHTML.replace(verificaExpresion, "<b>$1</b>");
		x++;
	}
}

function limpiaPalabra(palabra)
{
	// Funcion encargada de sacarle el codigo HTML de la negrita a las palabras
	var navegador = navigator.appName
	if (navegador == "Microsoft Internet Explorer"){
	
		palabra=palabra.replace(/<b>/i, "");
		palabra=palabra.replace(/<\/b>/i, "");
		palabra=palabra.replace(/\<div id=consultas\>[0-9]* Consultas/gi, "");
		palabra=palabra.replace(/<\/div>/i, "");
	}else{
		palabra=palabra.replace(/<b>/i, "");
	    palabra=palabra.replace(/<\/b>/i, "");
		palabra=palabra.replace(/\<div id="consultas"\>[0-9]* Consultas/gi, "");
		palabra=palabra.replace(/<\/div>/i, "");
		
	}
	
	
	return palabra;
}

function coincideBusqueda(palabraEntera, primerasLetras)
{
	/* Funcion para verificar que las primeras letras de busquedaActual sean iguales al
	contenido de busquedaAnterior. Se devuelve 1 si la verificacion es afirmativa */
	if(primerasLetras==null) return 0;
	var verificaExpresion=new RegExp("^("+primerasLetras+")", "i");
	if(verificaExpresion.test(palabraEntera)) return 1;
	else return 0;
}

function nuevaCadenaNula(valor)
{
	/* Seteo cual fue la ultima busqueda que no arrojo resultados siempre y cuando la cadena
	nueva no comience con las letras de la ultima cadena que no arrojo resultados */
	if(coincideBusqueda(valor, ultimaBusquedaNula)==0) ultimaBusquedaNula=valor;
}

function busquedaEnBD()
{
	/* Funcion encargada de verificar si hay que buscar el nuevo valor ingresado en la base
	de datos en funcion de los resultados obtenidos en la ultima busqueda y en base a que
	la cadena bsucada anteriormente este dentro de la nueva cadena */
	var valor=inputLista.value;
	
	if((coincideBusqueda(valor, busqueda)==1 && nuevaBusqueda==0) || coincideBusqueda(valor, ultimaBusquedaNula)==1) return 0;
	else return 1;
}

function filtraLista(valor)
{
	// Funcion encargada de modificar la lista de nombres en base a la nueva busqueda
	var x=0;

	while(divLista.childNodes[x]!=null)
	{
		// Saco la negrita a los elementos del listado
		divLista.childNodes[x].innerHTML=limpiaPalabra(divLista.childNodes[x].innerHTML);
		if(coincideBusqueda(limpiaPalabra(divLista.childNodes[x].innerHTML), valor)==0)
		{
			/* Si remuevo el elemento x, el elemento posterior pasa a ocupar la posicion de
			x, entonces quedaria sin revisar. Por eso disminuyo 1 valor a x */
			divLista.removeChild(divLista.childNodes[x]);
			x--;
		}
		
		x++;
	}
}

function reiniciaSeleccion()
{
	mouseFuera(); 
	elementoSeleccionado=0;
}

function navegaTeclado(evento)
{
	var teclaPresionada=(document.all) ? evento.keyCode : evento.which;
	
	switch(teclaPresionada)
	{
		
		case 27:
			document.getElementById('lista').style.display = "none";
			var div = document.getElementById("lista");
			while(div.firstChild){
				div.removeChild(div.firstChild);
			}
			return 0;
		case 40:
		if(elementoSeleccionado<divLista.childNodes.length)
		{
			mouseDentro(document.getElementById(parseInt(elementoSeleccionado)+1));
			
		}
		return 0;
		
		case 38:
		if(elementoSeleccionado>1)
		{
			mouseDentro(document.getElementById(parseInt(elementoSeleccionado)-1));
		}
		return 0;
		
		case 13:
		
		if(divLista.style.display=="block" && elementoSeleccionado!=0 && banderitamia==0)
		{	
			
			clickLista(document.getElementById(elementoSeleccionado));
			
		}else{
			 
				if(banderitamia==1){
					
					var opc=0;
					if(document.getElementById("phrase").value==""|| document.getElementById("phrase").value=="<Escribe la actividad: Comprar Una Casa>" || document.getElementById("phrase").value==" " || document.getElementById("phrase").value==0){
						
						alert("Debe colocar informacion en la frase a buscar.");
						
					}else{
						  opc++;
					} 
					if(document.getElementById("as-values-timezone").value=="" || document.getElementById("as-values-timezone").value==" " || document.getElementById("as-values-timezone").value==0 || document.getElementById("as-values-timezone").value=="Ingrese la Ciudad"  ){
										alert("Debe escoger una zona horaria.");
										
					}else{
						opc++;
					}
					if(opc==2){
								String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ""); };
							banderitamia=0;
							valor = inputLista.value;
							valor = valor.trim();
							var timezone = limpiatime(document.getElementById("as-values-timezone").value);
							elem = document.getElementsByName('action');
							var action = action(elem);
							var edit1 = document.getElementById("edit1").value;
							var time2;
							var hora = document.getElementById("hourcombo").options[document.getElementById("hourcombo").selectedIndex].value;
							var minuto= document.getElementById("mincombo").options[document.getElementById("mincombo").selectedIndex].value;
							time2 = hora+":"+minuto;
							divLista.style.display="none";
							location.href = location.href
							location.href="search.php?phrase="+valor+"&action="+action+"&timezone_string="+timezone+"&edit1="+edit1+"&time2="+time2;
							document.get
					}
				}
				
		}
		return 0;
		
		
		default: return 1;
	}
}
function limpiatime(palabra){
	var navegador = navigator.appName
	if (navegador == "Microsoft Internet Explorer"){
	
		palabra=palabra.replace(/<b>/i, "");
		palabra=palabra.replace(/<\/b>/i, "");
		
	}else{
		palabra=palabra.replace(/<b>/i, "");
	    palabra=palabra.replace(/<\/b>/i, "");
				
	}
	
	
	return palabra;
	}
function validatecla(evento){
	var teclaPresionada=(document.all) ? evento.keyCode : evento.which;
	
	switch(teclaPresionada)
	{
		case 13:
			return 1;
	
		
	
	default: return 0;
		
	}
}
function action(elem){
	for(i=0;i<elem.length;i++)
							if (elem[i].checked) {
								action = elem[i].value;
								
								return action;
							}
}
function pasarfoco(){
	document.getElementById("phrase").focus();
}
function enviabusqueda(){
	var opc=0;
	if(document.getElementById("phrase").value==""|| document.getElementById("phrase").value=="<Escribe la actividad: Comprar Una Casa>" || document.getElementById("phrase").value==" " || document.getElementById("phrase").value==0){
		
		alert("Debe colocar informacion en la frase a buscar.");
		
	}else{
		  opc++;
		} 
	if(document.getElementById("as-values-timezone").value=="" || document.getElementById("as-values-timezone").value==" " || document.getElementById("as-values-timezone").value==0 || document.getElementById("as-values-timezone").value=="Ingrese la Ciudad"){
						alert("Debe escoger una zona horaria.");
						
	}else{
		opc++;
		
	}
	if(opc==2){
					String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ""); };
					valor = inputLista.value;
					valor = valor.trim();
					var timezone = limpiatime(document.getElementById("timezone").value);
					elem = document.getElementsByName("action");
					var action1 = action(elem);
					var edit1 = document.getElementById("edit1").value;
					var time2;
					var hora = document.getElementById("hourcombo").options[document.getElementById("hourcombo").selectedIndex].value;
					var minuto= document.getElementById("mincombo").options[document.getElementById("mincombo").selectedIndex].value;
					time2 = hora+":"+minuto;
					location.href = location.href;
					location.href="search.php?phrase="+valor+"&action="+action1+"&timezone_string="+timezone+"&edit1="+edit1+"&time2="+time2;				
	}
}

function rellenaLista()
{
	var valor=inputLista.value;
	
	// Valido con una expresion regular el contenido de lo que el usuario ingresa
	var reg=/(^[a-zA-Z0-9.@ ]{2,100}$)/;
	if(!reg.test(valor)) divLista.style.display="none";
	else
	{
		
			var ajax=nuevoAjax();
			ajax.open("POST", "metodos/ac_proceso.php?", true);
			ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			ajax.send("busqueda="+valor);
		
			ajax.onreadystatechange=function()
			{	
				if (ajax.readyState==4)
				{
					if(!ajax.responseText) { divLista.style.display="none"; }
					else 
					{
						var respuesta=new Array(2);
						respuesta=ajax.responseText.split("&");
				
						/* Obtengo un valor que representa si tengo que ir a BD en las proximas 
						busquedas con cadena similar */
						nuevaBusqueda=respuesta[0];
				
						// Si se obtuvieron datos los muestro
						if(respuesta[1]!="") 
						{ 
							divLista.style.display="block"; 
							divLista.innerHTML=respuesta[1]; 
							// Coloco en negrita las palabras
							reiniciaSeleccion();
							formateaLista(valor); 
						}
						 // En caso contrario seteo la busqueda actual como una busqueda sin resultados
						else
						{ 
							divLista.style.display="none"; 
							nuevaCadenaNula(valor);
						}
					}
				}
			}
		}
	}

function clickLista(elemento){
   var cible = document.getElementById("phrase");
      var posc = 0;
	 
	  cadena = cible.value;
	  var arreglo = new Array();
	  arreglo = cadena.split("");
	  
      for (var i=cible.value.length-1; i>=0; i--)   {
         var caracter = arreglo[i];
         if (caracter==" "){
            posc = i+1;
            break;
         }
      }
	  valor=limpiaPalabra(elemento.innerHTML);
	  valor=eliminaEspacios(valor);
	  valor=acentos(valor);
	  document.getElementById('phrase').focus();
   	  document.getElementById('phrase').value = document.getElementById("phrase").value.substr(0,posc)+""+valor+" ";
      banderitamia = 1;
	  divLista.style.display = "none";
	var div = document.getElementById("lista");
	while(div.firstChild){
		div.removeChild(div.firstChild);
	}
	
   
}

function mouseFuera()
{
	
	// Des-selecciono el elemento actualmente seleccionado, si es que hay alguno	
	if(elementoSeleccionado!=0 && document.getElementById(elementoSeleccionado)) {
		document.getElementById(elementoSeleccionado).className="normal";
			
	}
	
}
function mouseDentro(elemento)
{
	banderitamia = 0;
	mouseFuera();
	elemento.className="resaltado";
	// Establezco el nuevo elemento seleccionado
	elementoSeleccionado=elemento.id;
	//move_up(elemento);
}
var color = 0;
	var suma = 10;
function aparecer(){
var obj = document.getElementById("escondido");
obj.style.display = "block";
color += suma;
if (!(color>=110)){
obj.style.filter = 'alpha(opacity='+color+')';
			 obj.style.opacity = color /100;
			 obj.style.MozOpacity = color /100;
			 obj.style.KHTMLOpacity = color /100;
		window.setTimeout("aparecer();", 100);
}
}
function verificaNavegador(){
	
IE='\v'=='v';
		if(IE){
				var navVer=/*@cc_on function(){ 
										switch(@_jscript_version){ 
											case 1.0:return 3; 
											case 3.0:return 4; 
											case 5.0:return 5; 
											case 5.1:return 5; 
											case 5.5:return 5; 
											case 5.6:return 5; 
											case 5.7:return 7; 
											case 5.8:return 8; }}()||@*/0;
				if(/MSIE 6.0/i.test(navigator.userAgent)) {navVer=6;}
					if(navVer<=6){
						alert("Estas usando Internet Explorer "+navVer+" , La pagina puede no funcionar correctamente");
						//document.getElementById("escondido").innerHTML="Estas usando Internet Explorer "+navVer+" , La pagina puede no funcionar correctamente";
						aparecer();
						
				
					}
		}
FF2=(function x(){})[-6]=='x';
		if(FF2){
			alert("Estas usando Mozilla Firefox 2 o Menor, La pagina puede no funcionar correctamente");
				//document.getElementById("escondido").innerHTML="Estas usando Mozilla Firefox 2 o Menor, La pagina puede no funcionar correctamente";
				aparecer();
		}	
		
}
function eliminaChilds(){
	var div = document.getElementById("lista");
	while(div.firstChild){
		div.removeChild(div.firstChild);
	}
}
