//---------------------------------------------------------------------------------
//						CATALOGO.JS 
//
//		Contiene funciones necesarias para realizar las busquedas en catalogos
// 	segun el estandar CSW.
//	
//---------------------------------------------------------------------------------

var numberOfResults = 0;

//---------------------------------------------------------------------------------
// busquedaCatalogo: funcion encargada de establecer el tipo de busqueda a realizar
//---------------------------------------------------------------------------------
function busquedaCatalogo(){
	//Reseteamos la variable global de records de la peticiÃ³n actual 
	recordsActuales = 1;
	
	//Decidimos el tipo de busqueda a realizar
	if (document.getElementById("busqClave").style.display != "none"){
		busquedaClave();
	}else{
		if (document.getElementById("busqTema").style.display != "none"){
			busquedaTema();
		}else{
			if (document.getElementById("busqAsist").style.display != "none"){
				busquedaAsistida();
			}else{
				alert("ERROR");
			}
		}
	}
}

//---------------------------------------------------------------------------------
//imgError: Para el evento onerror de las imagenes de la busqueda catalogo 
//			generadas en cuerpoRes
//---------------------------------------------------------------------------------	
function imgError(idInput){
	return function() {
		this.setAttribute("inputdisabled", "true"); //marcamos la imagen para que mantenga el input disabled
		this.src = urlImagenes + "result_noImg.png";
	};
}

function logoError(idInput){
	return function(){
		this.src = urlImagenes + "result_noLogo.png";
	}
}

//---------------------------------------------------------------------------------
//imgLoad: Para el evento onload de las imagenes de la busqueda catalogo 
//			generadas en cuerpoRes active el input del checkbox
//---------------------------------------------------------------------------------	
function imgLoad(img,idInput){
	if (img.complete){
		if (document.getElementById(idInput) != null){				
			if (img.getAttribute("inputdisabled") == "false"){
				document.getElementById(idInput).disabled = false;
				var ident = idInput.substr(0,idInput.indexOf("_"));
				var j = 0;
				while(document.getElementById(ident+"__"+j+"__checkbox_sublayer") != null){
					document.getElementById(ident+"__"+j+"__checkbox_sublayer").disabled = false;
					j++;
				}
			}
			img.parentNode.getElementsByTagName("div")[0].style.display = "none";
		}else{
			setTimeout(function(){imgLoad(img,idInput)},1000);
		}
	}else{
		setTimeout(function(){imgLoad(img,idInput)},1000);
	}	
}

//---------------------------------------------------------------------------------
//abrirVentana: Para el evento onclick de las imagenes de los Documentos generados 
//				en cuerpoRes
//---------------------------------------------------------------------------------	
function abrirVentana(linkage){
	return function() {
		window.open(linkage,"","");
	};
}


//---------------------------------------------------------------------------------
//pagAtras y pagAdelante: para moverse por la paginacion de resultados
//---------------------------------------------------------------------------------
var paginaMapas = 1;
var paginaMapasMax = 1;
var paginaDocumentos = 1;
var paginaDocumentosMax = 1;

var pagActMapas = 1; //paginacion actual mapas
var pagActDocumentos = 1; //paginación actual documentos

//devuelve un array con los valores de pagina y max pagina segun el tipo de resultado
function getPagina(tipo){
	var paginaArray = new Array();
	
	switch(tipo){
		case "Mapas":
			paginaArray['pagina'] = paginaMapas;
			paginaArray['paginaMax'] = paginaMapasMax;
			break;
		case "Documentos":
			paginaArray['pagina'] = paginaDocumentos;
			paginaArray['paginaMax'] = paginaDocumentosMax;
			break;
	}
	
	return paginaArray;
}

//asigna un nuevo valor a la pagina segun el tipo
function setPagina(tipo, valor){
	switch(tipo){
		case "Mapas":
			paginaMapas = valor;
			break;
		case "Documentos":
			paginaDocumentos = valor;
			break;
	}
}

//oculta todas las paginas y muestra la que toca
function pagMostrar(resTotales, tipo, paginaArray){
	//ocultamos todos los divs de paginacion
	for (var i=1; i <= paginaArray['paginaMax']; i++){
		document.getElementById("resultados" + tipo + "CuerpoPag_"+i).style.display = "none";
	}
	
	//actualizamos los valores del div de navegacion de la paginacion
	resultadoInicial = (resXpag * (paginaArray['pagina']-1)) + 1;
	resultadoFinal = resXpag * paginaArray['pagina'];
	if (resTotales < resultadoFinal)
		resultadoFinal = resTotales; 
	Ext.DomHelper.overwrite('resultado' + tipo + 'Inicial', ""+resultadoInicial);
	Ext.DomHelper.overwrite('resultado' + tipo + 'Final', ""+resultadoFinal);
	
	//mostramos el div de paginacion actual
	Ext.getDom("resultados" + tipo + "CuerpoPag_" + paginaArray['pagina']).style.display = "block";
}

//muestra la pagina anterior
function pagAtras(resTotales, tipo){
	return function() {
		var paginaArray = getPagina(tipo);
		
		if (paginaArray['pagina'] > 1){
			paginaArray['pagina']--;
			//setPagina(tipo, paginaArray['pagina']);
			//pagMostrar(resTotales, tipo, paginaArray);
			paginacionResListaRefresca2(paginaArray['pagina'], tipo);
		}
	};
}

//muestra la pagina siguiente
function pagAdelante(resTotales, tipo){
	return function() {
		var paginaArray = getPagina(tipo);
		
		if (paginaArray['pagina'] < paginaArray['paginaMax']){
			paginaArray['pagina']++;
			//setPagina(tipo, paginaArray['pagina']);
			//pagMostrar(resTotales, tipo, paginaArray);
			paginacionResListaRefresca2(paginaArray['pagina'], tipo);
		}
	};
}


//---------------------------------------------------------------------------------
// servAtras, servAdelante, servGo: busqueda en el servidor/catalogo
//---------------------------------------------------------------------------------
var proxyUrlServ = servidor_local + '/IDESiapad/proxyMetadata';
var parametroServ = "";

//peticion al servidor
function servGo(){
	//Reseteamos los records actuales sobre los q se realiza la bÃºsqueda, al ser un cambio de nodo
	recordsActuales = 1;
	
	servidor = Ext.getDom('comboServidores').selectedIndex;
	http.open("POST",proxyUrlServ+"?url="+servidores[servidor]["url"], true);
	http.setRequestHeader("content-type","application/x-www-form-urlencoded");
	http.onreadystatechange = handleBusq;		   		
	http.send(parametroServ);
}

function trimComas(cad){	
	var cad_aux = "";
	var cad = trim(cad);
	while(cad.indexOf("  ")>0){
		cad = cad.replace("  "," ");
	}
	for (var ind_ent = 0; ind_ent < cad.length; ind_ent++){		
		var caract = cad.charAt(parseInt(ind_ent));	
		if (caract != " "){
			cad_aux += caract;		
		}else{			
			if ((cad.charAt(parseInt(ind_ent)-1) != ",") && (cad.charAt(parseInt(ind_ent)+1) != ",")) {
				cad_aux += caract;					
			}		
		}
		
	}
	return(cad_aux);
	
}

