function AUTOCompletarCallback(ev,auto,value){
	this.callback = function(event){auto(value,event)};
}
/*function AutoCompletarCallback2(ob){
	this.callback = function(param){actualizarTabla(ob,param)};
}*/
function AUTOCompletar(input,input2,url,params,calltome,div,cursor,procesando){
	this.input = input;
	this.input2 = input2;
	this.div = div;
	this.url = url;
	var timeout = null;
	AUTOCompletar.prototype.init = function(){
		cursor = 0;
		var escribir = new AUTOCompletarCallback(null,this.escribir,div);
		var perderFoco = new AUTOCompletarCallback(null,this.perderFoco,div);
		var ganarFoco = new AUTOCompletarCallback(null,this.ganarFoco,div);
		addEvent(input,'onkeydown',escribir.callback);
		addEvent(input,'onblur',perderFoco.callback);
		addEvent(input,'onfocus',ganarFoco.callback);
		procesando =0;
		//alert('vamos!');
	};
	this.interval = null
	this.escribir = function(value,e){
		var code;
		if (!e) var e = window.event;
		if (e.keyCode) code = e.keyCode;
		else if (e.which) code = e.which;
		
		if (code == 38 && div != null){//arriba
			var old = cursor;
			if (cursor>0)
				cursor--;
			//cambiarAutocompletar(div.firstChild,old,cursor);
		}else if (code == 40 && div != null){//abajo
			var old = cursor;
			if (cursor<div.firstChild.rows.length-1)
				cursor++;
			//cambiarAutocompletar(div.firstChild,old,cursor);
		}
		else if (code == 13 && div != null){//enter
			try{
				input.value = div.firstChild.rows[cursor].cells[0].getElementsByTagName('label')[0].innerHTML;
				if (input2 != null){
					input2.value = div.firstChild.rows[cursor].cells[0].getElementsByTagName('input')[0].value;
				}
			}catch(e){
				if (input == null)
					input.value = 'input es null';
			}
			cursor = 0;
			//div.style.visibility = 'hidden';
		}else if (code == 27 || code == 9){//enter
			
		}
		else{
			var v = function(){
			var urlt = url+'?';
			if (params != null){
				urlt+=params+'&';
			}
			var a = new Ajax();
			var obj = new Object();
			obj[input.name] = input.value;
			a.url = urlt+getParams(obj);
			
			var actualizar = function(response){
				agregarItemsAutocompletar(div,response);
				calltome();
				procesando = 0;
				var old = cursor;
				cursor = 0;
				//cambiarAutocompletar(div.firstChild,old,cursor);
			}
			a.callback = actualizar;
			var sended = sendAjax(a);
		}
		if (timeout != null)
			clearTimeout(timeout);
		
		if (input2 != null){
			input2.value = '';
		}
		if (procesando == 0)
			procesando = 1;
			timeout = setTimeout(v,400);
		}
		
	};
	this.ganarFoco = function(){
		//div = document.createElement('DIV');
		var t = document.createElement('table');
		div.appendChild(t);
		div.style.zIndex = '1000';
		//div.className = 'Autocomplete';
	}
	this.perderFoco = function(value){
		if (div != null){
		}
		
	};
	
	
}

