function pulsacion()
{
   if (document.getElementById("buscar").value.length > 3) autocompleta(arguments[0]);
   else borraLista();
}

var peticion = null;
var elementoSeleccionado = -1;
var sugerencias = null;
var cacheSugerencias = {};

function inicializa_xhr()
{
   if (window.XMLHttpRequest) return new XMLHttpRequest();
   else if (window.ActiveXObject) return new ActiveXObject("Microsoft.XMLHTTP");
}

Array.prototype.formateaLista = function()
{
   var codigoHtml = "";
   //codigoHtml = "<ul>";
   for(var i=0; i<this.length; i++)
   {
      if (i == elementoSeleccionado) codigoHtml += "<p  class=\"seleccionado\" onclick=\"reyena("+i+");\">"+this[i]+"</p>";
      else codigoHtml += "<p onmouseover=\"muestraMouse("+i+"); return false;\" >"+this[i]+"</p>";
   }
   //codigoHtml += "</ul>";
   return codigoHtml;
};

function noenter(key)
{
   suggcont = document.getElementById("sugerencias");
   if (elementoSeleccionado != -1)
   {
      if (key.keyCode == 13)
      {
         reyena(elementoSeleccionado);
         return false;
      }
      else
      {
         return true;
      }
	  alert(key.keycode);
   }
   else
   {
      return true;
   }
}

function reyena(indice)
{
   document.getElementById("buscar").value = sugerencias[indice];
   borraLista();
}

function muestraMouse(indice)
{
   elementoSeleccionado = indice;
   muestraSugerencias();
}

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();
   }
   else
   {
      var texto = document.getElementById("buscar").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)
      {
         peticion = inicializa_xhr();
         peticion.onreadystatechange = function()
         {
            if (peticion.readyState == 4)
            {
               if (peticion.status == 200)
               {
                  if(peticion.responseText.length == 0)
                  {
                     sinResultados();
                  }
                  else
                  {
                     sugerencias = eval('('+peticion.responseText+')');
                     cacheSugerencias[texto] = sugerencias;
                     actualizaSugerencias();
                  }
               }
            }
         };
         peticion.open('POST', 'sugerencias.php?nocache='+Math.random(), true);
         peticion.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
         peticion.send('buscar='+encodeURIComponent(texto));
      }
      else
      {
         sugerencias = cacheSugerencias[texto];
         actualizaSugerencias();
      }
   }
}

function sinResultados()
{
   document.getElementById("sugerencias").innerHTML = "";
   document.getElementById("sugerencias").style.display = "none";
}

function actualizaSugerencias()
{
   elementoSeleccionado = -1;
   muestraSugerencias();
}

function seleccionaElemento()
{
   if (sugerencias[elementoSeleccionado])
   {
      document.getElementById("buscar").value = sugerencias[elementoSeleccionado];
      borraLista();
   }
}

function muestraSugerencias()
{
   var zonaSugerencias = document.getElementById("sugerencias");
   zonaSugerencias.innerHTML = sugerencias.formateaLista();
   zonaSugerencias.style.display = 'block';
}

function borraLista()
{
   document.getElementById("sugerencias").innerHTML = "";
   document.getElementById("sugerencias").style.display = "none";
   elementoSeleccionado = -1
   document.getElementById("buscar").focus();
}


window.onload = function()
 {
   var elDiv = document.createElement("div");
   elDiv.id = "sugerencias";
   document.getElementById("contenedor").appendChild(elDiv);
   
   document.getElementById("buscar").onkeypress = noenter;
   document.getElementById("buscar").onkeyup = pulsacion;
   document.getElementById("buscar").focus();
   //document.getElementById("sugerencias").onmouseout = borraLista;
}