//---------------------------------------------------------------------------------
//cuerpoRes: Cuerpo de los resultados obtenidos en handleBusq
//---------------------------------------------------------------------------------	
function cuerpoRes(resultados, tbody, ires, tipo){
	//cuerpo
	var tr;
	var td_checkbox;
	var input_checkbox;
	var input_linkage;
	var td_logo;
	var img_logo;
	var td_descr;
	var h2_descr;
	var txt_descr;
	var a_descr;
	var div_descr;
	var td_img;
	var div_td_img;
	var img_img;
	var src_img;
	var div_img;
	var img_cargando;
	var td_meta;
	var a_meta;
	var img_meta;
	
	//var flag_checkbox;
	var flag_img;
	var aux;
	
	//var tipo;
	var name;
	var title;
	var abstract;
	var linkage;
	var norte;
	var sur;
	var este;
	var oeste;
	var identifier;	   	
	//flag_checkbox = false;
	flag_img = false;
	
	var i_total = ires + recordsActuales;
     	
	name = resultados.item(ires).getElementsByTagName("name");	
		
	if (resultados.item(ires).getElementsByTagName("logo").length > 0){
		logo = resultados.item(ires).getElementsByTagName("logo")[0].firstChild.data;
	}else{
		logo = "";
	}
	title = resultados.item(ires).getElementsByTagName("title");
	abstract = resultados.item(ires).getElementsByTagName("abstract");
	linkage = resultados.item(ires).getElementsByTagName("linkage");	
	norte = resultados.item(ires).getElementsByTagName("north");
	sur = resultados.item(ires).getElementsByTagName("south");
	este = resultados.item(ires).getElementsByTagName("east");
	oeste = resultados.item(ires).getElementsByTagName("west");
	identifier = resultados.item(ires).getElementsByTagName("identifier");
	//alert(name.item(0).firstChild.data + " - " + title.item(0).firstChild.data + " - " + abstract.item(0).firstChild.data + " - " + linkage.item(0).firstChild.data);

	//Si la capa tiene title y abstract la mostramos, sino no.
	//if (title.length > 0 && abstract.length > 0){
   	  //if ((title.length > 0) && (title.item(0).firstChild != null)){
	if (((title.length > 0) && (title.item(0).firstChild != null)) && (identifier.length > 0) && (identifier.item(0).firstChild != null)){
		title = title.item(0).firstChild.data;
		//abstract puede llegar en varios nodos
		if (abstract.length > 0){
			if (abstract.length > 1){
				aux = "";
				for(var j = 0; j < abstract.length; j++) { 
					if (abstract.item(j) && abstract.item(j).firstChild)
						aux += abstract.item(j).firstChild.data;
				}
				abstract = aux;
			}
			else abstract = abstract.item(0).firstChild.data;
		}else{
			abstract = "Resumen no disponible.";
		}
		//alert("length ="+abstract.length+"abstract ="+abstract);
		if (abstract.length > 300){
			abstract = abstract.substr(0,300);
			abstract = abstract.concat("...");
//			alert("length ="+abstract.length+"abstract ="+abstract);
		}
		
		//si la capa tiene name y linkage se podra añadir al visor
		if (name.length > 0 && linkage.length > 0){
			name = name.item(0).firstChild.data;			
			//alert("name ="+name);
			aux = "";
			aux = name.split(",");
			name = "";
			
			for ( var l=0; l < aux.length; l++){
				if (l == (aux.length -1)){ 
					name += trim(aux[l]);
				}else{
					name += trim(aux[l])+",";
				}
			}
			
			//linkage puede llegar en varios nodos
			if (linkage.length > 1){
				aux = "";
				for(var j = 0; j < linkage.length; j++) { 
					aux += linkage.item(j).firstChild.data;
				}
				linkage = aux;
			}
			else linkage = linkage.item(0).firstChild.data;
			
			if (linkage.indexOf(".map") > 0){				
				linkage = linkage.substring(0,linkage.indexOf(".map")+4);
			}else{
				if (linkage.indexOf("?") > 0){
					if (linkage.indexOf("ServiceName") > 0){
						if (linkage.indexOf("&") > 0){					
							linkage = linkage.substring(0,linkage.indexOf("&"));
						}					
					}else{
						linkage = linkage.substring(0,linkage.indexOf("?")+1);
					}
				}
			}
			//flag_checkbox = true;
			
			//si tiene extent tendra imagen
			if (norte.length > 0 && sur.length > 0 && este.length > 0 && oeste.length > 0){			
				if (norte.item(0).firstChild != null){
					norte = norte.item(0).firstChild.data;
					if (sur.item(0).firstChild != null){
						sur = sur.item(0).firstChild.data;
						if (este.item(0).firstChild != null){	
							este = este.item(0).firstChild.data;
							if (oeste.item(0).firstChild != null){
								oeste = oeste.item(0).firstChild.data;
								flag_img = true;
							}
						}
					}
				}	
			}
		}
		else if (linkage.length > 1){
			//linkage puede llegar en varios nodos
			aux = "";
			for(var j = 0; j < linkage.length; j++) { 
				aux += linkage.item(j).firstChild.data;
			}
			linkage = aux;
		}
		else linkage = linkage.item(0).firstChild.data;
				
		//Creamos dinamicamente la fila del resultado				       		
 		tr = document.createElement("TR");

 		//columna checkbox
 		//solo los resultados de capas tienen checkbox
 		if (tipo == "mapas"){  	
	 		td_checkbox = document.createElement("TD");
	 		td_checkbox.setAttribute("rowSpan", "2");
	 		td_checkbox.setAttribute("align", "center");
	 		td_checkbox.setAttribute("vAlign", "top");
	 		
	 		input_checkbox = document.createElement("INPUT");
	 		input_checkbox.setAttribute("type", "checkbox");
	 		input_checkbox.setAttribute("style", "margin-top: 3px");
	 		var id_checkbox = i_total + "_" + name;
	 		input_checkbox.setAttribute("id", id_checkbox+"_checkbox");
	 		input_checkbox.setAttribute((document.all ? 'className' : 'class'), "checkbox");
	 		input_checkbox.setAttribute("disabled", "true");
	 		input_checkbox.onclick = selAllLayersMap;
	 		//if (!flag_checkbox)
	 		//	input_checkbox.setAttribute("disabled", "true")
	 		input_linkage = document.createElement("INPUT");
	 		input_linkage.setAttribute("type", "hidden");
	 		input_linkage.setAttribute("value", linkage);
	 		input_linkage.setAttribute("id", id_checkbox + "_linkage");
	 		
	 		td_checkbox.appendChild(input_checkbox);
	 		
	 		td_checkbox.appendChild(input_linkage);
	 		
	 		tr.appendChild(td_checkbox);
	 	}
	 	
	 	//columna titulo y descripcion
 		td_logo = document.createElement("TD");
 		//solo los resultados de capas tienen checkbox
 		if (tipo == "documentos")
 			td_logo.setAttribute("rowSpan", "2");
 		td_logo.setAttribute("vAlign", "top");
	 	img_logo = document.createElement("IMG");
 		img_logo.setAttribute("id",i_total+"_logo");
 		//img_logo.setAttribute("width","35"); 
 		img_logo.style.width = "35px";
 		//img_logo.setAttribute("height","30");
 		img_logo.style.height = "30px";
 		if (tipo == "documentos")
 			img_logo.style.marginRight = "10px";
 		img_logo.setAttribute("src",logo);
 		img_logo.onerror = logoError(i_total + "_logo");
 		
 		td_logo.appendChild(img_logo);
 		
 		tr.appendChild(td_logo);
 		
	 	//columna titulo y descripcion
 		td_descr = document.createElement("TD");
 		td_descr.setAttribute("vAlign", "top");
 		//solo los resultados de capas tienen checkbox e imagen
 		if (tipo != "mapas") 
 			td_descr.setAttribute("colSpan", "3"); //2

		txt_descr = document.createTextNode(title);
		
		h2_descr = document.createElement("H2");
		h2_descr.setAttribute((document.all ? 'className' : 'class'), "resultados");
		
		//si es tipo documentos, metemos link en la imagen
		if (tipo == "documentos"){
			a_descr = document.createElement("A");
			a_descr.setAttribute("href", "#");
			a_descr.onclick = abrirVentana(linkage);
			a_descr.setAttribute((document.all ? 'className' : 'class'), "documentos");
			
			a_descr.appendChild(txt_descr);
			h2_descr.appendChild(a_descr);
		}
		//Sino, en negrita y subrayado
		else{
			h2_descr.appendChild(txt_descr);
		}
		
		td_descr.appendChild(h2_descr);
		
		//br_descr = document.createElement("BR");
		div_descr = document.createElement("DIV");
		div_descr.setAttribute((document.all ? 'className' : 'class'), "resultadosTexto");
		txt_descr = document.createTextNode(abstract);
		
		div_descr.appendChild(txt_descr);
		td_descr.appendChild(div_descr);
		
		tr.appendChild(td_descr);
			
		//columna imagen
		///solo los resultados de capas tienen imagen
		if (tipo == "mapas"){
			td_img = document.createElement("TD");
			//td_img.setAttribute("rowspan", "2");
			td_img.setAttribute("rowSpan", "2");
			td_img.setAttribute("align", "center");
			
			var img_img = document.createElement("IMG");
			img_img.setAttribute("width", "100");
			img_img.setAttribute("height", "100");
			img_img.setAttribute("inputdisabled", "false"); //atributo para controlar cuando desbloquear el input checkbox
			img_img.setAttribute((document.all ? 'className' : 'class'), "resultadosMapas");
			//Si tiene imagen el xml le ponemos la url
			if (flag_img){
				src_img = linkage;
				if (linkage.indexOf("?") >= 0){
					if (linkage.indexOf("?") < (linkage.length - 1))
						src_img += "&";
				}else{
				 	src_img += "?";
				}
				//var date = new Date(); //para evitar la cache de las imagenes ponemos el timestamp del date al final de la imagen
				//src_img += "SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&LAYERS="+name+"&SRS=EPSG:4326&BBOX="+oeste+","+sur+","+este+","+norte+"&WIDTH=100&HEIGHT=100&FORMAT=image/png&TRANSPARENT&STYLES=,,&d="+date.getTime();								
				src_img += "SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&LAYERS="+name+"&SRS=EPSG:4326&BBOX="+oeste+","+sur+","+este+","+norte+"&WIDTH=100&HEIGHT=100&FORMAT=image/png&TRANSPARENT=TRUE&STYLES=";				
								
				//img_img.onload = imgLoad(i_total+"_"+name+"_checkbox");	
				imgLoad(img_img,i_total+"_"+name+"_checkbox");
				img_img.onerror = imgError(i_total+"_"+name+"_checkbox");																					
			}
			//Si no, la imagen por defecto
			else 
				src_img = urlImagenes + "result_noImg.png";
				
			//img_img.setAttribute("vspace", "2");
			//img_img.setAttribute("src", src_img);
			
			//div contenedor de imagenes
			div_td_img = document.createElement("DIV");
			div_td_img.setAttribute("class","resultadosImgCont");
			div_td_img.setAttribute("className","resultadosImgCont");
						
			img_img.src = src_img;
			div_td_img.appendChild(img_img);
			
			//Si tiene imagen el xml, metemos el div e img de cargando
			
			if (flag_img){
				div_img = document.createElement("DIV");
				div_img.setAttribute("class","resultadosImg");
				div_img.setAttribute("className","resultadosImg");
				
				img_cargando = document.createElement("IMG");
				//img_cargando.setAttribute((document.all ? 'className' : 'class'), "resultadosMapasCargando");
				img_cargando.setAttribute("src", urlImagenes + "cargando-imagenes.gif");
				img_cargando.setAttribute("width", "16");
				img_cargando.setAttribute("height", "16");
				
				div_img.appendChild(img_cargando);
				div_td_img.appendChild(div_img);
			}
			
			
			td_img.appendChild(div_td_img);
			tr.appendChild(td_img);
			
		}
		//si no si es de tipo documentos solo una columna con cabecera con enlace, descripcion...
		
		tbody.appendChild(tr);
		
		/*Si en el name hay mÃ¡s de un nombre (separados por comas), es
		 * necesario mostrar todos los nombres de las capas junto a un checkbox
		 * para poder cargarlas individualmente
		*/
		
		if (name.length > 0){			
			if(name.indexOf(",") > -1){				
				name = trim(name);
				name = trimComas(name);
				var names = name.split(",");
				trc = document.createElement("TR");
				tdc = document.createElement("TD");
				tdc.setAttribute("colSpan", "2");
				txn = document.createTextNode("Lista de capas del mapa: ");
				tdc.appendChild(txn);
				trc.appendChild(tdc);
				tbody.appendChild(trc);
				
				//comprobamos si el ultimo caracter es "&" para anyadirselo o no
				if (linkage.indexOf("&") >= 0){
					if (linkage.lastIndexOf("&") < (linkage.length-1))
						linkage += "&";
				}else{
					linkage += "&";
				}
				
				linkage += "REQUEST=getCapabilities&VERSION=1.1.1&service=wms";

				if(navigator.appName == "Microsoft Internet Explorer"){
			 		var urltosend = "url="+escape(linkage);			 
			 		var link = servidor_local + "/IDESiapad/proxyWMS?nav=explorer";
		 			http.open("POST",link, false);
			 		//http.open("POST",link, true);
		   			http.setRequestHeader("content-type","application/x-www-form-urlencoded");
		   		
		   			http.onreadystatechange = handleCapabIE(i_total);
		   			http.send(urltosend);
		   		}else{		   		
		   			var urltosend = "url="+escape(linkage);			 
			 		var link = servidor_local + "/IDESiapad/proxyWMS?nav=firefox";
		 			http.open("POST",link, false);
			 		//http.open("POST",link, true);
		   			http.setRequestHeader("content-type","application/x-www-form-urlencoded");
		   			
		   			if(http.onreadystatechange == null){
		   				http.send(urltosend);
		   				handleCapabFF(i_total);
		   			}
		   		}
		   		
		   		var trsublayers = document.createElement("TR");
		   		var tdsublayers = document.createElement("TD");
		   		trsublayers.appendChild(tdsublayers);
		   		tdsublayers = document.createElement("TD");
		   		trsublayers.appendChild(tdsublayers);
		   		tdsublayers = document.createElement("TD");
		   		tdsublayers.setAttribute("colSpan", "2");
		   		var tblsublayers = document.createElement("TABLE");
		   		var tbodysublayers = document.createElement("TBODY");
		   		
				for(var k=0;k<names.length;k++){
					var trl = document.createElement("TR");
					var tdn = document.createElement("TD");
					trl.appendChild(tdn);
					var tdn = document.createElement("TD");
					trl.appendChild(tdn);
					var tdl = document.createElement("TD");
					tdl.setAttribute("colSpan",2);
					tdl.setAttribute("id","tdhl-"+k+"-"+i_total);
					var cbx = document.createElement("INPUT");
					cbx.setAttribute("type", "checkbox");
			 		cbx.setAttribute("style", "margin-top: 3px");
			 		cbx.setAttribute("id", i_total+"__"+k+"_"+names[k]+"_checkbox");
			 		cbx.setAttribute("disabled", "true");
			 		cbx.setAttribute((document.all ? 'className' : 'class'), "checkbox");
			 		var inp = document.createElement("INPUT");
			 		inp.setAttribute("type", "hidden");
			 		inp.setAttribute("value", names[k]);
			 		inp.setAttribute("id", i_total+"__"+k+"__layername");
			 		var father = document.createElement("INPUT");
			 		father.setAttribute("type","hidden");
			 		father.setAttribute("value",name);
			 		father.setAttribute("id",i_total+"__"+k+"__father");
			 		var nombre = document.createTextNode(names[k]);
			 		tdl.appendChild(cbx);
			 		tdl.appendChild(nombre);
			 		tdl.appendChild(inp);
			 		tdl.appendChild(father);
			 		trl.appendChild(tdl);
			 		//tbody.appendChild(trl);
			 		tbodysublayers.appendChild(trl);
				}
				tblsublayers.appendChild(tbodysublayers);
				tdsublayers.appendChild(tblsublayers);
				trsublayers.appendChild(tdsublayers);
				tbody.appendChild(trsublayers);								
			}
		}		
		
		//Fila de ver metadatos
		tr = document.createElement("TR");
		if (name.length > 0){
			if(name.indexOf(",") > -1){
				td_blanco = document.createElement("TD");
				tr.appendChild(td_blanco);
			}
		}
		td_meta = document.createElement("TD");
		td_meta.setAttribute("vAlign", "top");
		//solo los resultados de capas tienen checkbox
		//if (tipo != "mapas") 
 			td_meta.setAttribute("colSpan", "3"); //2
		a_meta = document.createElement("A");
		a_meta.setAttribute("href", "#");
		a_meta.setAttribute("border", "0");
		
		a_meta.onclick = metadato(identifier.item(0).firstChild.data);
		
		img_meta = document.createElement("IMG");
		img_meta.setAttribute("src", urlImagenes + "result_verMetadatos.png");
		img_meta.setAttribute("width", "82");
		img_meta.setAttribute("height", "17");
		img_meta.setAttribute("border", "0");
		//img_meta.setAttribute("vspace", "4");
		img_meta.setAttribute((document.all ? 'className' : 'class'), "verMetadatos");
		img_meta.setAttribute("id", "resultadosVerMetadatos_" + i_total);
		img_meta.onmouseover = cambiarBotonOver("resultadosVerMetadatos_" + i_total, 'result_verMetadatos-over.png');
		img_meta.onmouseout = cambiarBotonOver("resultadosVerMetadatos_" + i_total, 'result_verMetadatos.png');
		
		a_meta.appendChild(img_meta);
		td_meta.appendChild(a_meta);
		tr.appendChild(td_meta);
		
		tbody.appendChild(tr);		
	}
}

//---------------------------------------------------------------------------------
//cabeceraRes: Cabecera de los resultados obtenidos en handleBusq
//---------------------------------------------------------------------------------	
function cabeceraRes(tabla, tbody){
	tabla.setAttribute('cellPadding', 0);
	tabla.setAttribute('cellSpacing', 0);
	tabla.setAttribute('border', 0);
	tabla.setAttribute('width', '100%');
	tabla.setAttribute('align', 'center');
	
	//cabecera
	var tr_cab = document.createElement("TR");
	var br_cab = document.createElement("BR");
	var td_cab = document.createElement("TD");
	td_cab.setAttribute('width', '5%');
	td_cab.appendChild(br_cab);
	tr_cab.appendChild(td_cab); //columna de checkbox
	br_cab = document.createElement("BR");
	td_cab = document.createElement("TD");
	td_cab.setAttribute('width', '6%');
	td_cab.setAttribute('align', 'center');
	td_cab.appendChild(br_cab);
	tr_cab.appendChild(td_cab); //columna del logo
	br_cab = document.createElement("BR");
	td_cab = document.createElement("TD");
	td_cab.setAttribute('width', '69%');
	td_cab.appendChild(br_cab);
	tr_cab.appendChild(td_cab); //columna del texto
	br_cab = document.createElement("BR");
	td_cab = document.createElement("TD");
	td_cab.setAttribute('width', '20%');
	td_cab.appendChild(br_cab);
	tr_cab.appendChild(td_cab); //columna de la imagen
	tbody.appendChild(tr_cab);
}