function AUTOCompletarSelect(input,input2,url,params,calltome,div,cursor,parametro_dinamico){
	this.input = input;
	this.input2 = input2;
	this.div = div;
	this.url = url;
	var timeout = null;
	AUTOCompletarSelect.prototype.init = function(){
		cursor = 0;
		var escribir = new AUTOCompletarCallback(null,this.escribir,div);
		var perderFoco = new AUTOCompletarCallback(null,this.perderFoco,div);
		var ganarFoco = new AUTOCompletarCallback(null,this.ganarFoco,div);
		addEvent(input,'onkeydown',escribir.callback);
		addEvent(input,'onblur',perderFoco.callback);
		addEvent(input,'onfocus',ganarFoco.callback);
		//alert('vamos!');
	};
	this.interval = null
	this.escribir = function(value,e){
		var code;
		if (!e) var e = window.event;
		if (e.keyCode) code = e.keyCode;
		else if (e.which) code = e.which;
		
		if (code == 38 && div != null){//arriba
			var old = cursor;
			if (cursor>0)
				cursor--;
			cambiarAutocompletarSelect(div.firstChild,old,cursor);
		}else if (code == 40 && div != null){//abajo
			var old = cursor;
			if (cursor<div.firstChild.rows.length-1)
				cursor++;
			cambiarAutocompletarSelect(div.firstChild,old,cursor);
		}
		else if (code == 13 && div != null){//enter
			try{
				input.value = div.firstChild.rows[cursor].cells[0].getElementsByTagName('label')[0].innerHTML;
				if (input2 != null){
					input2.value = div.firstChild.rows[cursor].cells[0].getElementsByTagName('input')[0].value;
				}
			}catch(e){
				if (input == null)
					input.value = 'input es null';
			}
			cursor = 0;
			div.style.visibility = 'hidden';
		}else if (code == 27 || code == 9){//enter
			
		}
		else{
			var v = function(){
			var urlt = url+'?';
			if (params != null){
				urlt+=params+'&';
			}
			if(parametro_dinamico != null){
				urlt+=obtenerParametroDinamico(parametro_dinamico)+'&';
			}
			var a = new Ajax();
			var obj = new Object();
			obj[input.name] = input.value;
			a.url = urlt+getParams(obj);
			var actualizar = function(response){
				agregarItemsAutocompletar(div,response);
				var old = cursor;
				cursor = 0;
				cambiarAutocompletar(div.firstChild,old,cursor);
			}
			a.callback = actualizar;
			var sended = sendAjax(a);
		}
		if (timeout != null)
			clearTimeout(timeout);
		
		if (input2 != null){
			input2.value = '';
		}
		timeout = setTimeout(v,200);	
		
		}
		
	};
	this.ganarFoco = function(){
		
		div = document.createElement('DIV');
		document.getElementsByTagName('BODY')[0].appendChild(div);
		div.className = 'Autocomplete';
		//div.style.backgroundColor = 'cyan';
		var t = document.createElement('table');
		
		div.style.top = getY(input)+input.offsetHeight+'px';
		div.style.left = getX(input)+'px';
		div.style.width = input.offsetWidth-2+'px';
		
		//div.style.height = '200px';
		//div.style.visibility = 'visible';
		div.style.zIndex = '1000';
		div.appendChild(t);
		//
		
		
		
	}
	this.perderFoco = function(value){
		if (div != null){
			document.getElementsByTagName('BODY')[0].removeChild(div);
		}
		
	};
	
	
}

function obtenerParametroDinamico(divObj){
	return divObj.name + "=" + divObj.value;
}

function cambiarAutocompletarSelect(table,old,current){

	if (table.rows.length > 0){
	table.rows[old].className = ''
	table.rows[current].className = 'divAutocompleteSelected'
	}
	
}


function cambiarAutocompletar(table,old,current){
/*
	if (table.rows.length > 0){
	table.rows[old].className = ''
	table.rows[current].className = 'divAutocompleteSelected'
	}
*/	
}
function agregarItemsAutocompletar(div,response){
	var items = null;
	var cantidad = parseInt(response.cantidad);
	div.removeChild(div.firstChild);
	var childs = div.childNodes;
	var i=0;
	
	for (i=0;i<childs.length; i++){
		div.removeChild(childs[i]);	
	}
	
	var t = document.createElement('table');
	div.appendChild(t);
	
	if (cantidad == 0){
		return;
	}

	if (div.style.visibility != 'visible'){
		div.style.visibility = 'visible';
	}

	if(cantidad == 1){
		items = new Array();
		items[0] = response.sugeridos.item;
	}else{
		items = response.sugeridos.item;
	}

	
	for (i=0;i<items.length;i++){
		var r = t.insertRow(r);
		var c = r.insertCell(0);
		var c2 = r.insertCell(1);
		c.appendChild(createInputHidden(items[i].id));
		c.appendChild(createLabel(items[i].descripcion));
		
		if (items[i].imagen != ''){
			var img = createImage(items[i].imagen);	
			img.style.height = '20px';
			img.style.width = 'auto';
			c2.appendChild(img)
		}else{
		
		}
	}
	
}


function getY( oElement )
	{
		var iReturnValue = 0;
		while( oElement != null ) {
			iReturnValue += oElement.offsetTop;
			oElement = oElement.offsetParent;
		}
		return iReturnValue;
	}
	function getX( oElement )
	{
		var iReturnValue = 0;
		while( oElement != null ) {
			iReturnValue += oElement.offsetLeft;
			oElement = oElement.offsetParent;
		}
		return iReturnValue;
	}

