//----------------------------------------------------------
//	Funciones para la gestion de las consultas
//----------------------------------------------------------
function EstablecerCampoFiltroConsulta(sCampo,sValor)
{
  var aElemDes,oCampoDes,i,iLength;

  //Buscamos el campo destino
  aElemDes=document.getElementsByName(sCampo);  
  
  iLength = aElemDes.length;
  if (iLength>0)
	{ 
			
		//iLength = 1;
		for(i=0;i<iLength;i++){
			
			oCampoDes=aElemDes[i];
			
		
			// NRG 14/01/08 >> Si es una lista simulamos un evento "onfocus" para que la cargue
			if (oCampoDes.nodeName=='SELECT') {
				var status = oCampoDes.disabled;
				oCampoDes.disabled = false;
				if( document.createEvent ) 
				{ // caso mozilla
					oCampoDes.focus();
				} 
				else if( document.createEventObject ) 
				{ // caso IE
					oCampoDes.fireEvent("onfocus");
				}
				oCampoDes.disabled = status;
			}
			
			if (oCampoDes.type=='checkbox') oCampoDes.checked=(sValor=='S');
			else if (oCampoDes.type=='radio')
			{
				// AGA 04/12/2006 >> Inicialización campos radio
				for(i=0; i<aElemDes.length; i++)
				{
					oCampoDes=aElemDes[i];
					if(oCampoDes.value == sValor) oCampoDes.checked=true;
				}
			}
			else if (oCampoDes.disabled && ((oCampoDes.type=='select-one') || (oCampoDes.type=='textarea')))
			{
				// AGA 23/11/2006 >> Inicializació campo desactivado 
				// que  no se envían al hacer el submit => se replica 
				// el valor de inicialización al campo hidden paralelo
				EstablecerValorCampo(oCampoDes.form, sCampo, sValor, '=');
				aElemDes[1].value = sValor;
			}
			else EstablecerValorCampo(oCampoDes.form, sCampo, sValor, '=');
		
		}
		
		
	}
	else if(sCampo.substring(0,4) == 'FIL_')
	{
		// No hemos encontrado el campo FIL_WTX... quizás es un campo informativo
		EstablecerCampoFiltroConsulta('INF_' + sCampo.substring(4),sValor);
	}
}



function GestionarEnlaceAccion(sEnlace,sIdAccion,iVentana,iWidth,iHeight,iHTTPS)
{
	var aElementos,i,sIdFila;

	//Buscamos la fila seleccionada
	sIdFila='';
	aElementos=document.getElementsByName('WTGSELECC');
	for(i=0;i<aElementos.length;i++)
	{
		if (aElementos[i].checked)
		{
			sIdFila=aElementos[i].value;
			break;
		}
	}

	//Comprobamos si hay alguna fila seleccionada
	if (sIdFila.length>0)
	{
		GestionarEnlaceAccionFila(sEnlace,sIdAccion,sIdFila,iVentana,iWidth,iHeight,iHTTPS);
	}
	else
	{
		alert(strSeleccionarFila);
	}
}