//---------------------------------------------------------------------------------
//pieError: Pie de cuando no hay resultados en handleBusq
//---------------------------------------------------------------------------------	
function pieError(div, pError){
	//pie error
	var brError = document.createElement("BR");
	pError.setAttribute("align", "center");
	var txt_pError = document.createTextNode("No se encontraron resultados");
	pError.appendChild(brError);
	pError.appendChild(txt_pError);
		       		
	div.appendChild(pError);
}

function paginacionResListaRefresca(pagAct, tipo){
	return function() {	
		paginacionResListaRefresca2(pagAct, tipo)
	};
}

function paginacionResListaRefresca2(pagAct, tipo){
	var resTotales;
	//resultados de la busqueda
	if (tipo == "Mapas")
		resTotales = nResMapas;
	else if (tipo == "Documentos")
		resTotales = nResDocumentos;
		
	//div contenedor
	var listaPaginacion = Ext.getDom("listaPaginacion"+tipo)
	//Si no existe lo creamos
	if (!listaPaginacion){
		listaPaginacion = document.createElement("DIV");
		listaPaginacion.setAttribute("id", "listaPaginacion"+tipo);
		listaPaginacion.style.textAlign = "center";
	}
	//Si existe lo reseteamos
	else {
		while (listaPaginacion.hasChildNodes())
			listaPaginacion.removeChild(listaPaginacion.childNodes[0]);
	}
	
	//creamos la lista de links
	paginacionResLista(listaPaginacion, pagAct, tipo, resTotales);
	
	//asignamos la pagina a mostrar y mostramos el div de dicha pagina
	var paginaArray = getPagina(tipo);		
	paginaArray['pagina'] = pagAct;
	setPagina(tipo, paginaArray['pagina']);
	pagMostrar(resTotales, tipo, paginaArray);
}

function paginacionResLista(div, pagAct, tipo, resTotales){
	//var resXpag = 5;
	//var resTotal = 150;
	//var pagAct = 13;
	
	//numero de paginas
	var pags = Math.ceil(resTotales / resXpag);
	
	//pagina inicial a mostrar link
	var pagIni = Math.abs(10 - pagAct);
	if (pagIni>=pagAct) pagIni = 1;
	else if (pagIni == 4) pagIni = 1;
	else if (pagIni == 0) pagIni = 1;
	
	//pagina final a mostrar link
	var pagFin = pagAct + 10;
	if (pagFin > pags) pagFin = pags;
	
	//paginas anteriores a la actual
	for (i = pagIni; i<pagAct; i++){
		var a_lista = document.createElement("A");
		a_lista.setAttribute("href", "#");
		a_lista.setAttribute("border", "0");
		a_lista.setAttribute((document.all ? 'className' : 'class'), "paginacionLista");
		a_lista.onclick = paginacionResListaRefresca(i, tipo);
		a_lista.appendChild(document.createTextNode(i));
		div.appendChild(a_lista);
	}
	
	//pagina actual
	var b_lista = document.createElement("B");
	b_lista.appendChild(document.createTextNode(pagAct));
	div.appendChild(b_lista);
	
	//paginas siguientes a la actual
	for (i = pagAct+1; i<=pagFin; i++){
		var a_lista = document.createElement("A");
		a_lista.setAttribute("href", "#");
		a_lista.setAttribute("border", "0");
		a_lista.setAttribute((document.all ? 'className' : 'class'), "paginacionLista");
		a_lista.onclick = paginacionResListaRefresca(i, tipo);
		a_lista.appendChild(document.createTextNode(i));
		div.appendChild(a_lista);
	}
}

//---------------------------------------------------------------------------------
//paginacionRes: Div de navegaciÃ³n de la paginaciÃ³n
//---------------------------------------------------------------------------------	
function paginacionRes(div, nRes, tipo){
	//Div de la navegaciÃ³n de la paginaciÃ³n
	var divPag = Ext.getDom("resultados"+tipo+"CuerpoPag");
	//si no existe lo creamos
	if (!divPag){
		divPag = document.createElement("DIV");
		divPag.setAttribute("id", "resultados"+tipo+"CuerpoPag");
		divPag.style.textAlign = "center";
		divPag.style.marginTop = "10px";
	}
	//si existe lo reseteamos
	else {
		while (divPag.hasChildNodes())
			divPag.removeChild(divPag.childNodes[0]);
	}
	
	//Link para ir hacia atrÃ¡s
	var img_atras = document.createElement("IMG");
	img_atras.style.width = "16px";
	img_atras.style.height = "16px";
	img_atras.setAttribute("src", urlImagenes + "flechaIzda.png");
	img_atras.setAttribute("align", "top");
	img_atras.setAttribute("hspace", "10");
	//var txt_atras = document.createTextNode("<<");
	var a_atras = document.createElement("A");
	a_atras.setAttribute("href", "#");
	a_atras.setAttribute("border", "0");
	a_atras.onclick = pagAtras(nRes, tipo);
	//a_atras.appendChild(txt_atras);
	a_atras.appendChild(img_atras);
	
	//Link para ir hacia adelante
	var img_adelante = document.createElement("IMG");
	img_adelante.style.width = "16px";
	img_adelante.style.height = "16px";
	img_adelante.setAttribute("src", urlImagenes + "flechaDcha.png");
	img_adelante.setAttribute("align", "top");
	img_adelante.setAttribute("hspace", "10");
	//var txt_adelante = document.createTextNode(">>");
	var a_adelante = document.createElement("A");
	a_adelante.setAttribute("href", "#");
	a_adelante.setAttribute("border", "0");
	a_adelante.onclick = pagAdelante(nRes, tipo);
	//a_adelante.appendChild(txt_adelante);
	a_adelante.appendChild(img_adelante);
	
	//Texto central informativo, con dos span con id para poder actualizar valores tras la navegacion en la paginacion
	var paginaArray = getPagina(tipo);
	var resultadoInicial = (resXpag * (paginaArray['pagina']-1)) + 1;
	var resultadoFinal = (nRes < resXpag) ? nRes : (resXpag * paginaArray['pagina']); //si hay menos resultados q resultados por pagina, el resultado final son los resultados en si
	var span_mostrandoInicial = document.createElement("SPAN");
	span_mostrandoInicial.setAttribute("id", "resultado" + tipo + "Inicial");
	span_mostrandoInicial.style.fontWeight = "bold";
	span_mostrandoInicial.appendChild(document.createTextNode(resultadoInicial));
	var span_mostrandoFinal = document.createElement("SPAN");
	span_mostrandoFinal.setAttribute("id", "resultado" + tipo + "Final");
	span_mostrandoFinal.style.fontWeight = "bold";
	span_mostrandoFinal.appendChild(document.createTextNode(resultadoFinal));
	var txt_mostrando1 = document.createTextNode(" Mostrando resultados: ");
	var txt_mostrando2 = document.createTextNode(" al ");
	var txt_mostrando3 = document.createTextNode(" de un total de ");
	var b_total = document.createElement("B");
	b_total.appendChild(document.createTextNode(nRes));
	
	divPag.appendChild(a_atras);
	divPag.appendChild(txt_mostrando1);
	divPag.appendChild(span_mostrandoInicial);
	divPag.appendChild(txt_mostrando2);
	divPag.appendChild(span_mostrandoFinal);
	divPag.appendChild(txt_mostrando3);
	divPag.appendChild(b_total);
	divPag.appendChild(a_adelante);
	
	var divPagLista = document.createElement("DIV");
	divPagLista.setAttribute("id","listaPaginacion"+tipo);
	divPagLista.style.textAlign = "center";
	//divPagLista.style.marginTop = "10px";
	
	var pagAct;
	if (tipo == "Mapas")
		pagAct = paginaMapas;
	else if (tipo == "Documentos")
		pagAct = paginaDocumentos;
	
	paginacionResLista(divPagLista, pagAct, tipo, nRes);
	
	divPag.appendChild(divPagLista);
	
	div.appendChild(divPag);
}


//---------------------------------------------------------------------------------
//paginacionServidores: Div de navegación de la paginaciÃ³n de servidores
//---------------------------------------------------------------------------------
//Funcion que selecciona el pais actual en el combo
function actualizarComboServidores(combo){
	combo.selectedIndex = servidor;
}
function paginacionServidores(div){
	//Div de la navegaciÃ³n de la paginaciÃ³n de servidores
	var divServ = Ext.getDom("resultadosPaginacionServidores");
	//Si ya existe no lo creamos
	if (!divServ){
		divServ = document.createElement("DIV");
		divServ.style.textAlign = "center";
		divServ.style.marginTop = "10px";
		divServ.setAttribute("id", "resultadosPaginacionServidores");
		
		//Texto central
		var span_central = document.createElement("SPAN");
		var txt_central1 = document.createTextNode("EstÃ¡ en el catÃ¡logo ");
		var span_central_catalogoActual = document.createElement("SPAN");
		span_central_catalogoActual.setAttribute("id", "pagServ_CatalogoActual");
		span_central_catalogoActual.style.fontWeight = "bold";
		var txt_catalogoActual = document.createTextNode(servidores[servidor]["nombre"]);
		span_central_catalogoActual.appendChild(txt_catalogoActual);
		var txt_central2 = document.createTextNode(". Puede realizar la bÃºsqueda en uno de los siguientes catÃ¡logos: ");
		span_central.appendChild(txt_central1);
		span_central.appendChild(span_central_catalogoActual);
		span_central.appendChild(txt_central2);
	
		divServ.appendChild(span_central);
		
		var combobox = Ext.getDom("comboServidoresAux").cloneNode(true);
		combobox.setAttribute("id", "comboServidores");
		combobox.setAttribute((document.all ? 'className' : 'class'), "");
		combobox.onchange = servGo;
		actualizarComboServidores(combobox);
		divServ.appendChild(combobox);
		
		div.appendChild(divServ);
	}
	//Si estÃ¡ creado actualizamos el catalogo actual
	else{
		Ext.DomHelper.overwrite("pagServ_CatalogoActual", servidores[servidor]["nombre"]);
	}	
}

//---------------------------------------------------------------------------------
//paginacion de Records CSW: Div de bÃºsqueda en los siguientes records
//---------------------------------------------------------------------------------
//Para controlar en que intervalo de records estamos
var recordsActuales = 1;
//divDestino es el div donde se colocarÃ¡ divMaxRecords
//divMaxRecords es el div que contendrÃ¡ el link para continuar con los siguientes records
//puede ser resultadosCabeceraMaxRecords si va en la cabecera o resultadosPagMaxRecords si va en el pie donde la paginacion
function paginacionMaxRecords(divDestino, divMaxRecords){
	var div = Ext.getDom(divDestino);
	var divRecords = Ext.getDom(divMaxRecords);
	if (!divRecords){
		divRecords = document.createElement("DIV");
		if (divMaxRecords != "resultadosCabeceraMaxRecords") //texto centrado en el pie pero no en la cabecera
			divRecords.style.textAlign = "center";
		divRecords.style.marginTop = "10px";
		divRecords.setAttribute("id", divMaxRecords);
		
		//Texto
		var a_central = document.createElement("A");
		a_central.setAttribute("href", "#");
		a_central.setAttribute("border", "0");
		a_central.onclick = anyadirRecords;
		var txt_central = document.createTextNode("Buscar los siguientes "+maxRecords+" resultados");
		a_central.appendChild(txt_central);
	
		divRecords.appendChild(a_central);
		div.appendChild(divRecords);
	}
}
//peticiÃ³n para los siguientes records
function anyadirRecords(){
	//recuperamos la peticion csw
	var resultado = Ext.getDom('peticionCont').value;
	
	//editamos la peticiÃ³n csw para los siguientes records
	var records = recordsActuales + maxRecords;
	
	//entra si se busca en un nodo y hay menos records q hits, o si se busca en todos los nodos y hay menos records q hits en el nodo que se busca
	var entra = false;
	if (Ext.getDom("TodosNodos").checked && records<=servidores[servidor]["hits"])
		entra = true;
	if (Ext.getDom("UnNodo").checked && records<=hitsTotales)
		entra = true;
	if (entra){//if (records<=hitsTotales){
		resultado = resultado.replace('startPosition="1"', 'startPosition="'+records+'"');
		
		//actualizamos la variable global de records actuales
		recordsActuales = records;
				
		var parametro_post = 'xml='+resultado;
		var proxyUrl= servidor_local + '/IDESiapad/proxyMetadata';
		
		//Si buscamos solo en un nodo
		if (Ext.getDom("UnNodo").checked){
		    //http.open("POST",proxyUrl+"?url="+urlCatalogo+"&hits=1", true);
			http.open("POST",proxyUrl+"?url="+urlCatalogo, true);
	   		http.setRequestHeader("content-type","application/x-www-form-urlencoded");
	   		http.onreadystatechange = handleBusq;		   		
	   		http.send(parametro_post);
		}
		
		//Si buscamos en todos los nodos
		else if (Ext.getDom("TodosNodos").checked){
			//Actualizamos las variables globales para la navegaciÃ³n de los servidores
			proxyUrlServ = proxyUrl;
			parametroServ = parametro_post;
			
			//lanzamos la bÃºsqueda al servidor
			http.open("POST",proxyUrlServ+"?url="+servidores[servidor]["url"], true);
			http.setRequestHeader("content-type","application/x-www-form-urlencoded");
			http.onreadystatechange = handleBusq;		   		
			http.send(parametroServ);
		}
	}
	else alertaInfo("resultadosCabeceraMaxRecords", "No hay mÃ¡s registros donde obtener resultados");
}

