// JavaScript Document

var IE = navigator.appName.toLowerCase().indexOf("microsoft") > -1;
var Mozilla = navigator.appName.toLowerCase().indexOf("netscape") > -1;

var textoAnt = "";
var posicionListaFilling = -1;

var datos = new Array();
var lista = new Array();
var listaAux = new Array();
var listaIds = new Array();

var cargando = false;

function cargaLista(evt, obj, txt, ele, tabla, campo) {
	var url = '../inc/ajax/autocomplete.php?texto='+txt+'&tabla='+tabla+'&campo='+campo;
	cargando = true;
	new Ajax.Request(url, {
		method: 'get',
		onComplete: function(respuesta) {

			var datos = respuesta.responseText.split(';');
			
			listaProductos = new Array();

			if(datos.length > 0 && datos[0] != ''){
				for (var i=0; i<=(datos.length - 1); i++) {
					//alert(i+"-"+datos.length);
					listaProductos[i] = datos[i];
					listaAux[i] = datos[i];
					listaIds[i] = datos[i];
				}	
			}
			//alert(listaProductos.length);
			escribeLista(obj, listaProductos, ele);
			cargando = false;
			
		}});
}

function escribeLista(obj, listaProd, ele) {
	
	var html = "";
	lista = listaProd;
	if (lista.length > 0) {
		var html='<table cellspacing="0" cellpadding="0" border="0" width="100%" id="productos_autocomplete">';
		
		for (var i=0; i<lista.length; i++) {
			if(lista[i]!=''){
				html += '<tr id="tr_'+ele+'_'+i+'"';
				html += 'onmouseover="seleccionaFilling('+i+',\''+ele+'\');"';
				if(posicionListaFilling == i){
					html += 'class="selected">';
				}
				else{
					html += 'class="list">';	
				}
				html += '<td onClick="aceptarsugerencia(\''+lista[i]+'\', \''+obj.id+'\');">'+lista[i]+'</td></tr>';
			}
		}
		
		html += '</table>';
		
		//Si ya existe una div, se actualiza el hml
		if($('lista_productos')){
			posicionar_div(obj);
			$('lista_productos').innerHTML = html;
			($('lista_productos')).style.display = "block";
		}
		//Si no existe se crea
		else{
			//alert('aca');
			var div = document.createElement("div");
			div.id = div.name = "lista_productos";
			div.style.position = "absolute";
			div.innerHTML = html;
			document.body.appendChild(div);
			
			
			arrPositions = findPos(obj);
			$('lista_productos').style.left = (arrPositions[0]-1)+"px";
			$('lista_productos').style.top =  (arrPositions[1]+24)+"px";
			
			//$('lista_productos').style.top = "155px";
			//$('lista_productos').style.left = "279px";
			$('lista_productos').style.width = "235px";
		    $('lista_productos').className = "autocomplete_block";
		}
	}
	else{
		if($('lista_productos')){
			($('lista_productos')).style.display = "none";
		}
	}
}

function aceptarsugerencia(valor, obj){
    var campo = $(obj);
    campo.value = valor;
	if($('lista_productos')){
		($('lista_productos')).style.display = "none";
	}
}

// Muestra las coincidencias en la lista evt, obj, ele
function inputFilling(evt,obj,ele, tabla, campo) {
	
	var fill = document.getElementById('lista_'+ele);
	
	var elems = datos;
	
	var tecla = "";
	
	var res = obj.value;
	var borrar = false;
	
	// Almaceno la tecla pulsada
	if (!IE) {
	  tecla = evt.which;
	} else {
	  tecla = evt.keyCode;
	}
	
	var texto = "";
	// Si la tecla que pulso es una letra, un espacio, el intro o la tecla borrar, almaceno lo que debo buscar
	if ((!String.fromCharCode(tecla).match(/(\w|\s)/)) && (tecla != 13) && (tecla != 8) ) {
		texto = textoAnt;
	} else {
		texto = obj.value;
	}
	
	
	textoAnt = texto;
	// Seg�n la letra que se pulse
	/*if(tecla==38){ //Arriba
		
		//Subir la posicion en la lista desplegable
		if(posicionListaFilling>0){
			posicionListaFilling--;
			seleccionaFilling(posicionListaFilling,ele);
		}
		
		//se corrije la posicion del scroll
		//fill.scrollTop = posicionListaFilling*14;
		seleccionaTextoFilling(posicionListaFilling,ele);
		//seleccionarTexto(ele);
	}
	else if(tecla==40){ //Abajo
	
		// Bajar la posici�n en la lista desplegable
		if(lista.length>0){
			if(posicionListaFilling < lista.length-2){
				posicionListaFilling++;
				seleccionaFilling(posicionListaFilling,ele);
			}
			//fill.srollTop = posicionListaFilling*14;
			seleccionaTextoFilling(posicionListaFilling,ele);
			//seleccionarTexto(ele);
		}
	}
	
	else{*/
		if ((texto != null) && (tecla != 37 && tecla != 39 )){
			if(!cargando) cargaLista(evt, obj, texto, ele, tabla, campo);
		}
		else if((texto==null) && $('lista_productos')){
			fill.style.display = "none";
		}
		posicionListaFilling = -1;
	//}
	
	return true;
}

// Introduce el texto seleccionado
function setInput(obj, fill) {
	obj.value = textoAnt;
	var hidden = $('input_prod');
	hidden.value = textoAnt;
	fill.style.display = "none";
}


// Cambia el estilo de la palabra seleccionada de la lista
function seleccionaFilling(pos, ele) {
	var id = 'tr_'+ele+'_'+pos;
	var tabla = document.getElementById('productos_autocomplete');
	var listaTR = document.getElementsByTagName('tr');
	
	for(var x=0; x<listaTR.length; x++){

		if(listaTR[x].id == id){
			listaTR[x].className = "selected";
		}
		else{
			listaTR[x].className = "list";
		}
	}
	
	posicionListaFilling = pos;
}

//Posicionar la div
function posicionar_div(obj){
	
	/*var ancho = getWindowWidth();
	var izquierda = (ancho/2)-342;
	var pix = izquierda+"px";
	$('lista_productos').style.left = pix;*/
	//var div_prod = $('div_prod');
	arrPositions = findPos(obj);
	$('lista_productos').style.left = (arrPositions[0]-1)+"px";
	$('lista_productos').style.top =  (arrPositions[1]+24)+"px";
}

// Find the position of the banner to set the floating expandible
function findPos(obj) 
{
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft;
		curtop = obj.offsetTop;
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		}
	}
	return [curleft,curtop];
}


// Pasa el texto de la lista al input
function seleccionaTextoFilling(pos,ele) {
	var input = $('input_'+ele);
	var hidden = $('input_prod');
	
	textoAnt = document.getElementById('tr_'+ele+'_'+pos).firstChild.innerHTML;
	//textoAnt = textoAnt.replace("</TD>","");
	
	input.value = textoAnt;
	hidden.value = listaAux[pos];
	//posicionListaFilling = 0;
}