function GestionarEnlaceAccionFila(sEnlace,sIdAccion,sIdFila,iVentana,iWidth,iHeight,iHTTPS)
{
	var oCampo,aRelServicio,aParejaRel,sValor,oFormLink,oCampoOculto,i,oVentana,sNombreVentana,iTop,iLeft,sFeatures,aParams;

  
	//Buscamos el formulario que utilizaremos para simular un link y le quitamos todos los campos que tenga.
	oFormLink=document.getElementById('frmLink');
	while (oFormLink.childNodes.length>0)
		oFormLink.removeChild(oFormLink.childNodes.item(0));

	//Buscamos la relacion de campos con el servicio de este enlace
	oCampo=document.getElementById(sIdAccion);
  if ((oCampo!=null) && (oCampo.value.length>0))
	{
		//Por cada campo anadimos un campo oculto al formulario con su valor
		aRelServicio=oCampo.value.split('&');

		for(i=0;i<aRelServicio.length;i++)
		{
			//Buscamos el valor del campo
			aParejaRel=aRelServicio[i].split('=');
			
			//** AGA 20/09/2006: Paso de parámetros entre formularios
			// La codificación de la relación de campos entre páginas puede ser de 2 maneras:
			//  - Campos resultado consulta (sistema tradicional):
			//				En la parte derecha del igual está el nombre del campo resultado de la consulta
			//  - Parámetro (sistema nuevo):
			//				En la parte derecha del igual está el tipo de parámetro (CMP=campo o VAL=valor)
			//        y el valor (nombre del campo en el form o valor, respectivamente) separados
			// 				por la secuencia de control "|$|"

			aParams=aParejaRel[1].split('|$|');
			
			if (aParams.length == 1)
			{
				// Relación por campo resultado de consulta
				oCampo=document.getElementById(sIdFila.concat('_').concat(aParejaRel[1]));
				if (oCampo!=null) sValor=oCampo.value;
				else sValor='';
	
				//Creamos un campo oculto y lo anadimos al formulario
				oCampoOculto=document.createElement('INPUT');
				oCampoOculto.type='hidden';
				oCampoOculto.name=aParejaRel[0];
				oCampoOculto.value=sValor;
				oFormLink.appendChild(oCampoOculto);
			}
			else if (aParams.length == 2)
			{
				// Relación por parámetro
				switch(aParams[0])
				{
					case 'CMP':
						oCampo=document.getElementById(aParams[1]);
						if (oCampo!=null) sValor=oCampo.value;
						else sValor='';
						break;
					
					case 'VAL':
						sValor=URLDecode(aParams[1]);
						break;
					
					default:
						sValor='';
						break;
				}
				//Creamos un campo oculto y lo anadimos al formulario
				oCampoOculto=document.createElement('INPUT');
				oCampoOculto.type='hidden';
				oCampoOculto.name=aParejaRel[0];
				oCampoOculto.value=sValor;
				oFormLink.appendChild(oCampoOculto);				
			}
		}
	}

	//Comprobamos si el resultado hay que mostrarlo en otra ventana o no
	if ((iVentana==0) || (iVentana==1))
	{
	  // Calculamos la posicion de la ventana para que salga en el centro
		iLeft=Math.round((window.screen.availWidth-iWidth)/2);
	  if (iLeft<0) iLeft=0;
		iTop=Math.round((window.screen.availHeight-iHeight)/2);
	  if (iTop<0) iTop=0;
		if (iVentana==1) sFeatures='scrollbars=yes,resizable=yes';
		else sFeatures='menubar=yes,toolbar=yes,scrollbars=yes,resizable=yes,location=yes';
		sFeatures=sFeatures.concat(',width='+iWidth+',height='+iHeight+',left='+iLeft+',top='+iTop);

		// Abrimos la nueva ventana
		oCampo=document.getElementById('EDC_ID_VENTANA');
		if (oCampo!=null) sNombreVentana=oCampo.value;
		else sNombreVentana='EDC_link';
		oVentana=window.open('about:blank',sNombreVentana,sFeatures);
		oFormLink.target=sNombreVentana;
		oVentana.focus();
	}
	else oFormLink.target='_self';

	//Ejecutamos el link
	sEnlace=CalcularURLHTTPS(sEnlace,iHTTPS);
	oFormLink.action=sEnlace.concat('?procedencia=Consulta');
	oFormLink.submit();
}
function InicializarConsulta()
{
	try   { InicializarCampos(); }
	catch(ex) {   }
	
	InicializarSeccionesConsulta();
}


function InicializarSeccionesConsulta()
{
	 	if (typeof aSeccCons != 'undefined')
	 	{
			for (var i=0; i<iNumSeccCons; i++)
			{
				if (aSeccCons[i]['tipoSeccion'] == "busqueda")
				{
					if (aSeccCons[i]['ejecutar'] == "True")
					{
						CargarSeccionBusqueda('c' + aSeccCons[i]['id'], document.getElementById(ObtenerIdFormSeccionConsulta(aSeccCons[i]['id'])));
					}
				}
				else{
					if (aSeccCons[i]['ejecutar'] == "True")
					{
						CargarSeccionConsulta('c' + aSeccCons[i]['id'], document.getElementById(ObtenerIdFormSeccionConsulta(aSeccCons[i]['id'])));
					}
				}
			}
		}
}