//---------------------------------------------------------------------------------
//handleBusq: Manejador de las peticiones al catalogo 
//---------------------------------------------------------------------------------
//Contadores de resultados totales
var nResDocumentos = 0;
var nResMapas = 0;
function handleBusq() {
	switch (http.readyState){
		case 1:
    	case 2:
    	case 3:
	 		mostrarCargando();
	 	break;
		case 4:	 		
			xmlRes = http.responseXML;
			
		//alert(http.responseText);
			
			//http status = 200 OK
			//http status = 404 File not Found (por ejemplo cuando no encontraba el jsp de ExceptionHandler)
			//http status = 500 Timeout (suele pasar cuando no se encuentra el servidor de urlCatalogo)
			if(http.status != 200){
				alert("ERROR " + http.status + ": " + http.statusText);
				
			}
			else if (xmlRes == null){                     
            	alert("ERROR: El servidor de Toponimos no existe o no se encuentra disponible en estos momentos!!!");
            	
	        }
	        //Si el xml devuelve una excepciÃ³n del servicio web
	        else if (xmlRes.getElementsByTagName('serviceException').length > 0){
        		message = xmlRes.getElementsByTagName("serviceException").item(0).getElementsByTagName("message").item(0).firstChild; 
        		alert("ERROR: "+message);
	            		
	        }
	        //Parse error
	        else if (xmlRes.getElementsByTagName("parsererror").length > 0){
	        	message = xmlRes.getElementsByTagName("parsererror").item(0).firstChild.data; 
        		alert("ERROR: "+message);	        	
	        }
	        //Todo OK, generamos los resultados
	        else{
		            	
				var divMapas = document.getElementById("resultadosMapas");
				var divDocumentos = document.getElementById("resultadosDocumentos");
				
				var resultadosMapasCuerpo = document.getElementById("resultadosMapasCuerpo");
				var resultadosDocumentosCuerpo = document.getElementById("resultadosDocumentosCuerpo");
            	
				var error = false;
				var flag_Mapas = false;
				var flag_Documentos = false;
				
				//Si es la primera bÃºsqueda sobre los records del csw, borramos los resultados anteriores
				if (recordsActuales == 1){
            	
					//Si existe algun resultado de algun tipo, los eliminamos
					if (resultadosMapasCuerpo){ 
						var resultadosMapasPie = document.getElementById("resultadosMapasPie");
						divMapas.removeChild(resultadosMapasCuerpo); //divMapas.innerHTML = "";
						//si hubo error anteriormente puede ser q no tenga pie
						if (resultadosMapasPie)
							divMapas.removeChild(resultadosMapasPie);
					}
					if (resultadosDocumentosCuerpo)
						divDocumentos.removeChild(resultadosDocumentosCuerpo); //divDocumentos.innerHTML = "";
					//divDocumentos.innerHTML = "";
				}

				//Comprobamos si hubieron resultados
				if (xmlRes.getElementsByTagName('numresults').length >= 0)
		       		var nRes = parseInt(xmlRes.getElementsByTagName('numresults').item(0).firstChild.data);
		       	else var nRes = -1;
		       	
		       	//alert("resultados: "+nRes);

		       	//Si hubieron resultados en la busqueda
		       	if (nRes > 0){
		       		numberOfResults = nRes;
		       		//Contadores de resultados segun el tipo
		       		//var nResMapas;
		       		//var nResDocumentos;
		       		
		       		//var pagActMapas; //paginacion actual mapas
					//var pagActDocumentos; //paginaciÃ³n actual documentos
		       		
		       		//Si es la primera bÃºsqueda sobre los records del csw, reseteamos la paginaciÃ³n resultados anteriores
					if (recordsActuales == 1){
						//Reseteamos los valores de los contadores de resultados
						nResMapas = 0;
		       			nResDocumentos = 0;
		       			
			       		//Reseteamos valores de la paginacion
						paginaMapas = 1;
						paginaMapasMax = 1;
						paginaDocumentos = 1;
						paginaDocumentosMax = 1;
						//Reseteamos los valores de la pagina siguiente a paginar
						pagActMapas = 1;
						pagActDocumentos = 1;
					}
					else{
						//Si no es la primera busqueda actualizamos los valores de la pagina actual a paginar
						//Si en la primera busqueda hubo error, no avanzamos la paginacion
						if (Ext.getDom("resultadosMapasCuerpoError")){
			       			pagActMapas = 1;
						}
						else{
							//pagActMapas = paginaMapasMax+1;
						}
						//pagActDocumentos = paginaDocumentosMax+1;
					}
		       	
		       		var resultados = xmlRes.getElementsByTagName('result');

	       			       		
					//Cuerpo Resultados Mapas
		       		var divMapasCuerpo;
		       		//Si es la primera bÃºsqueda creamos el div contenedor de resultados
		       		if (recordsActuales == 1){
						divMapasCuerpo = document.createElement("DIV");
						divMapasCuerpo.setAttribute("id", "resultadosMapasCuerpo");
		       		}
		       		else divMapasCuerpo = Ext.getDom("resultadosMapasCuerpo");
		       		
					if (Ext.getDom("resultadosMapasCuerpoPag_" + pagActMapas)){
						var divMapasCuerpoPag = Ext.getDom("resultadosMapasCuerpoPag_" + pagActMapas);
						var tablaresMapas = divMapasCuerpoPag.getElementsByTagName("TABLE")[0];
						var tbodyMapas = divMapasCuerpoPag.getElementsByTagName("TBODY")[0];
					}
					else{
						var divMapasCuerpoPag = document.createElement("DIV"); //Para la paginacion, habrÃ¡ tantos divs como paginas
						//var pagActMapas = 1; //paginacion actual mapas
						divMapasCuerpoPag.setAttribute("id", "resultadosMapasCuerpoPag_" + pagActMapas);
						if (recordsActuales > 1 && pagActMapas > 1)
							divMapasCuerpoPag.setAttribute((document.all ? 'className' : 'class'), "oculto");
						var tablaresMapas = document.createElement("TABLE"); //Tabla Resultados Mapas
						var tbodyMapas = document.createElement("TBODY");					
						cabeceraRes(tablaresMapas, tbodyMapas);
					}
			       						
					//Cuerpo Resultados Documentos
					var divDocumentosCuerpo;
					//Si es la primera bÃºsqueda creamos el div contenedor de resultados
		       		if (recordsActuales == 1){
						divDocumentosCuerpo = document.createElement("DIV");
						divDocumentosCuerpo.setAttribute("id", "resultadosDocumentosCuerpo");
		       		}
		       		else divDocumentosCuerpo = Ext.getDom("resultadosDocumentosCuerpo");
		       		
			       	if (Ext.getDom("resultadosDocumentosCuerpoPag_" + pagActDocumentos)){
			       		var divDocumentosCuerpoPag = Ext.getDom("resultadosDocumentosCuerpoPag_" + pagActDocumentos);
			       		var tablaresDocumentos = divDocumentosCuerpoPag.getElementsByTagName("TABLE")[0]; //Tabla Resultados Documentos
			       		var tbodyDocumentos = divDocumentosCuerpoPag.getElementsByTagName("TBODY")[0];
			       	}
			       	else{
			       		var divDocumentosCuerpoPag = document.createElement("DIV"); //Para la paginacion, habrÃ¡ tantos divs como paginas
						//var pagActDocumentos = 1; //paginaciÃ³n actual documentos
						divDocumentosCuerpoPag.setAttribute("id", "resultadosDocumentosCuerpoPag_" + pagActDocumentos);
						if (recordsActuales > 1 && pagActDocumentos > 1)
							divDocumentosCuerpoPag.setAttribute((document.all ? 'className' : 'class'), "oculto");
						var tablaresDocumentos = document.createElement("TABLE"); //Tabla Resultados Documentos
						var tbodyDocumentos = document.createElement("TBODY");					
						cabeceraRes(tablaresDocumentos, tbodyDocumentos);
			       	}
				
			       	for(var iresult = 0; iresult < resultados.length; iresult++) {

			       		//si tiene tipo lo mostramos
						tipo = resultados.item(iresult).getElementsByTagName("tipo").item(0);
			       		if(tipo){
				       		tipo = tipo.firstChild.data;
				       		/* Capa: OGC:WMS-1.1.1-http-get-capabilities
			       			   Capa: OGC:WMS-1.1.1-http-get-map
			       			   Documento: WWW:LINK-1.0-http--link
			       			 */
			       			
			       			switch(tipo){
			       				//Capas
			       				case "OGC:WMS-1.1.1-http-get-capabilities":
			       				case "OGC:WMS-1.1.1-http-get-map":
			       					flag_Mapas = true;
			       					nResMapas++; //tenemos un resultado mas

			       					//Si el resultado actual es menor que la paginaciÃ³n aÃ±adimos un item a la tabla
			       					if (nResMapas <= (resXpag*pagActMapas)){			       						
			       						cuerpoRes(resultados, tbodyMapas, iresult, "mapas");			       						
			       					}
			       					//Si no, ajustamos variables de paginacion, cerramos la tabla y el div de la paginacion, y creamos el nuevo div de paginacion y tabla
			       					else {
			       						pagActMapas++;
			       						
			       						tablaresMapas.appendChild(tbodyMapas);
			       						divMapasCuerpoPag.appendChild(tablaresMapas);
								       	divMapasCuerpo.appendChild(divMapasCuerpoPag);
			       						
			       						divMapasCuerpoPag = document.createElement("DIV");
			       						divMapasCuerpoPag.setAttribute("id", "resultadosMapasCuerpoPag_" + pagActMapas);
										divMapasCuerpoPag.setAttribute((document.all ? 'className' : 'class'), "oculto");
										tablaresMapas = document.createElement("TABLE");
										tbodyMapas = document.createElement("TBODY");					
										cabeceraRes(tablaresMapas, tbodyMapas);
										
										cuerpoRes(resultados, tbodyMapas, iresult, "mapas");
			       					}			       					
			       					
			       					break;
			       					
			       				//Documentos
			       				case "WWW:LINK-1.0-http--link":
			       					flag_Documentos = true;
			       					nResDocumentos++;
			       				
			       					//Si el resultado actual es menor que la paginaciÃ³n aÃ±adimos un item a la tabla
			       					if (nResDocumentos <= (resXpag*pagActDocumentos)){
			       						
			       						cuerpoRes(resultados, tbodyDocumentos, iresult, "documentos");
			       						
			       					}
			       					//Si no, ajustamos variables de paginacion, cerramos la tabla y el div de la paginacion, y creamos el nuevo div de paginacion y tabla
			       					else {
			       						pagActDocumentos++;
			       						
			       						tablaresDocumentos.appendChild(tbodyDocumentos);
			       						divDocumentosCuerpoPag.appendChild(tablaresDocumentos);
								       	divDocumentosCuerpo.appendChild(divDocumentosCuerpoPag);
			       						
			       						divDocumentosCuerpoPag = document.createElement("DIV");
			       						divDocumentosCuerpoPag.setAttribute("id", "resultadosDocumentosCuerpoPag_" + pagActDocumentos);
										divDocumentosCuerpoPag.setAttribute((document.all ? 'className' : 'class'), "oculto");
										tablaresDocumentos = document.createElement("TABLE");
										tbodyDocumentos = document.createElement("TBODY");					
										cabeceraRes(tablaresDocumentos, tbodyDocumentos);
										
										cuerpoRes(resultados, tbodyDocumentos, iresult, "documentos");
			       					}
			       					
			       					break;
			       				default:
			       					error = true;
			       					break;
			       			}//switch(tipo){
		       			}
			       	}//for(var i = 0; i < resultados.length; i++) {
			       	
			       	//Tabla Mapas
			       	if (flag_Mapas){
			       		
			       		//si habÃ­a un error en la primera busqueda y ya hay resultados, lo eliminamos
			       		if (Ext.getDom("resultadosMapasCuerpoError"))
			       			divMapasCuerpo.removeChild(Ext.getDom("resultadosMapasCuerpoError"));
			       			
			       		//nResMapasTotal += (nResMapasTotal - nResMapas);
			       		//pie
			       		//Si no se aÃ±adieron los ultimos items al no cambiar de pag y no haber mÃ¡s resultados, los cerramos
			       		if (nResMapas <= (resXpag*pagActMapas)){
					       	tablaresMapas.appendChild(tbodyMapas);
					       	divMapasCuerpoPag.appendChild(tablaresMapas);
					       	divMapasCuerpo.appendChild(divMapasCuerpoPag);					       	
					       	//divMapas.appendChild(divMapasCuerpo);
			       		}
			       		
			       		//Si hay mÃ¡s resultados que resultados por pagina creamos el div de paginaciÃ³n
			       		if (nResMapas > resXpag || recordsActuales > 1){
			       			paginaMapasMax = pagActMapas;			       			
			       			paginacionRes(divMapasCuerpo, nResMapas, "Mapas");			       			
			       			//divMapas.appendChild(divMapasCuerpo);
			       		}
			       		
			       		divMapas.appendChild(divMapasCuerpo);

				    }
				    else{
				    	if (recordsActuales == 1){
				    		var divMapasCuerpo = document.createElement("DIV");
							divMapasCuerpo.setAttribute("id", "resultadosMapasCuerpo");
					    	//error: no results
							var divError = document.createElement("DIV");
							divError.setAttribute("id", "resultadosMapasCuerpoError");
							pieError(divMapasCuerpo, divError);
							divMapas.appendChild(divMapasCuerpo);
				    	}
				    }			       	
			       	
			       	//Tabla Documentos
				    if (flag_Documentos){
				    	
				    	//si habÃ­a un error en la primera busqueda y ya hay resultados, lo eliminamos
			       		if (Ext.getDom("resultadosDocumentosCuerpoError"))
			       			divMapasCuerpo.removeChild(Ext.getDom("resultadosDocumentosCuerpoError"));
			       			
				    	//nResDocumentosTotal += (nResDocumentosTotal - nResDocumentos);
						//pie
						//Si no se aÃ±adieron los ultimos items al no cambiar de pag y no haber mÃ¡s resultados, los cerramos
			       		if (nResDocumentos <= (resXpag*pagActDocumentos)){
					       	tablaresDocumentos.appendChild(tbodyDocumentos);
					       	divDocumentosCuerpoPag.appendChild(tablaresDocumentos);
					       	divDocumentosCuerpo.appendChild(divDocumentosCuerpoPag);
					       	
					       	//divDocumentos.appendChild(divDocumentosCuerpo);
			       		}
			       		
			       		//Si hay mÃ¡s resultados que resultados por pagina creamos el div de paginaciÃ³n
			       		if (nResDocumentos > resXpag || recordsActuales > 1){
			       			paginaDocumentosMax = pagActDocumentos; //AKI
			       			
			       			paginacionRes(divDocumentosCuerpo, nResDocumentos, "Documentos");
			       			
			       			//divDocumentos.appendChild(divDocumentosCuerpo);
			       		}
			       		
			       		divDocumentos.appendChild(divDocumentosCuerpo);
					}
					else{
						if (recordsActuales == 1){
							var divDocumentosCuerpo = document.createElement("DIV");
							divDocumentosCuerpo.setAttribute("id", "resultadosDocumentosCuerpo");
							//error: no results
							var divError = document.createElement("DIV");
							divError.setAttribute("id", "resultadosDocumentosCuerpo");
							pieError(divDocumentos, divError);
							divDocumentos.appendChild(divDocumentosCuerpo);
						}
					}
					//iba aqui lo de los tabs de mapas o documentos
					
					
					//Si hubo alguna capa con tipo desconocido.
					if (error)
						alert("Error: Algun resultado es de Tipo desconocido y no se muestra.");
			    }
				else if (nRes == 0) { //if (nRes > 0){
					//No hay resultados de ningÃºn tipo, lo indicamos
					//Mapas
					var pError = document.createElement("P");
					pError.setAttribute("id", "resultadosMapasCuerpo");
					pieError(divMapas, pError);
					
					//Documentos
					pError = document.createElement("P");
					pError.setAttribute("id", "resultadosDocumentosCuerpo");
			       	pieError(divDocumentos, pError);

					//Si hay resultados de capas, o si no hay resultados de ninguno, dejamos que el subtab lo controle el tab (comportamiento por defecto)
				}//if (nRes > 0){
				else{ //nRes = -1
					alert("No se recibieron datos del servidor.");
				}
				
				//Actualizamos la cabecera de Resultados
				if (nRes > 0){
					if (Ext.getDom("TodosNodos").checked){
						cabeceraResultados = "<b>" + hitsTotales + "</b> resultados en <b>" + servidores.length + 
											"</b> cat&aacute;logos, entre los cuales para el cat&aacute;logo de <b>" + servidores[servidor]["nombre"] + 
											"</b> son v&aacute;lidos:<br> <span id='resultadosCabeceraResMapas' style='font-weight: bold;'>" + nResMapas + "</span> mapas de informaci&oacute;n geogr&aacute;fica y <span id='resultadosCabeceraResDocumentos' style='font-weight: bold;'>" + nResDocumentos + "</span> documentos";
					}
					else cabeceraResultados = "<span id='resultadosCabeceraResMapas' style='font-weight: bold;'>" + nResMapas + "</span> mapas de informaci&oacute;n geogr&aacute;fica y <span id='resultadosCabeceraResDocumentos' style='font-weight: bold;'>" + nResDocumentos + "</span> documentos";
					//cabeceraResultados = "Total resultados: " + nRes + " (Mapas: " + nResMapas + "; Documentos: " + nResDocumentos + ")";
	            
				}
				else {
					if (Ext.getDom("TodosNodos").checked){
						cabeceraResultados = "<b>" + hitsTotales + "</b> resultados en <b>" + servidores.length + 
											"</b> catÃ¡logos, entre los cuales para el catÃ¡logo de <b>" + servidores[servidor]["nombre"] + 
											"</b> no hay resultados vÃ¡lidos.";
					}
					else cabeceraResultados = "0 resultados";
				}
					
				//Ext.DomHelper.overwrite('resultadosCabecera', cabeceraResultados);
				Ext.DomHelper.overwrite('resultadosCabeceraRes', cabeceraResultados);
					
				SetHiddenLayerNames();
				
				//si hay mas resultados que los pedidos, ponemos el link para la siguiente peticiÃ³n
				//en el caso de multiples servidores se consulta sobre hitTotales, para un Ãºnico servidor sobre nResMapas
				//alert("hitsTotales: "+hitsTotales+" maxRecords: "+maxRecords);
				if (hitsTotales > maxRecords){
					paginacionMaxRecords("resultados", "resultadosPagMaxRecords"); //tabsResultadosCont
					paginacionMaxRecords("resultadosCabeceraRes", "resultadosCabeceraMaxRecords");
				}
				
				//si hay varios servidores, agregamos la paginacion de servidores
				if (Ext.getDom("TodosNodos").checked)
					paginacionServidores(Ext.getDom("resultados")); //tabsResultadosCont
				
				//mostramos el div de resultados			
				setTimeout(function () { tabs('resultados');}, 1000);
				
			 //}//if (xmlRes.getElementsByTagName('serviceException').length > 0){
	         //}//if (xmlRes == null){ 
			}//if(http.status == 200){

			var comboServidores = Ext.getDom("comboServidores");
			if (comboServidores && comboServidores.selectedIndex != 0)
				comboServidores.selectedIndex = 0;
							
            ocultarCargando();
            //Si no hay resultados de mapas y si de documentos, mostramos los documentos
			if (!flag_Mapas && flag_Documentos){
				tabsResultados("documentos");
			}else{						
				setTimeout(function () { tabsResultados("mapas"); }, 1000);
			}
        break;
        case 0:
            alert("ERROR: El servidor de Toponimos no existe o no se encuentra disponible en estos momentos!!!");
        break;                
    }
}