//tablas
function addRow(tableId,index,array){
	try{
	var i=0;
	var row = document.getElementById(tableId).insertRow(index);
	if (index%2 == 1){
		row.className = 'fila_impar';
	}
	for (i=0;i<array.length;i++){
		var cell = row.insertCell(i);
		cell.innerHTML = array[i];
	}
	}catch(e){
		alert('error al agregar fila '+e);
	}
}
function cleanTable(tableId,from,to){

	try{
		var table =  document.getElementById(tableId);
		if (to==null)
			to = table.rows.length-1;
		var i=0;
		for(i=to; i>=from;i--){
			table.deleteRow(i);
		}
	}catch(e){
		alert('Error al Limpiar la Tabla '+e.message);
	}
}
function addElement(tableId,row,col,element){
	var table =  document.getElementById(tableId);
	var td = table.rows[row].cells[col];
	td.appendChild(element);
}
//eventos
function addEventOld(element,eventName,handler){
	alert(eventName);
	if (window.ActiveXObject){ //ie
		element.attachEvent(eventName, handler);
	}
	else{
		element.setAttribute(eventName, handler);
	}
}
function addEvent(element,eventName,handler,param){
	if (window.ActiveXObject){ //ie
		element.attachEvent(eventName,handler);
	}
	else{
		element[eventName] = handler;
	}
	if (eventName == 'onclick' || eventName == 'ondblclick'){
	
		addEvent(element,'onmouseover', function(){document.body.style.cursor='pointer';});
		addEvent(element,'onmouseout', function(){document.body.style.cursor='default';});
	}
}
//paginacion
function SFPaginacionCallbak(callback,nueva,paginaActual,sf){
	this.callback = function callback2(){paginacionCambiarPagina(callback,nueva,paginaActual,sf)};
}
function SolofutbolPaginacion(id,callback,paginas,paginaActual,resultado,resultadoPorPagina){
	this.table = document.getElementById(id);
	this.callback = callback;
	this.paginas = paginas;
	this.paginaActual = null;
	this.paginaAnterior = null;
	this.resultado = resultado;
	this.resultadoPorPagina = resultadoPorPagina;
	
	this.print = function (param){
		try{
		var table =  this.table;
		table.className = 'paginacion';
		if (this.paginaActual == null){
			this.paginaActual = 1;
		}
		
		cleanTable(table.id,0,table.rows.length-1);
		var row = table.insertRow(0);
		var i=0;
		var cell = row.insertCell(i);
		var label = createLabel('<<');
		cell.appendChild(label);
		var callb = new SFPaginacionCallbak(this.callback,'ANTERIOR',this.paginaActual,this)
		addEvent(label,'onclick',callb.callback);
		
		for (i=1;i<=paginas;i++){
			cell = row.insertCell(i);
			label = createLabel(i);
			cell.appendChild(label);
			if (i==this.paginaActual){
				cell.style.fontWeight='bold';
				cell.style.textDecoration='underline';
			}
			var callb = new SFPaginacionCallbak(this.callback,i,this.paginaActual,this)
			addEvent(label,'onclick',callb.callback);
		}
		cell = row.insertCell(i);
		label = createLabel('>>');
		var callb = new SFPaginacionCallbak(this.callback,'SIGUIENTE',this.paginaActual,this)
		addEvent(cell,'onclick',callb.callback);
		cell.appendChild(label);
		row = table.insertRow(1);
		cell = row.insertCell(0);
		cell.colSpan = paginas+2;
		label = createLabel('Resultados de Busqueda:'+this.resultado);
		cell.appendChild(label);
		}catch(e){
			alert('Error de Paginacion = '+e.message);
		}
	}
	this.elegirPagina = function (param){
		alert('puta!'+param);
	}
}
function paginacionCambiarPagina(callback,nueva,actual,sf){
	var to = nueva;
	if (nueva == 'ANTERIOR'){
		to=actual;
		if (actual>1)
			to--;
	}
	if (nueva == 'SIGUIENTE'){
		to=actual;
		if (actual-2<sf.paginas)
			to++;
	}
	sf.paginaActual = to;
	sf.print();
	callback(to);
}

//create elements
function createImage(url){
	var img = document.createElement('img');
	img.src = url;
	return img;
}
function createLabel(text){
	var label = document.createElement('label');
	label.innerHTML = text;
	return label;
}
function createLink(text){
	var label = document.createElement('a');
	label.href = '#';
	label.innerHTML = text;
	return label;
}
function createInputHidden(text){
	var input = document.createElement('input');
	input.type = 'hidden'
	input.value = text;
	return input;
}

