var puntero = null;

function autocomplete(textBoxId, containerDivId){
	var ac = this;
			document.getElementById("view").style.display = 'block';	
	this.textbox = document.getElementById(textBoxId);
	this.div = document.getElementById(containerDivId);
	this.list = this.div.getElementsByTagName('li');
	puntero = null;
	
	
	for (var i = 0; i < this.list.length; i++) {
		this.list[i].numero = i;

		this.list[i].onmouseover = function(){
			ac.reset();
			this.url = document.getElementById('link'+this.numero).getAttribute('href');
			puntero = this.numero;
			this.className = 'active';
		}
		this.list[i].onclick = function(){
			window.location = document.getElementById('link'+this.numero).getAttribute('href');
		}
	}

	this.reset = function(){
		if(puntero != null) this.list[puntero].className = '';
		puntero = null;
	}	

	this.textbox.onfocus = function(){
		document.getElementById("listsugg").style.display = 'block';
	}
	
	this.textbox.onblur = function(){
		this.timer = window.setTimeout(ac.save, 250);

	}
    this.save = function(){
		document.getElementById("listsugg").style.display = 'none';
		ac.reset();	  
    }	
	
	this.textbox.onkeydown = function(e){
		e = e || window.event;
		switch (e.keyCode) {
			case 38: //up
				ac.selectDiv(-1);
				break;
			case 40: //down
				ac.selectDiv(1);
				break;
			case 13: //enter
				ac.irUrl();
				Event.stop(e);
				break;
			case 27: //esc
				ac.reset();
				document.getElementById("listsugg").style.display = 'none';
				break;		
		}
	}
	
	this.irUrl = function(){
		if (puntero != null) {
			window.location = this.list[puntero].url;
		}
		else {
			busca = document.getElementById('query').value;
			window.location = "/buscar?q="+busca;
			}

	}
	
	this.selectDiv = function(inc){
		if ((puntero + inc) < 0) {
			ac.reset();
			puntero = null;
		}
		else {
			if (puntero !== null && puntero + inc >= 0 && puntero + inc < this.list.length) {
				this.list[puntero].className = '';
				puntero += inc;
				this.list[puntero].className = 'active';
				this.list[puntero].url = document.getElementById('link' + puntero).getAttribute('href');
			}
			if (puntero === null) {
				puntero = 0;
				this.list[puntero].className = 'active';
				this.list[puntero].url = document.getElementById('link' + puntero).getAttribute('href');
			}
		}
	}

}	