//---------------------------------------------------------------------------------
//EvaluarExpresion: se encarga de transformar la expresion (cadena) de bï¿½squeda a 
//	un xml (gml) para realizar la peticion a al catalogo csw
//---------------------------------------------------------------------------------	
var primera = true;
function EvaluarExpresion(expresion){	
	var result = "";
	var aux_y = expresion.split(" Y ");	
	if (aux_y.length > 1){ //EXPRESION CON CONJUNCION AND
		result += "<And>";		
		if (primera == true){						
			primera = false;
			
			//Si hay criterios de busqueda miramos los filtros espaciales y temporales
			if (flag_criterios){
			
				//Filtro espacial
				var oIframe = document.getElementById('iframeDonde');		
				var oDoc = (oIframe.contentWindow || oIframe.contentDocument);
				if (oDoc.document) oDoc = oDoc.document;
				
				if (oDoc.getElementsByName("southCoord")[0].value != ""){
						var div_padre = oDoc.getElementById("mainMapPane_OpenLayers_Container");					
						var existe_box = false;
						for (var k=0; k < div_padre.childNodes.length; k++){
							var div_id = div_padre.childNodes[k].id;
							if (div_id.indexOf("OpenLayers.Layer.Boxes_") >= 0){						
								existe_box = true;
							}
						}
						if (existe_box == true){
				            var south = oDoc.getElementsByName("southCoord")[0].value.replace(',','.');      
				            var east = oDoc.getElementsByName("eastCoord")[0].value.replace(',','.');      
				            var north = oDoc.getElementsByName("northCoord")[0].value.replace(',','.');
				            var west = oDoc.getElementsByName("westCoord")[0].value.replace(',','.');
			            	if (( south != north) && ( north != west)){		            
			            		filtro_espac = true;
					            result += "<And>";						           			
					            result += "<BBOX>";
								result += "<PropertyName>ows:BoundingBox</PropertyName>";
								result += "<gml:Envelope srsName=\"http://www.opengis.net/gml/srs/epsg.xml#63266405\">";
			              		result += "<gml:lowerCorner>"+south+" "+west+"</gml:lowerCorner>";
			              		result += "<gml:upperCorner>"+north+" "+east+"</gml:upperCorner>";
			            		result += "</gml:Envelope>";
			            		result += "</BBOX>";
			            	}
			            }
					}
				
				//Filtro temporal
				if ((document.getElementById("campo_fecha_ini").value != "") || (document.getElementById("campo_fecha_fin").value != "")){
					if (document.getElementById("campo_fecha_ini").value != ""){
						var fecha_ini = document.getElementById("campo_fecha_ini").value;
						var aux_ini = fecha_ini.split("/");
						fecha_ini = aux_ini[2]+"-"+aux_ini[1]+"-"+aux_ini[0];
						result+="<PropertyIsGreaterThanOrEqualTo><PropertyName>dct:modified</PropertyName><Literal>";
			        	result += fecha_ini+"</Literal></PropertyIsGreaterThanOrEqualTo>"; 
					}
					if (document.getElementById("campo_fecha_fin").value != ""){	        	
						var fecha_fin = document.getElementById("campo_fecha_fin").value;
						var aux_fin = fecha_fin.split("/");
						fecha_fin = aux_fin[2]+"-"+aux_fin[1]+"-"+aux_fin[0];
			        	result += "<PropertyIsLessThanOrEqualTo><PropertyName>dct:modified</PropertyName><Literal>";
			        	result += fecha_fin+"</Literal></PropertyIsLessThanOrEqualTo>";         	  	            	
			        }
		        }
			}//if (flag_Criterios)
		}			
		for (var i=0; i < aux_y.length; i++){	
			if (aux_y[i].indexOf("expr") >= 0 ){
				var ind_y = aux_y[i].substr(aux_y[i].indexOf("expr")+4,aux_y[i].length);
				result += EvaluarExpresion(expr[parseInt(ind_y)]);
			}else{
				result += '<PropertyIsEqualTo><PropertyName>any</PropertyName><Literal>'+trim(aux_y[i])+'</Literal></PropertyIsEqualTo>';
			}					
		}		
		result += "</And>";	
	}else{	//Expresion con conjuncion OR	
		var aux_o = expresion.split(" O ");					
		if (aux_o.length > 1){
			result += "<Or>";
			for (var j=0; j < aux_o.length; j++){
				if (aux_o[j].indexOf("expr") >= 0 ){
					var ind_o = aux_o[j].substr(aux_o[j].indexOf("expr")+4,aux_o[j].length);					
					result += EvaluarExpresion(expr[parseInt(ind_o)]);
				}else{
					result += '<PropertyIsEqualTo><PropertyName>any</PropertyName><Literal>'+trim(aux_o[j])+'</Literal></PropertyIsEqualTo>';
				}				
			}
			result += "</Or>";
		}else{ //Espresion sin conjunciones			
			if (primera == true){								
				var filtro_espac = false;			
				var filtro_time = false;
				primera = false;
				
				//Si hay criterios de busqueda miramos los filtros espaciales y temporales
				if (flag_criterios){
				
					//Filtro espacial
					var oIframe = document.getElementById('iframeDonde');		
					var oDoc = (oIframe.contentWindow || oIframe.contentDocument);
					if (oDoc.document) oDoc = oDoc.document;
									
					if (oDoc.getElementsByName("southCoord")[0].value != ""){
						var div_padre = oDoc.getElementById("mainMapPane_OpenLayers_Container");					
						var existe_box = false;
						for (var k=0; k < div_padre.childNodes.length; k++){
							var div_id = div_padre.childNodes[k].id;											
							if (div_id.indexOf("OpenLayers.Layer.Boxes_") >= 0){						
								existe_box = true;
							}
						}
						if (existe_box == true){
				            var south = oDoc.getElementsByName("southCoord")[0].value.replace(',','.');      
				            var east = oDoc.getElementsByName("eastCoord")[0].value.replace(',','.');      
				            var north = oDoc.getElementsByName("northCoord")[0].value.replace(',','.');
				            var west = oDoc.getElementsByName("westCoord")[0].value.replace(',','.');
			            	if (( south != north) && ( north != west)){		            
			            		filtro_espac = true;
					            result += "<And>";	
					            result += "<BBOX>";
								result += "<PropertyName>ows:BoundingBox</PropertyName>";
								result += "<gml:Envelope srsName=\"http://www.opengis.net/gml/srs/epsg.xml#63266405\">";
			              		result += "<gml:lowerCorner>"+south+" "+west+"</gml:lowerCorner>";
			              		result += "<gml:upperCorner>"+north+" "+east+"</gml:upperCorner>";
			            		result += "</gml:Envelope>";
			            		result += "</BBOX>";
			            		
			            	}
			            }
					}
					
					//Filtro temporal
					if ((document.getElementById("campo_fecha_ini").value != "") || (document.getElementById("campo_fecha_fin").value != "")){
						filtro_time = true;
						if (document.getElementById("campo_fecha_ini").value != ""){
							var fecha_ini = document.getElementById("campo_fecha_ini").value;
							var aux_ini = fecha_ini.split("/");
							fecha_ini = aux_ini[2]+"-"+aux_ini[1]+"-"+aux_ini[0];
							if (filtro_espac == false){
					            result += "<And>";
							}
							result +="<PropertyIsGreaterThanOrEqualTo><PropertyName>dct:modified</PropertyName><Literal>";
				        	result += fecha_ini+"</Literal></PropertyIsGreaterThanOrEqualTo>"; 
						}
						if (document.getElementById("campo_fecha_fin").value != ""){	        						
							var fecha_fin = document.getElementById("campo_fecha_fin").value;
							var aux_fin = fecha_fin.split("/");
							fecha_fin = aux_fin[2]+"-"+aux_fin[1]+"-"+aux_fin[0];
							if ((filtro_espac == false) && (document.getElementById("campo_fecha_ini").value == "")){
								result += "<And>";
							}
				        	result +="<PropertyIsLessThanOrEqualTo><PropertyName>dct:modified</PropertyName><Literal>";
				        	result += fecha_fin+"</Literal></PropertyIsLessThanOrEqualTo>";         	  	            	
				        }
			        }
				}//if (flag_Criterios){
		        		        
		        expresion = trim(expresion);
				if (expresion.indexOf("expr") >= 0 ){
					var ind = expresion.substr(expresion.indexOf("expr")+4,expresion.length);					
					result += EvaluarExpresion(expr[parseInt(ind)]);
				}else{
					result += '<PropertyIsEqualTo><PropertyName>any</PropertyName><Literal>'+trim(expresion)+'</Literal></PropertyIsEqualTo>';
				}
				if ((filtro_espac == true) || (filtro_time == true)){
					result += "</And>";
				}
			}else{
				expresion = trim(expresion);
				if (expresion.indexOf("expr") >= 0 ){
					var ind = expresion.substr(expresion.indexOf("expr")+4,expresion.length);					
					result += EvaluarExpresion(expr[parseInt(ind)]);
				}else{
					result += '<PropertyIsEqualTo><PropertyName>any</PropertyName><Literal>'+trim(expresion)+'</Literal></PropertyIsEqualTo>';
				}			
			}
		}
	}
	return(result);
}