var id = 0;

function getParams(obj){
	var params = "";
	var first = true;
	var property = null;
	for (property in obj)
	{
		if (!first){
			params+='&';
		}else{
			first = false;
		}
		params+= property + '=' + escape(obj[property]);
	}
	return params;
}

function agregarAlumno(){
	var a = new Ajax();
	a.url = 'cualquiera.uxml';
	a.callback = agregar;
	a.id = 108;
	sendAjax(a);
	
}
function agregar(obj){
	var array = new Array();
	array[0] = obj.alumno.nombre;
	array[1] = obj.alumno.apellido;
	alert(array[0]);
	alert(array[1]);
}


function prueba(){
	alert('sendAjax');
	
}
function myCallback(obj,ajax){
	alert(obj.opcion);
   	alert(obj.mensaje.mensaje1.mensaje2);
   	alert(obj.response);
   	alert(ajax.id);
}

//AJAX
function Ajax(){
	this.request = null;
	this.id = null;
	this.url = null;	
	this.callback = null;
	this.change = null;
	this.xmlhttp = null;
}

var xmlhttp = null;
function sendAjax(ajax){
	// code for Mozilla, etc.
	document.getElementById('status').style.display='';
	if (xmlhttp != null){
		return false;
	}
	var browser = '';
	if (window.XMLHttpRequest)
  	{
		browser = 'NEW_BROWSER';	
		xmlhttp=new XMLHttpRequest()
	}
	// code for IE
	else if (window.ActiveXObject)
  	{
	  browser = 'OLD_BROWSER';	
	  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
  	}
	ajax.request = xmlhttp;	
	if(browser == 'NEW_BROWSER'){
		xmlhttp.ajax = ajax;
		return loadXMLDoc(ajax.url,xmlhttp);
	}else if(browser == 'OLD_BROWSER'){
		return loadXMLDocOldBrowser(ajax);
	}
}

var callbackOldBrowser = null;
function loadXMLDocOldBrowser(ajax){
	var xmlhttp = ajax.request;
	callbackOldBrowser = ajax.callback;
	if (xmlhttp!=null){
		  xmlhttp.onreadystatechange=state_Change_OldBrowser;
		  xmlhttp.open("POST",ajax.url,true)
		  xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=ISO-8859-15');
 		  xmlhttp.send(null); 		  
 		  return true;
	 }else{
		  alert("Your browser does not support XMLHTTP.")
	  }	
}

function state_Change_OldBrowser(){
	if (xmlhttp.readyState==4){
		if (xmlhttp.status==200){
			try{
				var xmlDoc = xmlhttp.responseXML;
				var values = xmlDoc.getElementsByTagName("root");
				var obj = new Object();

	   		obj = load(values[0]);		   		
   			callbackOldBrowser(obj);
	   		document.getElementById('status').style.display='none';
   			xmlhttp = null;
   			callbackOldBrowser = null;
   		}catch(e){
   				alert('error de Callback '+e.message);
   				xmlhttp = null;
   		}
  				
	   }else{
    }	
  }
}


function sendAjaxNext(ajax) {
try {
  xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
 } catch (e) {
  try {
   xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  } catch (E) {
   xmlhttp = false;
  }
 }
if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
  xmlhttp = new XMLHttpRequest();
}
	ajax.request = xmlhttp;
	xmlhttp.ajax = ajax;
	return loadXMLDoc(ajax.url,xmlhttp);
}
function loadXMLDoc(url,xmlhttp)
{
	if (xmlhttp!=null)
  	{
		  xmlhttp.onreadystatechange=state_Change
		  xmlhttp.open("POST",url,true)
		  xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=ISO-8859-15');
 		  xmlhttp.send(null);
 		  return true;
	 }
	  else
  		{
		  alert("Your browser does not support XMLHTTP.")
	  }
	  return false;
}
function state_Change(){
		if (xmlhttp.readyState==4)
		  {
			  if (xmlhttp.status==200)
			    {
			   // alert(xmlhttp.responseText);
				try{
					var xmlDoc = xmlhttp.responseXML;
					var values = xmlDoc.getElementsByTagName("root");
					var obj = new Object();
					var ajax = xmlhttp.ajax;
			   		obj = load(values[0]);
	   				ajax.callback(obj);
	   				document.getElementById('status').style.display='none';
	   				xmlhttp = null;
	   			}catch(e){
	   				alert('error de Callback '+e.message);
	   				xmlhttp = null;
	   			}
   				
   		    }
		  else
		    {
	
		    }	
	  }
	}