function CargarSeccionConsulta(sIdConsulta, oForm)
{
  if (!oForm) return;
	// Ocultamos el área de datos y hacemos visible el GIF de carga 
	var oContainer = document.getElementById(sIdConsulta + '_data');
	// Si la sección consulta está paginada volvemos a la página inicial
	if (document.getElementById(sIdConsulta + '_data_PageActual')) document.getElementById(sIdConsulta + '_data_PageActual').value = 1;
	
	if (oContainer.tagName == 'DIV')
		oContainer.innerHTML = '<p align="center"><img src="../../css/img/loading.gif" alt="loading..." /></p>';
	/*else
	{
		// Tabla
		while (oContainer.firstChild)  { oContainer.removeChild(oContainer.firstChild); };
	
		var oRow = Builder.node('tr');
		var oCell = Builder.node('td');
		oCell.colSpan = 100;
		oRow.appendChild(oCell);
		oContainer.appendChild(oRow);
		oCell.innerHTML = '<p align="center"><img src="../../css/img/loading.gif" alt="loading..." /></p>';
	}*/
	
	if(typeof consultaRealizada!="undefined")
	{
		var getCallback= function()
		{
			consultaRealizada(sIdConsulta,oForm);
		}
		new Ajax.Updater(sIdConsulta + '_data', '../src/asp/consulta/SeccionConsulta.asp', {asynchronous:true, parameters:Form.serialize(oForm.id),onComplete : getCallback});
	}
	else
	{
		new Ajax.Updater(sIdConsulta + '_data', '../src/asp/consulta/SeccionConsulta.asp', {asynchronous:true, parameters:Form.serialize(oForm.id)});
	}

}
function CargarSeccionBusqueda(sIdConsulta, oForm)
{
	//ECA >> Función Ajax que se conectará con el WebService y devolverá los resultados  para completar los campos del formulario seleccionados para la busqueda.
			
		var urlASP= '../src/asp/consulta/SeccionBusqueda.asp';
			
		var getItemUpdate= function(resp)
			{
				var oElement;
						//Cargamos los datos del item seleccionado.
						//en el tag ul de la lista tendremos la información sobre el nombre d elos campos que componen este control ajax, para 
						//insertar la información, así como el numero de campos que existen.
					if (200 == resp.status)
					{
						var NumSubCampos, jSubCampo, sBusqSubCampos, sSubCamp;
			    		var oNode=resp;
						
						if (NavegadorIE())
						{
							oElement = oNode.responseXML.selectSingleNode('//SeccionBusq');
						}
						else 
						{//Si se abre la página con un explorador Firefox, utilizaremos el elemento XML_SeccionBusq, 
						//creado mediante el xslt en la generación de las páginas,
						//para insertar el código dentro de este elemento y poder recoger los valores de dicho XML. 
						//Esto ocurre, porque en FireFox no existen las propiedades para acceder a un XML como en explorer.
							oElement = oNode.responseXML.getElementsByTagName('SeccionBusq')[0];
						}
						
						if (oElement != null)
						{
							NumSubCampos = oForm.elements.namedItem('NUM_SUB_CAMPOS').value;
							sBusqSubCampos = oForm.elements.namedItem('RELACION_FORM_CONS').value;
							
							sSubCamp = sBusqSubCampos.split("|");
				
							for(jSubCampo=0; jSubCampo<=NumSubCampos-1; jSubCampo++)
							{
								//Guardamos la informacion de cada subcampo de la seccion.
								sBusqSubForm = sSubCamp[jSubCampo].split("-")[0];
								sBusqSubCons = sSubCamp[jSubCampo].split("-")[1];
										
								if (NavegadorIE())
								{		
									//document.getElementById(sBusqSubForm).value = oElement.selectSingleNode(sBusqSubCons).text; 
									EstablecerValorCampo(oForm,sBusqSubForm,oElement.selectSingleNode(sBusqSubCons).text,"S")
								}
								else
								{
									//document.getElementById(sBusqSubForm).value = oElement.getElementsByTagName(sBusqSubCons)[0].textContent;
									EstablecerValorCampo(oForm,sBusqSubForm,oElement.getElementsByTagName(sBusqSubCons)[0].textContent,"S")
								}
							}
							//OOF 02/12/2008 --> Miramos si esta definida la funcion asociada al retorno de la consulta (Callback) si es asi hacemos la llamada pasando
							//                              el Id de la consulta y el formulario asociado.
							if(typeof consultaRealizada!="undefined")
							{consultaRealizada(sIdConsulta, oForm)}
							
						}
						else{alert(resp.responseText); }						
					}		
					else{
					alert(strErrorSeccBusq);
					}	
			}
		 
		new Ajax.Request(urlASP, {  method: 'post', onComplete: getItemUpdate,
						onFailure: function() {alert(strErrorBusq)}, parameters: Form.serialize(oForm)});
													   
}
//ECA 14/04/2008 --> Función que recargará mediante AJAX la paginación de un elemento AJAX
function CargarSeccionConsultaPag(sIdDiv, sIdForm, PageActual)
{
	// Ocultamos el área de datos y hacemos visible el GIF de carga 
	var oContainer = document.getElementById(sIdDiv);
	var oForm = document.getElementById(sIdForm);
		if (sIdDiv.length > 37 && sIdDiv.substr(0, 1)=='c')
	 document.getElementById(sIdDiv.substr(1, 37) + '_PageActual').value  = PageActual; //Seccion consulta
  else
		document.getElementById(sIdDiv + '_PageActual').value  = PageActual;
	//alert(document.getElementById("PageActual").value);
	
	//alert(oForm.id);
	if (oContainer.tagName == 'DIV')
		oContainer.innerHTML = '<p align="center"><img src="../../css/img/loading.gif" alt="loading..." /></p>';
	else
	{
		// Tabla
		while (oContainer.firstChild)  { oContainer.removeChild(oContainer.firstChild); };

		var oRow = Builder.node('tr');
		var oCell = Builder.node('td');
		oCell.colSpan = 100;
		oRow.appendChild(oCell);
		oContainer.appendChild(oRow);
		oCell.innerHTML = '<p align="center"><img src="../../css/img/loading.gif" alt="loading..." /></p>';
	}

	new Ajax.Updater(sIdDiv, '../src/asp/consulta/SeccionConsulta.asp', {asynchronous:true, parameters:Form.serialize(oForm.id)});

}