function encontrarParentesisAnt(cad, pos_fin){
	var i = pos_fin - 1;
	var cadena = new String(cad);
	while (i>=0){
		if (cad.substring(i,i+1) == "("){
			return i;
		}
		i--;
	}
	return -1;
}
//Sustituir Palabra
function SustituirPalabra(expresion,cadena){
	var cad = new String(expresion);
	cad = cad.replace(cadena,"");
	cad = cad.replace("()","expr"+parseInt(expr.length-1));	
	return cad;
}
//---------------------------------------------------------------------------------
//ObtenerExpresion: realiza la peticion al servidor de catalogo
//---------------------------------------------------------------------------------	
var expr;	
function ObtenerExpresion(xml){		
	xml = trim(xml);
	prueba = xml;
	var pos_fin = xml.length;
	var pos_ant = 0;
	var cut;
	var cadena;
	var elem = 0;
	var elem_ant = -1;
	pos_fin = prueba.indexOf(")");
	if (parseInt(pos_fin) > 0){						
		elem_ant = encontrarParentesisAnt(xml, pos_fin);	
		expr[expr.length] = xml.substring(elem_ant+1,pos_fin);		

		//Problema cuando tenemos una palabra contenida en otra con el split
		/*
		cut = xml.split(expr[expr.length-1]);
		if (cut[0].length <= 1){
			cut[0] = "";
		}else{		
			cut[0] = cut[0].substring(0,cut[0].length-1);		
		}		
		cut[1] = trim(cut[1]).substring(1,cut[1].length);		
		cadena = cut[0] + "expr" + parseInt(expr.length-1)+ cut[1];	
		*/
		//Tenemos que sustituir la cadena por la expresion correspondiente 
		cadena = SustituirPalabra(xml,expr[expr.length-1]);			
		ObtenerExpresion(cadena);	
	}else{
		var pos_ini_y = prueba.indexOf(" Y ");
		var pos_ini_o = prueba.indexOf(" O ");

		var pos_next_y = -1;
		var pos_next_o = -1;
		var pos_ant_o = -1;
		var pos_fin_y = -1;
		var pos_fin_o = -1;
		var pos_fin = -1;
		
		if (parseInt(pos_ini_y) > 0){ //Buscamos primero los AND's mas prioritarios			
			//Si encuentras una cadena acotamos la cadena a la expresion binomial
			while ((parseInt(pos_ini_o) < parseInt(pos_ini_y)) && (parseInt(pos_ini_o) > 0)){
				pos_ant_o = parseInt(pos_ini_o);
				pos_ini_o = prueba.indexOf(" O ",parseInt(pos_ant_o)+1);					
			}			

			//Acotamos la cadena por arriba para obtener la posicion 
			pos_fin_y = prueba.indexOf(" Y ",parseInt(pos_ini_y)+1);
			pos_fin_o = prueba.indexOf(" O ",parseInt(pos_ini_y)+1);

			if ((parseInt(pos_fin_y) > 0) || (parseInt(pos_fin_o) > 0)){ //Hay una Y o O despues de la que tenemos
				if ((parseInt(pos_fin_y) > 0) && (parseInt(pos_fin_o) > 0)){
					if (parseInt(pos_fin_y) > parseInt(pos_fin_o)){
						pos_fin = parseInt(pos_fin_o);							
					}else{
						pos_fin = parseInt(pos_fin_y);
					}
				}else{
					if (parseInt(pos_fin_y) > 0){
						pos_fin = parseInt(pos_fin_y);
					}else{
						pos_fin = parseInt(pos_fin_o);
					}						
				}
			}
				
			if (parseInt(pos_ant_o) > 0){					
				if (parseInt(pos_fin) > 0){
					expr[expr.length] = xml.substring(parseInt(pos_ant_o)+2,pos_fin);
					cut = xml.split(expr[expr.length-1]);					
					cut[1] = cut[1].substring(1,cut[1].length);
				}else{
					expr[expr.length] = xml.substring(parseInt(pos_ant_o)+2,xml.length);
					cut = xml.split(expr[expr.length-1]);		
				}
			}else{
				if (parseInt(pos_fin) > 0){
					expr[expr.length] = xml.substring(0,pos_fin);
				}else{
					expr[expr.length] = xml.substring(0,xml.length);
				}
				cut = xml.split(expr[expr.length-1]);		
				cut[0] = cut[0].substring(0,cut[0].length-1);
				cut[1] = cut[1].substring(1,cut[1].length);
			}
			
			cadena = cut[0] + " expr" + parseInt(expr.length-1)+ " " + cut[1];							
			ObtenerExpresion(cadena);				
		}else{ // Si hay O's seran unicas por lo que									
			if (parseInt(pos_ini_o) > 0){ //HAY O'sss
				//tenemos la primera O y buscamos la siguiente si la hay
				pos_ant_o = parseInt(pos_ini_o);
				pos_fin = prueba.indexOf(" O ",parseInt(pos_ant_o)+1);
				if (parseInt(pos_fin) > 0){					
					expr[expr.length] = xml.substring(0,pos_fin);
				}else{					
					expr[expr.length] = xml.substring(0,xml.length);
				}
				cut = xml.split(expr[expr.length-1]);		
				cut[0] = cut[0].substring(0,cut[0].length-1);
				cut[1] = cut[1].substring(1,cut[1].length);
				cadena = cut[0] + " expr" + parseInt(expr.length-1)+ " " + cut[1];							
				ObtenerExpresion(cadena);				
			}else{				
				expr[expr.length] = prueba;			
				//var resultado = '<csw:GetRecords service="CSW" version="2.0.1" xmlns="http://www.opengis.net/cat/csw" xmlns:csw="http://www.opengis.net/cat/csw" xmlns:ogc="http://www.opengis.net/ogc" xmlns:gml="http://www.opengis.net/gml" startPosition="1" maxRecords="100" outputSchema="csw:IsoRecord" resultType="results">';
				//resultado += '<csw:Query typeNames="csw:application csw:service csw:dataset csw:datasetcollection"><csw:ElementSetName>full</csw:ElementSetName><csw:Constraint version="1.1.0">result+="<ogc:Filter xmlns=\"http://www.opengis.net/ogc\" xmlns:gml=\"http://www.opengis.net/gml\">";';
				//poner hits para numero de resultados
				
				var resultado = '<csw:GetRecords xmlns:csw="http://www.opengis.net/cat/csw" service="CSW" version="2.0.1" resultType="results" outputSchema="csw:IsoRecord" startPosition="1" maxRecords="'+maxRecords+'">';
				resultado += '<csw:Query><csw:ElementSetName>full</csw:ElementSetName><csw:Constraint version="1.1.0">';
      			resultado += '<Filter xmlns="http://www.opengis.net/ogc" xmlns:gml="http://www.opengis.net/gml">';
				
				var indFenom = document.getElementById('selFenom').selectedIndex;
				//Filtro Keywords	 
		    	primera = true;
				resultado += EvaluarExpresion(expr[expr.length-1]);
				//resultado += "</ogc:And>";			
				resultado += '</Filter></csw:Constraint></csw:Query></csw:GetRecords>';			
				
				Ext.getDom('peticionCont').value = resultado;
			
				var parametro_post = 'xml='+resultado;
				var proxyUrl= servidor_local + '/IDESiapad/proxyMetadata';
				
				//Si buscamos solo en un nodo
				if (Ext.getDom("UnNodo").checked){
					//consultamos los hits
					var parametro_hits = parametro_post.replace(/results/, "hits");
					var parametros = "url="+urlCatalogo+"&hits=1&"+parametro_post;
					new Ajax.Request(proxyUrl, {
						method: 'post',
						asynchronous: false,
						encoding: 'ISO-8859-1',
						postBody: parametros,
						//onCreate: ,
						//onComplete: ,
						onSuccess: handleHitsUno//,
						//onFailure: muestraError
					});
					
					//lanzamos la peticiÃ³n de bÃºsqueda
				    //http.open("POST",proxyUrl+"?url="+urlCatalogo+"&hits=1", true);
					http.open("POST",proxyUrl+"?url="+urlCatalogo, true);
			   		http.setRequestHeader("content-type","application/x-www-form-urlencoded");
			   		http.onreadystatechange = handleBusq;		   		
			   		http.send(parametro_post);
				}
				
				//Si buscamos en todos los nodos
				else if (Ext.getDom("TodosNodos").checked){
					//Actualizamos las variables globales para la navegaciÃ³n de los servidores
					proxyUrlServ = proxyUrl;
					parametroServ = parametro_post;
					
					//Obtenemos el listado de servidores si es la primera bÃºsqueda con todos los nodos
					if (servidores.length == 0){
						ObtenerServidores();
					}
					//Obtenemos los hits de todos los servidores
					for (var i = 0; i < servidores.length; i++) {
						servidor = i;
						//Obtenemos los hits del servidor
						//http.open("POST",proxyUrl+"?url="+urlCatalogo+"&hits=1", true);
						parametro_post = parametro_post.replace(/results/, "hits");
						var parametros = "url="+servidores[i]["url"]+"&hits=1&"+parametro_post;
						new Ajax.Request(proxyUrl, {
							method: 'post',
							asynchronous: false,
							encoding: 'ISO-8859-1',
							postBody: parametros,
							//onCreate: ,
							//onComplete: ,
							onSuccess: handleHits//,
							//onFailure: muestraError
						});
						
						//alert(servidores[i]["nombre"] + " - " + servidores[i]["url"] + " : " + servidores[i]["hits"]);
					}
					servidor = 0;
					hitsTotales = 0;
					
					//sumamos los hits totales
					for (var k = 0; k < servidores.length; k++) {
						if (servidores[k]["hits"] != null){
							hitsTotales += parseInt(servidores[k]["hits"]);
						}
					}

					//Realizamos la bÃºsqueda en el primer servidor
					//nos colocamos en el primer servidor que tiene hits
					for (var k = 0; k < servidores.length; k++) {
						if (parseInt(servidores[k]["hits"]) > 0){
							servidor = k;
							break;
						}
					}
					//lanzamos la búsqueda al servidor
					http.open("POST",proxyUrlServ+"?url="+servidores[servidor]["url"], true);
					http.setRequestHeader("content-type","application/x-www-form-urlencoded");
					http.onreadystatechange = handleBusq;		   		
					http.send(parametroServ);
				}
				
		   	}
		}
		   	
	}	
}