var j =0;
function load(node){
	if (node == null){
		return null;
	}
	if (node.firstChild != null && node.firstChild.nodeType == 3){
		return node.firstChild.nodeValue;
	}
	if (node.firstChild == null){
		return '';
	}
	var obj = new Object();
	if (node.nodeType == 1){
		if (node.childNodes!=null){
			var i=0;
			for (i=0; i<node.childNodes.length;i++){
				var child = node.childNodes[i];
				if (getChildsByTagName(node,child.nodeName).length > 1){
					var array = obj[child.nodeName];
					if (array  == null){
						array = new Array();
						obj[child.nodeName] = array;
					}
					array[array.length] = load(child);
				}
				else{
						obj[child.nodeName] = load(child); 
				}
			}
		}
	}
	return obj;
}
function getChildsByTagName(node,name){
	var array = new Array();
	var i=0;
	var j=0;
	for (i=0; i<node.childNodes.length;i++){
		var child = node.childNodes[i];
		if (child.nodeName == name){
			array[j++] = child;
		}
	}
	return array;
}
function cleanForm(nodo){
	if (nodo==null){
		alert('error al limpiar nodo null');
	}
	if (nodo.type == 'text' || nodo.type == 'hidden'){
		nodo.value = '';
	}
	if (nodo.childNodes != null){
		var i;
		for (i=0; i<nodo.childNodes.length;i++){
			cleanForm(nodo.childNodes[i]);
		}
	}
}
function fillForm(nodo,obj){
	if (nodo.type == 'text' || nodo.type == 'hidden'){
		nodo.value = getProperty(obj,nodo.name);
	}
	if (nodo.childNodes != null){
		var i;
		for (i=0; i<nodo.childNodes.length;i++){
			fillForm(nodo.childNodes[i],obj);
		}
	}
}
function findFieldByName(nodo,fieldName){
	if (nodo.type == 'text' || nodo.type == 'hidden' || nodo.type == 'password'){
		if (nodo.name == fieldName){
			return nodo;
		}
	}
	if (nodo.nodeName == 'SELECT'){
		return nodo;
	}
	var o = null;
	if (nodo.childNodes != null){
		var i;
		for (i=0; i<nodo.childNodes.length;i++){
			o = findFieldByName(nodo.childNodes[i],fieldName);
			if (o != null)
				return o;
		}
	}
	return o;
}
function findButtonByName(nodo,fieldName){
	if (nodo.type == 'button'){
		if (nodo.name == fieldName){
			return nodo;
		}
	}
	var o = null;
	if (nodo.childNodes != null){
		var i;
		for (i=0; i<nodo.childNodes.length;i++){
			o = findButtonByName(nodo.childNodes[i],fieldName);
			if (o != null)
				return o;
		}
	}
	return o;
}
function transformar(nodo,o,debug){
	if (o == null)
		o = new Object();
	if (nodo.type == 'text' || nodo.type == 'hidden' || nodo.type == 'password'){
		if (nodo.type == 'select'){
			alert('select'+nodo.value);
		}
		o[nodo.name] = nodo.value;
		return o;
	}
	if(nodo.type == 'checkbox'){
		if(nodo.checked){
			o[nodo.name] = nodo.value;
			return o;
		}else{
			return o;
		}
	}

	if (nodo.nodeName == 'SELECT'){
		o[nodo.name] = nodo.value;
		return o;
	}
	if (debug==true){
		alert(nodo.nodeName);
	}
	if (nodo.childNodes != null){
		var i;
		for (i=0; i<nodo.childNodes.length;i++){
			o = transformar(nodo.childNodes[i],o,debug)
		}
	}
	return o;
}
function getProperty(obj,prop){
	var s = prop.split('.');
	if (s.length == 1){
		try{
			obj[s[0]].split('.');
			return (obj[s[0]]);
		}catch(e){
			return '';
		}
		
	}
	var s2 = s[1];
	var i=0;
	for (i=2;i<s.length;i++){
		s2=s2+'.'+s[i];
	}
	return getProperty(obj[s[0]],s2);
}