function mostrarOcultarSeccionConsulta(sIdConsulta)
{
	// Si la consulta está oculta, se muestra
	var oSeccCons = document.getElementById(sIdConsulta);
	
	if (oSeccCons.style.display=="none")
	{
		var oDataCons = document.getElementById(sIdConsulta + '_data');

		if (oDataCons.innerHTML.indexOf('<') < 0)  //Interior vacío: No hay datos cargados
		{
			CargarSeccionConsulta(sIdConsulta, oSeccCons.getElementsByTagName('FORM')[0]);
		}
		oSeccCons.style.display="";
	}
	else
	{
		oSeccCons.style.display="none";
	}	
	
	cambiarEstilosSeccionesConsulta(oSeccCons);
	
}

function mostrarOcultarElimDupl(sIdDiv)
{
	// Si la consulta está oculta, se muestra
	var sSeccDiv = document.getElementById(sIdDiv);
	
	if (sSeccDiv.style.display=="none")
	{
		sSeccDiv.style.display="";
	}
	else
	{
		sSeccDiv.style.display="none";
	}	
}
function comprobarEstadoVisible (sAccion, sElemento)
{	

	var sStyle = document.getElementById(sElemento).style.display;	
	if (sStyle == '') sStyle = 'block';
	
	if (sStyle != sAccion)
	{
		return true;
	}
	else
	{
		return false;
	}
}
function mostrarOcultarElimDuplCapas(sElementId)
{
	// Si la consulta está oculta, se muestra
	//var sElements = document.getElementsByName(sElementName);
	var sElements = document.getElementsByName(sElementId);
	var i, oCampoDiv;
	
	if (sElements.length > 0 )
	{
		for (i = 0; i<= sElements.length - 1; i++)
		{
			oCampoDiv=sElements[i];
			
			if (oCampoDiv.style.display=="none")
			{
				oCampoDiv.style.display="";
			}
			else
			{
				oCampoDiv.style.display="none";
			}	
		}
	}
}
//JAPB 27/10/2008 --> Cambiar estilos seccionesConsulta según si la consulta está visible o no visible.
function cambiarEstilosSeccionesConsulta(oSeccion)
{

	var sContConsulta = 'cnt' + oSeccion.id.slice(1,33);	
	var oContConsulta = document.getElementById(sContConsulta);
	var sContConsultaClassName = oContConsulta.className;

	if(oSeccion.style.display=="none"){
		sContConsultaClassName = sContConsultaClassName.replace(/ desplegado/, " plegado");
		if(sContConsultaClassName.search("plegado")=="-1"){
			sContConsultaClassName = sContConsultaClassName + " plegado";
		}
	}else{
		sContConsultaClassName = sContConsultaClassName.replace(/ plegado/, " desplegado");
		if(sContConsultaClassName.search("desplegado")=="-1"){
			sContConsultaClassName = sContConsultaClassName + " desplegado";
		}
	}
	oContConsulta.className = sContConsultaClassName;
}