//---------------------------------------------------------------------------------
//ObtenerSinonimo: Obtiene todos los sinonimos de las tablas 
//---------------------------------------------------------------------------------
function ObtenerSinonimo(expresion, filtro){
	var proxyUrl = "/predecan/ListSinonimos";
 	var parametros = "expresion="+expresion+"&filtro="+filtro;
 	
	new Ajax.Request(proxyUrl, {
		method: 'post',
		asynchronous: false,
		encoding: 'ISO-8859-1',
		postBody: parametros,
		//onCreate: ,
		//onComplete: ,
		onSuccess: handleSinonimo//,
		//onFailure: muestraError
	});
}

function handleSinonimo(respuesta) {
	xmlRes = respuesta.responseXML;			
	/*if(http.status != 200){
		alert("ERROR " + http.status + ": " + http.statusText);
		
	}*/
	if(respuesta.status != 200){
		alert("ERROR " + respuesta.status + ": " + respuesta.statusText);
		
	}
	if (xmlRes.getElementsByTagName('Sinonimos').item(0).firstChild != null){				
		if (xmlRes.getElementsByTagName('expresion').item(0).firstChild != null){											
			var expresion = xmlRes.getElementsByTagName('expresion').item(0).firstChild.data;
			expresion = LimpiarEspacios(expresion);
			var indFenom = document.getElementById('selFenom').selectedIndex;
			var indice = document.getElementById("selFenom")[indFenom].id.substr(5);
			if (indFenom > 0){				
				var exprsinonim = document.getElementById("exprfen"+indice).value;	
				if (exprsinonim != ""){					
					expresion = "( "+expresion+" ) ";
					expresion += " Y ( " + exprsinonim +" ) ";
				}
			}
			Ext.getDom('expresionCont').value = expresion;
			ObtenerExpresion(expresion);
		}
	}	
}

//---------------------------------------------------------------------------------
//ObtenerServidores: Obtiene todos los servidores contra los que buscar
//---------------------------------------------------------------------------------
var servidores = new Array(); //[0] nombre, [1] url, [2] hits
var servidor = 0;
var hitsTotales = 0;
var comboServidores = null;
function ObtenerServidores(){	
	var proxyUrl = "/predecan/listServers";
 	//var parametros = "";
 	
	new Ajax.Request(proxyUrl, {
		method: 'post',
		asynchronous: false,
		encoding: 'ISO-8859-1',
		//postBody: parametros,
		//onCreate: ,
		//onComplete: ,
		onSuccess: handleServers//,
		//onFailure: muestraError
	});	
}

function handleServers(respuesta) {
	xmlRes = respuesta.responseXML;			
	if(respuesta.status != 200){
		alert("ERROR " + respuesta.status + ": " + respuesta.statusText);
		
	}
	//if (xmlRes.getElementsByTagName('List').item(0).firstChild != null){
		var n_servidores = xmlRes.getElementsByTagName('servidor').length;
		if (n_servidores > 0){
			//metemos el servidor local
			servidores[0] = new Array();
			servidores[0]["nombre"] = "Local";
			servidores[0]["url"] = urlCatalogo;
			
			//creamos el combobox; lo dejamos oculto para ir clonandolo tras cada peticion
			comboServidores = document.createElement("select");
			comboServidores.setAttribute("id", "comboServidoresAux");
			comboServidores.setAttribute((document.all ? 'className' : 'class'), "oculto");
			//comboServidores.onchange = servGo;
			
			//opcion inicial del combobox
			var opt = document.createElement("option");
			var txt = document.createTextNode(servidores[0]["nombre"]);
			opt.appendChild(txt);
			comboServidores.appendChild(opt);
			
			//metemos el resto de servidores
			for (var i = 0; i < n_servidores; i++) {
				if (xmlRes.getElementsByTagName('servidor').item(i).firstChild != null){											
					var servidorNombre = xmlRes.getElementsByTagName('servidor').item(i).childNodes[0].firstChild.data
					var servidorUrl = xmlRes.getElementsByTagName('servidor').item(i).childNodes[1].firstChild.data
					servidores[i+1] = new Array();
					servidores[i+1]["nombre"] = trim(servidorNombre);
					servidores[i+1]["url"] = trim(servidorUrl) + "srv/es/csw";
					
					//opciones del combobox
					var opt = document.createElement("option");
					var txt = document.createTextNode(servidores[i+1]["nombre"]);
					opt.appendChild(txt);
					comboServidores.appendChild(opt);
				}
			}
			document.body.appendChild(comboServidores);
		}
	//}
}

function handleHits(respuesta){
	xmlRes = respuesta.responseXML;			
	if(respuesta.status != 200){
		alert("ERROR " + respuesta.status + ": " + respuesta.statusText);
		
	}
	//if (xmlRes.getElementsByTagName('xml').item(0).firstChild != null){
		var hits = xmlRes.getElementsByTagName('numresults').length;
		if (hits > 0){
			if (xmlRes.getElementsByTagName('numresults').item(0).firstChild != null){											
				servidores[servidor]["hits"] = trim(xmlRes.getElementsByTagName('numresults').item(0).firstChild.data);
				/*
				//<csw:GetRecords .... maxRecords="100">
				if (servidores[servidor]["hits"] > 100)
					servidores[servidor]["hits"] = 100;*/
			}
		}
	//}
}

function handleHitsUno(respuesta){
	xmlRes = respuesta.responseXML;			
	if(respuesta.status != 200){
		alert("ERROR " + respuesta.status + ": " + respuesta.statusText);
	}
	var hits = xmlRes.getElementsByTagName('numresults').length;
	if (hits > 0){
		if (xmlRes.getElementsByTagName('numresults').item(0).firstChild != null){											
			hitsTotales = parseInt(trim(xmlRes.getElementsByTagName('numresults').item(0).firstChild.data));
			//<csw:GetRecords .... maxRecords="100">
		}
	}
}

//---------------------------------------------------------------------------------
//busquedaClave: obtiene los datos necesarios para realizar la busqueda por 
//			palabra clave.
//---------------------------------------------------------------------------------	
function busquedaClave(){
	var title = document.getElementById("titulo").value;	
	var resumen = "";
	var clave = "";
	var proveedor = "";
		
	var radioObj = document.getElementsByName("busquedaCat");
    var radioLength = radioObj.length;
    for(var i = 0; i < radioLength; i++) {
        if(radioObj[i].checked) {
            namefilter = radioObj[i].value;
            break;
        }
    }
    if (document.getElementById("titulo").value != ""){
	    expr = new Array();
	    if (namefilter == "Y"){ //Al menos una palabra (aï¿½adir O)
			var expresion = document.getElementById("titulo").value;
			var aux = expresion.split(" ");
			expresion = "";
			for (h=0;h<aux.length-1;h++){
				expresion += aux[h] + " O ";
			}
			expresion += aux[aux.length-1];	
			/*var indFenom = document.getElementById('selFenom').selectedIndex; //selFenom2
			if (indFenom > 0){				
				var exprsinonim = document.getElementById("exprfen"+indFenom).value;	
				if (exprsinonim != ""){					
					expresion = "( "+expresion+" ) ";
					expresion += " Y ( " + exprsinonim +" ) ";
				}
			}*/
			expresion = LimpiarEspacios(expresion);		
			ObtenerSinonimo(expresion, namefilter);
		}else{
			if(namefilter == "A"){//Todas las palabras (añadir Y)
				var expresion = document.getElementById("titulo").value;
				var aux = expresion.split(" ");
				expresion = "";
				for (h=0;h<aux.length-1;h++){
					expresion += aux[h] + " Y ";
				}
				expresion += aux[aux.length-1];	
				/*var indFenom = document.getElementById('selFenom').selectedIndex; //selFenom2
				var indice = document.getElementById("selFenom")[indFenom].id.substr(5);
				if (indFenom > 0){				
					var exprsinonim = document.getElementById("exprfen"+indice).value;	
					if (exprsinonim != ""){					
						expresion = "( "+expresion+" ) ";
						expresion += " Y ( " + exprsinonim +" ) ";
					}
				}*/
				expresion = LimpiarEspacios(expresion);
				ObtenerSinonimo(expresion, namefilter);																	
			}else{ //Frase exacta
				var expresion = document.getElementById("titulo").value;
				var indFenom = document.getElementById('selFenom').selectedIndex; //selFenom2
				var indice = document.getElementById("selFenom")[indFenom].id.substr(5);					
				if (indFenom > 0){				
					var exprsinonim = document.getElementById("exprfen"+indice).value;	
					if (exprsinonim != ""){					
						expresion = "( "+expresion+" ) ";
						expresion += " Y ( " + exprsinonim +" ) ";
					}
				}
				expresion = LimpiarEspacios(expresion);
				Ext.getDom('expresionCont').value = expresion;
				ObtenerExpresion(expresion);				
			}			
		}				
	}else{
		alertaError("Introduzca la expresión a buscar.");
	}
}
//Limpiar espacios 
function LimpiarEspacios(cad){
	var cad_aux = "";
	var cad = trim(cad);
	while(cad.indexOf("  ")>0){
		cad = cad.replace("  "," ");
	}
	for (var ind_ent = 0; ind_ent < cad.length; ind_ent++){		
		var caract = cad.charAt(parseInt(ind_ent));	
		if (caract != " "){
			cad_aux += caract;		
		}else{			
			if ((cad.charAt(parseInt(ind_ent)-1) != "(") && (cad.charAt(parseInt(ind_ent)+1) != ")")) {
				cad_aux += caract;					
			}		
		}
		
	}
	return(cad_aux);
}
//---------------------------------------------------------------------------------
//busquedaTema: obtiene los datos necesarios para realizar la busqueda por 
//			tema.
//---------------------------------------------------------------------------------	
function busquedaTema(){	
	var tabla = document.getElementById("tablaTemas");
	if (tabla != null){
	    var elementos = tabla.getElementsByTagName("input");	
	    var id_area = "";
	    var id_fecha = "";
		if (elementos.length > 0){
			var result = new Array();
			var numresults = 0;
			for (i=0;i<elementos.length;i++){
				var elem = elementos.item(i);
				if (elem.type == "checkbox"){
					if (elem.checked == true){
						var id = elem.id.substr(3);						
						id_area = "temexarea"+id;
						id_fecha = "temexdate"+id;
						id = "temex"+id;												
						result [numresults] = document.getElementById(id).value;
						numresults++;
					}
				}						
			}
			if (numresults > 1){ //Multiples checkbox seleccionados 
				var aux = "";
				for (i=0; i<numresults; i++){
					if (i == (numresults - 1))  
					  aux += " ( " + result[i] + " ) ";
					else
					  aux += " ( " + result[i] + " ) O ";	
				}
				result[0] = " ( " + aux + " ) ";
				numresults = 1;
			}
			if (id_area != "" && id_fecha != ""){
				var continuar = true;
				if (document.getElementById(id_area).value == "true"){			
					var oIframe = document.getElementById('iframeDonde');		
					var oDoc = (oIframe.contentWindow || oIframe.contentDocument);
					if (oDoc.document) oDoc = oDoc.document;					
					var div_padre = oDoc.getElementById("mainMapPane_OpenLayers_Container");					
					continuar = false;
					if ( div_padre != null ){
						for (var k=0; k < div_padre.childNodes.length; k++){
							var div_id = div_padre.childNodes[k].id;
							if (div_id.indexOf("OpenLayers.Layer.Boxes_") >= 0){						
								continuar = true;
							}
						}
					}else{
						continuar = false;
					}
					if (continuar == false){
						alertaError('Por favor, seleccione un Ã¡rea de bÃºsqueda en el mapa mediante la herramienta "Seleccionar zona"');
					}			
				}
				if (document.getElementById(id_fecha).value == "true"){
					if ((document.getElementById("campo_fecha_ini").value == "") && (document.getElementById("campo_fecha_fin").value == "")){
						continuar = false;
						//alert("Por favor, seleccione un periodo de bÃºsqueda temporal mediante la herramienta 'Seleccionar periodo de tiempo'");
						alertaError('Por favor, seleccione un periodo de bÃºsqueda temporal mediante la herramienta "Seleccionar periodo de tiempo"');
					}
				}
				if((numresults > 0) && (continuar == true)){									
					expr = new Array();
					var indFenom = document.getElementById('selFenom').selectedIndex;
					var indice = document.getElementById("selFenom")[indFenom].id.substr(5);					
					if (indFenom > 0){				
						var expresion = document.getElementById("exprfen"+indice).value;	
						if (expresion != ""){					
							result[numresults-1] = "( "+result[numresults-1]+" ) ";
							result[numresults-1] += " Y ( " + expresion +" ) ";
						}
					}
					result[numresults-1] = LimpiarEspacios(result[numresults-1]);
					Ext.getDom('expresionCont').value = result[numresults-1];
					ObtenerExpresion(result[numresults-1]);
				}else{
					if (numresults <= 0){
						alert("Es necesario seleccionar al menos un tema para realizar la bÃºsqueda");	
					}
				}
			}//if (id_area != "" && id_fecha != ""){
			else{
				alertaError('Es necesario seleccionar al menos un tema para realizar la bÃºsqueda');
			}
		}
	}//if (tabla != null){
	else{
		alertaError('Es necesario seleccionar un proceso para realizar la bÃºsqueda');
	}
}