//JAPB 27/10/2008 --> Botones mostrar / Ocultar todas las secciones consulta
function mostrarOcultarSeccionesConsulta(sAccion, aSeccionesNoMobibles)
{
		var aSeccCons, iSeccCons, oSeccion, iSeccionesNoMobibles, bMob, oSeccionNoMobibleTemp;	
		
		aSeccCons = document.getElementsByClassName('seccCons');
		iSeccCons = aSeccCons.length;
		
		for(i=0;i<iSeccCons;i++){
			bMob = true;
			oSeccion = document.getElementById(aSeccCons[i].id);
			iSeccionesNoMobibles = aSeccionesNoMobibles.length;
			for(x=0;x<iSeccionesNoMobibles;x++){
				if(aSeccionesNoMobibles[x]==oSeccion.id){
					bMob = false;
					oSeccionNoMobibleTemp = aSeccionesNoMobibles.splice(x,1);				
				}			
			}		
			if(oSeccion && bMob){
				if(oSeccion.style.display == "none"){
					var oDataCons = document.getElementById(oSeccion.id + '_data');
					if (oDataCons.innerHTML.indexOf('<') < 0)  //Interior vacío: No hay datos cargados
						CargarSeccionConsulta(oSeccion.id, oSeccion.getElementsByTagName('FORM')[0]);
				}
				oSeccion.style.display = sAccion;	
				cambiarEstilosSeccionesConsulta(oSeccion)
			}
		}
}	