//---------------------------------------------------------------------------------
//busquedaAsistida: obtiene los datos necesarios para realizar la busqueda por 
//			pregunta.
//---------------------------------------------------------------------------------	
function busquedaAsistida(){
	var tabla = document.getElementById("tablaAsist");
	if (tabla != null){
	    var elementos = tabla.getElementsByTagName("input");	
	    var id_area = "";
	    var id_fecha = "";
		if (elementos.length > 0){
			var result = new Array();
			var numresults = 0;
			for (i=0;i<elementos.length;i++){
				var elem = elementos.item(i);
				if (elem.type == "radio"){									
					if (elem.checked == true){
						var id = elem.id.substr(3);
						id_area = "pregexarea"+id;
						id_fecha = "pregexdate"+id;				
						id = "pregex"+id;				
						result [numresults] = document.getElementById(id).value;
						numresults++;
					 }
				}						
			}
			if (id_area != "" && id_fecha != ""){
				var continuar = true;
				if (document.getElementById(id_area).value == "true"){			
					var oIframe = document.getElementById('iframeDonde');		
					var oDoc = (oIframe.contentWindow || oIframe.contentDocument);
					if (oDoc.document) oDoc = oDoc.document;					
					var div_padre = oDoc.getElementById("mainMapPane_OpenLayers_Container");					
					continuar = false;
					if (div_padre != null){ 
						for (var k=0; k < div_padre.childNodes.length; k++){
							var div_id = div_padre.childNodes[k].id;
							if (div_id.indexOf("OpenLayers.Layer.Boxes_") >= 0){						
								continuar = true;
							}
						}
					}else{
						continuar = false;
					}
					if (continuar == false){
						alertaError('Por favor, seleccione un Ã¡rea de bÃºsqueda en el mapa mediante la herramienta "Seleccionar zona"');
					}			
				}
				if (document.getElementById(id_fecha).value == "true"){
					if ((document.getElementById("campo_fecha_ini").value == "") && (document.getElementById("campo_fecha_fin").value == "")){
						continuar = false;						
						alertaError('Por favor, seleccione un periodo de bÃºsqueda temporal mediante la herramienta "Seleccionar periodo de tiempo"');
					}
				}
				if((numresults > 0) && (continuar == true)){	
					expr = new Array();
					var indFenom = document.getElementById('selFenom').selectedIndex; //selFenom2
					var indice = document.getElementById("selFenom")[indFenom].id.substr(5); //selFenom2								
					if (indFenom > 0){				
						var expresion = document.getElementById("exprfen"+indice).value;
						if (expresion != ""){
							result[numresults-1] = "( "+result[numresults-1]+" ) ";
							result[numresults-1] += " Y ( " + expresion +" ) ";
						}
					}
					result[numresults-1] = LimpiarEspacios(result[numresults-1]);
					Ext.getDom('expresionCont').value = result[numresults-1];
					ObtenerExpresion(result[numresults-1]);
				}else{
					if (numresults <= 0){
						alert("Es necesario seleccionar al menos un tema o pregunta para realizar la bÃºsqueda");	
					}
				}
			}//if (id_area != "" && id_fecha != ""){
			else{
				alertaError('Es necesario seleccionar al menos una pregunta para realizar la bÃºsqueda');
			}
		}
	}//if (tabla =! null){
	else{
		alertaError('Es necesario seleccionar el perfil para realizar la bï¿½squeda');
	}
}

//-------------------------------------------------------------------------
// handleCapab recoge una peticion getCapabilities a la url que 
// contiene un .map y mete en un input 'hidden' los nombres de las
// capas de las que esta compuesto dicho mapa
//-------------------------------------------------------------------------
function handleCapabIE(ires){
	return function(){		
		switch (http.readyState){
			case 1:
	    	case 2:
	    	case 3:
		 		mostrarCargando()
		 	break;
			case 4:	 
				//alert(http.responseText);		
				xmlRes = http.responseXML;
				handleCapab(ires,xmlRes);				
				break;
		}
	};
}

function handleCapabFF(ires){
	switch (http.readyState){
		case 1:
    	case 2:
    	case 3:
	 		mostrarCargando()
	 	break;
		case 4:	 		
		//	alert(http.responseText);
			xmlRes = http.responseXML;
			handleCapab(ires,xmlRes);				
			break;
	}
}

function handleCapab(ires,xmlRes){
	var laynames = "";
	//alert(xmlRes.getElementsByTagName("Layer"));
	var layer = xmlRes.getElementsByTagName("Layer")[0];
	//alert(layer.getElementsByTagName("Layer").length);
	//Si getCapabilities devuelve el titulo	
	if(layer != null){
		var k = 0;
		while(layer.getElementsByTagName("Layer")[k] != null){
			var sublay = layer.getElementsByTagName("Layer")[k];
			laynames += sublay.getElementsByTagName("Title")[0].firstChild.data + ";";
			k++;
		}
		var hid = document.createElement("INPUT");
		hid.setAttribute("type","hidden");
		hid.setAttribute("id",ires+"-hiddenlayernames");
		hid.setAttribute("value",laynames);
		document.getElementById('resultadosMapas').appendChild(hid);
	}
	//Si no, lo dejamos con el nombre de capa para que se pueda aÃ±adir al visor aunque no se pueda mostrar el titulo
	else{
		var hid = document.createElement("INPUT");
		hid.setAttribute("type","hidden");
		hid.setAttribute("id",ires+"-hiddenlayernames");
		hid.setAttribute("value","layerName");
		document.getElementById('resultadosMapas').appendChild(hid);
	}
}

//-------------------------------------------------------------------------
// SetHiddenLayerNames cambia el html que muestra los nombres de las capas
// de un mapa, cuando este esta formado por mÃ¡s de una capa 
//-------------------------------------------------------------------------

function SetHiddenLayerNames(){
	for(var ind = 1; ind <= numberOfResults; ind++){		
		if(document.getElementById(ind+"-hiddenlayernames") != null){
			var hdl = document.getElementById(ind+"-hiddenlayernames").value;
			//Si el valor de hd1 es layerName es que no se pudo obtener de getCapabilities el titulo de la capa y dejamos el nombre
			//alert("hdl ="+hdl);
			if (hdl != "layerName"){ 
				var titles = hdl.split(";");
				for(var k=0;k<titles.length -1;k++){
					if(document.getElementById("tdhl-"+k+"-"+ind) != null){
						var old_td = document.getElementById("tdhl-"+k+"-"+ind);
						var new_td = document.createElement("TD");
						new_td.setAttribute("id","tdhl-"+k+"-"+ind);
						new_td.setAttribute("colSpan",2);
						var table = document.createElement("TABLE");
						table.setAttribute("width",100+"%");
						var tbody = document.createElement("TBODY"); 
						var tr = document.createElement("TR");
						var tdcb = document.createElement("TD");
						tdcb.setAttribute("width","4%");
						
						if (document.getElementById(ind+"__"+k+"__layername") != null){
							var nomcapa = document.getElementById(ind+"__"+k+"__layername").value;
							var father = ind + "_" + document.getElementById(ind+"__"+k+"__father").value + "_checkbox";
							var cbx = document.createElement("INPUT");
							cbx.setAttribute("type", "checkbox");
					 		cbx.setAttribute("style", "margin-top: 3px");
					 		cbx.setAttribute("id", ind+"__"+k+"__checkbox_sublayer");
					 		cbx.setAttribute("value",nomcapa);
					 		cbx.setAttribute("disabled", "true");
					 		cbx.setAttribute((document.all ? 'className' : 'class'), "checkbox");
					 		cbx.onclick = clearFather(father);
					 		tdcb.appendChild(cbx);
					 		var tdnom = document.createElement("TD");
					 		tdnom.setAttribute("id",ind+"__"+k+"__td");
					 		tdnom.onclick = selectThisCB(ind+"__"+k,father);
					 		var nombre = document.createTextNode(titles[k]);
							tdnom.appendChild(nombre);
							tr.appendChild(tdcb);
							tr.appendChild(tdnom);
							tbody.appendChild(tr);
							table.appendChild(tbody);
							new_td.appendChild(table);
							var father = old_td.parentNode;
							father.replaceChild(new_td,old_td);
						}
					}
				}
			}//if (hd1 != "layerName"){ 
			else{
				var k = 0;
				while(document.getElementById("tdhl-"+k+"-"+ind) != null){
					var old_td = document.getElementById("tdhl-"+k+"-"+ind);
					var new_td = document.createElement("TD");
					new_td.setAttribute("id","tdhl-"+k+"-"+ind);
					new_td.setAttribute("colSpan",2);
					var table = document.createElement("TABLE");
					table.setAttribute("width",100+"%");
					var tbody = document.createElement("TBODY");
					var tr = document.createElement("TR");
					var tdcb = document.createElement("TD");
					tdcb.setAttribute("width","4%");
					
					if (document.getElementById("tdhl-"+k+"-"+ind).firstChild.nextSibling != null){
						var nomcapa = document.getElementById("tdhl-"+k+"-"+ind).firstChild.nextSibling.data;						
						//var nomcapa = document.getElementById(ind+"__"+k+"__layername").value;						
						var father = ind + "_" + document.getElementById(ind+"__"+k+"__father").value + "_checkbox";
						var cbx = document.createElement("INPUT");
						cbx.setAttribute("type", "checkbox");
				 		cbx.setAttribute("style", "margin-top: 3px");
				 		cbx.setAttribute("id", ind+"__"+k+"__checkbox_sublayer");
				 		cbx.setAttribute("value",nomcapa);
				 		cbx.setAttribute("disabled", "true");
				 		cbx.setAttribute((document.all ? 'className' : 'class'), "checkbox");
				 		cbx.onclick = clearFather(father);
				 		tdcb.appendChild(cbx);
				 		var tdnom = document.createElement("TD");
				 		tdnom.setAttribute("id",ind+"__"+k+"__td");
				 		tdnom.onclick = selectThisCB(ind+"__"+k,father);
				 		//var nombre = document.createTextNode(titles[k]);
				 		var nombre = document.createTextNode(nomcapa);
						tdnom.appendChild(nombre);
						tr.appendChild(tdcb);
						tr.appendChild(tdnom);
						tbody.appendChild(tr);
						table.appendChild(tbody);
						new_td.appendChild(table);
						var father = old_td.parentNode;
						father.replaceChild(new_td,old_td);
					}
					k++;
				}
			}//if (hd1 != "layerName"){
		}
	}
}

function selectThisCB(ident,father){
	return function(){
		var cbid = ident + "__checkbox_sublayer";
		if(document.getElementById(cbid).disabled == false){
			if(document.getElementById(cbid).checked == true)
				document.getElementById(cbid).checked = false;
			else
				document.getElementById(cbid).checked = true;
		}
		document.getElementById(father).checked = false;
	}
}

function selAllLayersMap(){
	var ident = this.id.substr(0,this.id.indexOf("_"));
	var m = 0;
	while(document.getElementById(ident+"__"+m+"__checkbox_sublayer") != null){
		if(document.getElementById(this.id).checked == true)
			document.getElementById(ident+"__"+m+"__checkbox_sublayer").checked = true;
		else
			document.getElementById(ident+"__"+m+"__checkbox_sublayer").checked = false;
		m++;
	}
}

function clearFather(father){
	return function(){
		document.getElementById(father).checked = false;
	}
}

function Trim(cadena){
	var cad = trim(cadena);
	while(cad.indexOf(" ")>0){
		cad = cad.replace(" ","");
	}
	return cad
}