function mostrarOcultarResultadosConsulta(sAccion)
{

		var aSeccCons, iSeccCons, oSeccion;
		
		aSeccCons = document.getElementsByClassName('ResultadosOcultables');
		iSeccCons = aSeccCons.length;
		
		for(i=0;i<iSeccCons;i++){
			oSeccion = aSeccCons[i];
			oSeccion.style.display = sAccion;	
		}
		
}	
// ENLACE CON ABSVISOR: Paso de parámetros al mapa
function CargarMapaAbsVisor()
{
		var ref, claveMapa, idCapa, idEntorno, maxElems, urlVisor, urlRespuesta, targetRespuesta;
    var oFrmMapa=document.getElementById("frmLink");
    
  	while (oFrmMapa.childNodes.length>0)
			oFrmMapa.removeChild(oFrmMapa.childNodes.item(0));
    
    // Recogida de valores
    if (document.getElementById('INF_WTXREFCAT').value != '')
    	ref = document.getElementById('INF_WTXREFCAT').value.replace('-','').substr(0, 14); 
    else
    	ref = document.getElementById('INF_WTXREFPAR').value + document.getElementById('INF_WTXREFPLA').value;

		if (ref.length == 0 && window.location.search.indexOf('procedencia') >= 0)
		{
			alert(sLitRefCatIncorrecta);
			return;
		}

    claveMapa = document.getElementById('INF_WTXCLAVEM').value;
    idCapa = document.getElementById('INF_WTXIDCAPA').value;
    idEntorno = document.getElementById('INF_WTXENTORN').value;
    maxElems = document.getElementById('INF_WTXMAXELE').value;
    urlVisor = document.getElementById('INF_WTXURLVIS').value;
    
    urlRespuesta = window.location.href.substr(0, window.location.href.lastIndexOf('/')) + '/../src/asp/absVisor/RespuestaMapa.asp?css=' + document.styleSheets[1].href;
    targetRespuesta = 'frmRespuesta';
    
    // CAMPO REFERENCIA CATASTRAL
    AnadirCampoFormulario('ida', ref, oFrmMapa);

    // CAMPO CLAVE MAPA
    AnadirCampoFormulario('claveMapa', claveMapa, oFrmMapa);
    
    // CAMPO CAPA
    AnadirCampoFormulario('idCapa', idCapa, oFrmMapa);
        														 
    // CAMPO ENTORNO
    AnadirCampoFormulario('idEntorno', idEntorno, oFrmMapa);
        														 
    // CAMPO MAX ELEMS
    AnadirCampoFormulario('max_elems', maxElems, oFrmMapa);
    
    // CAMPO URL RESPUESTA
    AnadirCampoFormulario('urlRespuesta', urlRespuesta, oFrmMapa);

    // CAMPO TARGET RESPUESTA
    AnadirCampoFormulario('targetRespuesta', targetRespuesta, oFrmMapa);
    
    oFrmMapa.action=urlVisor;
		oFrmMapa.target = 'frmVisor';
		
    oFrmMapa.submit();
    
   	while (oFrmMapa.childNodes.length>0)
			oFrmMapa.removeChild(oFrmMapa.childNodes.item(0));

    AnadirCampoFormulario('ida', ref, oFrmMapa);
    oFrmMapa.action=urlRespuesta;
		oFrmMapa.target = targetRespuesta;
    oFrmMapa.submit();
}
   
function AnadirCampoFormulario(sNombre,sValor,oForm)
{
    var oCampo=document.createElement('INPUT');
		oCampo.type='hidden';
		oCampo.name=sNombre;
		oCampo.value=sValor;
		oForm.appendChild(oCampo);
}



function ObtenerIdFormSeccionConsulta(sIdConsulta)
{
  if (document.getElementById(sIdConsulta + '_IdForm'))
	 return document.getElementById(sIdConsulta + '_IdForm').value;
	else
	 return '';
/* 	if (typeof aSeccCons != 'undefined')
 	{
		for (var i=0; i<iNumSeccCons; i++)
		{
			if (aSeccCons[i]['id'] == sIdConsulta)
			{
				return aSeccCons[i]['id_form'];
			}
		}
 	}
*/ 	
}

//JAPB 03/10/2008 --> Marcar fila de resultados secciones consulta tipo tabla con seleccion
function marcarFila(oTd){
	var aMarcados, iMarcadoslength;
	if(oTd){
		//Buscamos los elementos marcados
		aMarcados = document.getElementsByClassName("selected");
		if(aMarcados)
			iMarcadoslength = aMarcados.length;
		
		for (i=0;i<iMarcadoslength;i++){
			if(aMarcados[i].nodeName == 'TR')
				aMarcados[i].className = aMarcados[i].className.replace(/ selected/, "");	
		}

		//Marcamos el elemento acual como seleccionado
		if(oTd && oTd.parentNode && oTd.parentNode.parentNode && oTd.parentNode.parentNode.nodeName == 'TR'){
			oTd.parentNode.parentNode.className = oTd.parentNode.parentNode.className + " selected";
		}
	}
}
