//////////////////////////////////////////////////////////////////////////////////////////
// absEdiForm.js
//////////////////////////////////////////////////////////////////////////////////////////
function clickHandler(oEvent,targetId) 
{
	oElem=document.getElementById(targetId);
	if (oElem!=null)
  {
	  if (oElem.style.display == "") oElem.style.display = "none";
	  else oElem.style.display = "";
	}
	if (NavegadorIE())
	{
    oEvent.cancelBubble = true;
	  oEvent.returnValue = false;
	}
	else
	{
		oEvent.stopPropagation(); 
		oEvent.preventDefault();
	}
}

function clickHandlerCheck(oEvent,targetId,checkId) 
{
	oElem=document.getElementById(targetId);
	oElemCheck=document.getElementById(checkId);
	if (oElem!=null)
	{
	  if (oElemCheck.checked == false) 
	  {
		oElem.style.display = "none";
	  }
	  else
	  {
	    oElem.style.display = "";
	  }
	  TratarDatosSolicitante(oElemCheck.checked)
	}

}

function TratarDatosSolicitante(bTratar)
{
	var oSolicitante, oRepresentante;
	var oSolicitante2, oRepresentante2;		
	//Nombre
	oSolicitante = ObtenerObjetoControl('WTGNOMBRE', 'WTXNOMBRE');
	oRepresentante = document.getElementById('WTXIPRNOM');
	EstablecerComportamientoControles(oSolicitante, oRepresentante, bTratar);
	
	//Primer apellido
	oSolicitante = ObtenerObjetoControl('WTGAPELL1','WTXAPELL1');
	oRepresentante = document.getElementById('WTXIPRAP1');
	EstablecerComportamientoControles(oSolicitante, oRepresentante, bTratar);
	
	//Segundo apellido
	oSolicitante = ObtenerObjetoControl('WTGAPELL2','WTXAPELL2');	
	oRepresentante = document.getElementById('WTXIPRAP2');
	EstablecerComportamientoControles(oSolicitante, oRepresentante, bTratar);
	
	//Razón social
	oSolicitante = ObtenerObjetoControl('WTXIPSRAS','WTXRSDSOL'); //OMC  23/05/2008
	oRepresentante = document.getElementById('WTXRSDREP');
	EstablecerComportamientoControles(oSolicitante, oRepresentante, bTratar);	
	
	//Tipo de documento	
	oSolicitante = ObtenerObjetoControl('WTXIPSTDO', 'WTXIPSTDO'); // OMC 11/03/2008
	oRepresentante = ObtenerObjetoControl('WTXREPTDO', 'WTXIPRTDO'); // JRC 14/07/2010
	EstablecerComportamientoControles(oSolicitante, oRepresentante, bTratar);
	
	//Numero de documento 
	oSolicitante = ObtenerObjetoControl('WTGNUMDOC','WTXNUMDOC');
	oRepresentante = document.getElementById('WTXREPNDO');//OMC 11/03/2008
	if (oRepresentante == null)
	oRepresentante = document.getElementById('WTXIPRDNI');//OOF 27/02/2009 -> En ocasioens este campo tiene otro nombre
	EstablecerComportamientoControles(oSolicitante, oRepresentante, bTratar);
	
	//Letra del documento
	oSolicitante = ObtenerObjetoControl('WTXLETDNI','WTXLETDNI');
	oRepresentante = document.getElementById('WTXLDNIRE');//OMC 11/03/2008
	EstablecerComportamientoControles(oSolicitante, oRepresentante, bTratar);
	
	//Tipo de via
	oSolicitante = ObtenerObjetoControl('WTXIPSDO0','WTXIPSTDO0');
	oRepresentante = document.getElementById('WTXIPRDO0');
	EstablecerComportamientoControles(oSolicitante, oRepresentante, bTratar);
	
	//Nombre de la via
	oSolicitante = ObtenerObjetoControl('WTXIPSDO1','WTXIPSDO1');
	oRepresentante = document.getElementById('WTXIPRDO1');
	EstablecerComportamientoControles(oSolicitante, oRepresentante, bTratar);
		
	//Numero
	oSolicitante = ObtenerObjetoControl('WTXIPSDO2','WTXIPSDO2');
	oRepresentante = document.getElementById('WTXIPRDO2');
	EstablecerComportamientoControles(oSolicitante, oRepresentante, bTratar);
	
	//Bloque
	oSolicitante = ObtenerObjetoControl('WTXIPSDO3','WTXIPSDO3');
	oRepresentante = document.getElementById('WTXIPRDO3');
	EstablecerComportamientoControles(oSolicitante, oRepresentante, bTratar);
	
	//Escalera
	oSolicitante = ObtenerObjetoControl('WTXIPSDO4','WTXIPSDO4');
	oRepresentante = document.getElementById('WTXIPRDO4');
	EstablecerComportamientoControles(oSolicitante, oRepresentante, bTratar);
	
	//Planta
	oSolicitante = ObtenerObjetoControl('WTXIPSDO5','WTXIPSDO5');
	oRepresentante = document.getElementById('WTXIPRDO5');
	EstablecerComportamientoControles(oSolicitante, oRepresentante, bTratar);
	
	//Puerta
	oSolicitante = ObtenerObjetoControl('WTXIPSDO6','WTXIPSDO6');
	oRepresentante = document.getElementById('WTXIPRDO6');
	EstablecerComportamientoControles(oSolicitante, oRepresentante, bTratar);
	
	//Bis
	oSolicitante = ObtenerObjetoControl('WTXIPSDO7','WTXIPSDO7');
	oRepresentante = document.getElementById('WTXIPRDO7');
	EstablecerComportamientoControles(oSolicitante, oRepresentante, bTratar);
	
	//Numero Final
	oSolicitante = ObtenerObjetoControl('WTXIPSDO8','WTXIPSDO8');
	oRepresentante = document.getElementById('WTXIPRDO8');
	EstablecerComportamientoControles(oSolicitante, oRepresentante, bTratar);
	
	//Kilometro
	oSolicitante = ObtenerObjetoControl('WTXIPSDO9','WTXIPSDO9');
	oRepresentante = document.getElementById('WTXIPRDO9');
	EstablecerComportamientoControles(oSolicitante, oRepresentante, bTratar);
	
	//Portal
	oSolicitante = ObtenerObjetoControl('WTXIPSDOA','WTXIPSDOA');
	oRepresentante = document.getElementById('WTXIPRDOA');
	EstablecerComportamientoControles(oSolicitante, oRepresentante, bTratar);
	
	//Provincia//Municipio
	oSolicitante = ObtenerObjetoControl('WTXIPSMU0','WTXIPSMN0');
	oRepresentante = document.getElementById('WTXIPRMU0');
	oSolicitante2 = ObtenerObjetoControl('WTXIPSMU1','WTXIPSMN1');
	oRepresentante2 = document.getElementById('WTXIPRMU1');
	
	EstablecerComportamientoControles(oSolicitante, oRepresentante, bTratar);
	EstablecerComportamientoControles(oSolicitante2, oRepresentante2, bTratar);
	
	//Codigo Postal
	oSolicitante = ObtenerObjetoControl('WTXIPSCPO','WTXIPSCPO');
	oRepresentante = document.getElementById('WTXIPRCPO');
	EstablecerComportamientoControles(oSolicitante, oRepresentante, bTratar);
	
	//Telefono 1
	oSolicitante = ObtenerObjetoControl('WTGTELEF1','WTXTELEF1');
	oRepresentante = document.getElementById('WTXIPRTE1');
	EstablecerComportamientoControles(oSolicitante, oRepresentante, bTratar);
	
	//Telefono 2
	oSolicitante = ObtenerObjetoControl('WTXIPSTE2','WTXIPSTE2');
	oRepresentante = document.getElementById('WTXIPRTE2');
	EstablecerComportamientoControles(oSolicitante, oRepresentante, bTratar);
	
	//Fax
	oSolicitante = ObtenerObjetoControl('WTXNUMFAX','WTXNUMFAX');
	oRepresentante = document.getElementById('WTXIPRFAX');
	EstablecerComportamientoControles(oSolicitante, oRepresentante, bTratar);
	
	//Direccion electronica
	oSolicitante = ObtenerObjetoControl('WTGDIRMAI','WTXDIRMAI');
	oRepresentante = document.getElementById('WTXIPRDEM');
	EstablecerComportamientoControles(oSolicitante, oRepresentante, bTratar);

	//CIF
	oSolicitante = ObtenerObjetoControl('WTXIPSCIF','WTXIPSCIF');
	oRepresentante = document.getElementById('WTXIPRCIF');
	EstablecerComportamientoControles(oSolicitante, oRepresentante, bTratar);

}

function ObtenerObjetoControl(sNombreCtl, sNombreAux)
{
	var oControl;
	oControl = document.getElementById(sNombreCtl);
	if ((oControl == null)&&(sNombreAux != '')){
		oControl = document.getElementById(sNombreAux);
	}
	return oControl;
}

function EstablecerComportamientoControlesMulti(oSol1,oRep1,oSol2,oRep2, bTratar)
{
	var oValor;
	if ((oRep1!=null)&&(oRep2!=null)&&(oSol1!=null)&&(oSol2!=null)){
		if (bTratar){
			// Check marcada
		
			//alert("Tipo Control Sol1: " + oSol1.tagName + "    Title del control: " + oSol1.title + "  Contenindo del control: " + oSol1.value + " \nTipo Control Sol2: " + oSol2.tagName + "    Title del control: " + oSol2.title + "  Contenindo del control: " + oSol2.value + "\nTipo Control Rep1: " + oRep1.tagName + "    Title del control: " + oRep1.title + "  Contenindo del control: " + oRep1.value + "\nTipo Control Rep2: " + oRep2.tagName + "    Title del control: " + oRep2.title + "  Contenindo del control: " + oRep2.value);
            var sSol1Seleccionada=oSol1.value.split("-"); //OMC 12/03/2008
            var sSol2Seleccionada=oSol2.value.split("-"); //OMC 12/03/2008
		
            oRep1.options[1]=new Option(sSol1Seleccionada[1],oSol1.value); //OMC 12/03/2008
            oRep2.options[1]=new Option(sSol1Seleccionada[2],oSol2.value); //OMC 12/03/2008
            oRep1.selectedIndex=1;                                //OMC 12/03/2008
            oRep2.selectedIndex=1;                                //OMC 12/03/2008
			
            			
			oValor = (oSol2.value.length - 1) - (oSol2.value.lastIndexOf('-'));
			if ((oSol1.value.length > 0)&&(oValor > 0)){
				if (typeof aDinCmp[oRep1.id] == "undefined")
          LlenarListaAsociada(oRep2,'_LPRO',oRep1,false,false);
				oRep2.value = oSol2.value;
			}			
			
			if (oSol1.readOnly==true) opt.readOnly = true;	// enlloc de opt es oRep1.
			if (oSol2.readOnly==true) oRep2.readOnly = true;	
			oSol1.readOnly = false;
			oSol2.readOnly = false;
		}
		else{
			// Check desmarcada
			oSol1.value = oRep1.value;
			oValor = (oRep2.value.length - 1) - (oRep2.value.lastIndexOf('-'));
			if ((oRep1.value.length > 0)&&(oValor > 0)){
	      if (typeof aDinCmp[oSol1.id] == "undefined")  
  				LlenarListaAsociada(oSol2,'_LPRO',oSol1,false,false)
				oSol2.value = oRep2.value;
			}
			oRep1.value = '';
			oRep2.value = '';
			
			if (oRep1.readOnly==true) oSol1.readOnly = true;	
			else oSol1.readOnly = false;	
			if (oRep2.readOnly==true) oSol2.readOnly = true;	
			else oSol2.readOnly = false;	
			oRep1.readOnly = false;
			oRep2.readOnly = false;
		}
	}
}

function EstablecerComportamientoControles(oSolicitante, oRepresentante, bTratar)
{
	if ((oSolicitante!=null)&&(oRepresentante!=null)){
		// Existe el campo en los dos apartados "datosSolicitante" y "datosRepresentante".
		if (bTratar){ 
			// Check marcada
			if (oSolicitante.tagName != "SELECT" || oRepresentante.tagName != "SELECT"){ //OMC 12/03/2008
			    //Si no és una SELECT. //OMC 12/03/2008
			    oRepresentante.value = oSolicitante.value;
			    oSolicitante.value = '';
			}else{ //OMC 12/03/2008
			    //Si és una SELECT. //OMC 12/03/2008
						EliminarElementosSubListaMenosBlanco(oRepresentante);
						for (var j=0; j<oSolicitante.options.length; j++)
						{
							if(oSolicitante.options[j].value != '')
							{
								oOption = document.createElement("OPTION");
								oOption.text=oSolicitante.options[j].text;
							  oOption.value=oSolicitante.options[j].value;
      					if(NavegadorIE()) oRepresentante.add(oOption);
					      else oRepresentante.appendChild(oOption);     					
							}
						}
						oRepresentante.value= oSolicitante.value;
						oSolicitante.options.length = 0;

			} //OMC 12/03/2008
			
			if (oSolicitante.readOnly==true){
				oRepresentante.readOnly = true;	
			}
			oSolicitante.readOnly = false;
		}
		else{
			// Check desmarcada
			if (oSolicitante.tagName != "SELECT" || oRepresentante.tagName != "SELECT"){ //OMC 12/03/2008
			//Si no és una SELECT. //OMC 12/03/2008
			oSolicitante.value = oRepresentante.value;
			oRepresentante.value = '';
			if (oRepresentante.readOnly==true){
				oSolicitante.readOnly = true;	
			}
			else{
				oSolicitante.readOnly = false;	
			}
			oRepresentante.readOnly = false;
			}else{
			//Si és una SELECT. //OMC 12/03/2008
						EliminarElementosSubLista(oSolicitante);
						for (var j=0; j<oRepresentante.options.length; j++)
						{
							if(oRepresentante.options[j].value != '')
							{
								oOption = document.createElement("OPTION");
								oOption.text=oRepresentante.options[j].text;
								oOption.value=oRepresentante.options[j].value;
								if(NavegadorIE()) oSolicitante.add(oOption);
					      else oSolicitante.appendChild(oOption);   
							}
						}
						oSolicitante.value = oRepresentante.value;
						oRepresentante.options.length = 0;
			
			 //OMC 12/03/2008	
		}
	 }
	}
	else{
		// Puede que exista el campo en alguno de los apartados o puede que no.
		if ((oSolicitante!=null)&&(bTratar)) oSolicitante.value='';
		if ((oRepresentante!=null)&&(!bTratar)) oRepresentante.value='';
	}
}



function ValidarDatos(){
	var coll = document.all;
	if (coll!=null) {
	    for (i=0; i<coll.length; i++) 
	        alert(coll.item(i).tagName);
	}
}

/*
	FUNCION QUE DEVUELVE EL NUMERO DE FICHEROS ADJUNTOS AL TRAMITE
*/
function numAdjuntos(theForm)
{
	//*** OOF 22/05/8
	var input;
	var i = 0;
	var numadjuntos = 0;
	var idAdjunto = parseInt(-1);

	if (theForm.name != ""){
		input = document.getElementById(theForm.id).getElementsByTagName("input");
		while(i<input.length){
			if (input[i].type=="hidden" && (input[i].id.substring(0,10)=="fileAttach" || input[i].name.substring(0,10)=="fileAttach"))
			{
					//miro si es un numero pq hay unos campos fileAttachFirmaXX
					if (!isNaN(input[i].name.substring(10))){
						if (idAdjunto != parseInt(input[i].name.substring(10))){
							numadjuntos ++;
							idAdjunto = parseInt(input[i].name.substring(10));
						}
					}
			}
			i++;
		}
	}
return numadjuntos;
}

function comprobarMinimoFicherosAdjuntos(theForm, cmpMinArchivos){

	//******
	//Comprobación del número mínimo de documentos adjuntos:
	var numFicAdj;
	numFicAdj = numAdjuntos(theForm);
	//ya tenemos el número de ficheros adjuntos.
	//abrimos el tramite para mirar el mínimo que ha de tener 
	//minArchv podría ser un parámetro de entrada!
	var minArchv;
	minArchv = parseInt(document.getElementsByName(cmpMinArchivos)[0].value);
	
	if (numFicAdj < minArchv){
		alert(strMsgMinimoFichAdj);
		return false;
	} else{
		return true;
	}
}

function showElements(oEvent,theForm) {   

  var oCampo,value,name,sDescripcion,sTipoCampo,lLongitud,sOblig,j,bError,sMensajeError,oBtnAceptar,oBtnAtras,oSpanImg;

  
  if ((theForm != null) && (oEvent != null))
	{
	
	    //SMP 14/05/07
		if (typeof ActualizaBeforeShowError != 'undefined')
	     {		
				ActualizaBeforeShowError(theForm.id);
		 }
		//SMP 14/05/07

		oBtnAceptar=theForm['btnAceptar'];
		oBtnAtras=theForm['btnAtras'];
		if (oBtnAceptar!=null) oBtnAceptar.disabled=true;
		if (oBtnAtras!=null) oBtnAtras.disabled=true;

		value=theForm.elements[0].value;
		for (i = 0; i < theForm.length; i++) 
		{
			if ((name!=theForm.elements[i].name) && (theForm.elements[i].name != 'btn_'+name))
			{
				oCampo=theForm.elements[i];
				name=theForm.elements[i].name;
				value=theForm.elements[i].value;
				j=0;
				bError=false;
				if ((theForm.elements[i].style.color=='Red')||(theForm.elements[i].style.color=='red'))
				{
					bError=true;
					sMensajeError=strCampoIncorrectoRojo;
				}
				//** AGA 13/09/2006: Modificación para campos obligatorios en formularios de consultas
				if(name!=undefined && value!=undefined && !bError)
				{
					switch(theForm.elements[i].type.substr(0,6))
					{
						case 'select':
							if((theForm.elements[i].onblur+' ').indexOf('CampoObligatorio')>=0 && theForm.elements[i].selectedIndex<0)
							{
								bError=true;
								sMensajeError=strCampoObligatorio;
							}
							else
							{
	          			if((theForm.elements[i].onblur+' ').indexOf('CampoObligatorio')<0 && theForm.elements[i].options.length < 1)
	          			{				
	          				theForm.elements[i].options[0]=new Option("");
							theForm.elements[i].options[0].value = "";
	          				value = "";
	          			}
							}
							//** AGA 02/11/2006: Si el campo está desactivado en una consulta no se envía el valor
							//if (theForm.elements[i].disabled == true && name.substr(0,4) == 'FIL_') theForm.elements[i].disabled = false;

							break;
							
						case 'hidden':

							//** AGA: 24/10/2006 
							// Campos de tipo fecha y hora, actualizamos el valor del hidden antes de comprobar si es
							// obligatorio o no y si está vacío
							if ((name.length != 0) &&
								document.getElementById(name) && 
								document.getElementById(name + '0') && 
								document.getElementById(name + '1') && name.indexOf("fileAttach")>0)
							{
								var sNew;
								sNew = ActualizarFechaHora(theForm.elements[i].name);
								if (value != sNew && sNew.length > 0)
									value = sNew;
							}

/*						if (document.getElementById('ed_'+name) && (theForm.elements[i].onblur+' ').indexOf('CampoObligatorio')>=0 && value.length==0)
							{
								bError=true;
								sMensajeError=strCampoObligatorio;
								document.getElementById('ed_'+name).focus();
							}*/
							break;
						
						case 'textar':
							//** AGA: 14/02/2008
							// Textareas normales y campos de tipo edición HTML
							if((theForm.elements[i].onblur+' ').indexOf('CampoObligatorio')>=0)
							{
								if (theForm.elements[i].className == theForm.elements[i].name)
								{
									// Editor HTML
									var ed = tinyMCE.get(theForm.elements[i].name);
									value = ed.getContent();
									theForm.elements[i].value = value;
								}								
								else
								{
									// Textarea convencional
									if (value.length==0)
									{
										bError=true;
										sMensajeError=strCampoObligatorio;
									}
								}					
							}
						
							break;

						case 'checkb':
							if (theForm.elements[i].checked){
								theForm.elements[i].value ='S';
								value = theForm.elements[i].value;
							}
							
							if((theForm.elements[i].onblur+' ').indexOf('CampoObligatorio')>=0 && value.length==0)
							{
								bError=true;
								sMensajeError=strCampoObligatorio;
							}
							break;	
						
						default:
							if((theForm.elements[i].onblur+' ').indexOf('CampoObligatorio')>=0 && value.length==0)
							{
								bError=true;
								sMensajeError=strCampoObligatorio;
							}
							break;
						
					}
	 
	 				if (bError)
					{	
						if (oCampo.type != 'hidden' && sMensajeError == strCampoObligatorio)
						{
						    oCampo.focus();
					    	alert(sMensajeError);
						    if (typeof colorAvisoCampoVacio != 'undefined'){ //OMC 13/03/2008
						        pintaFondoCampo(oCampo)                           //OMC 13/03/2008
						    } //OMC 13/03/2008 Para activarlo en scriptCampos.js declarar a true el boolean.
						}
						
						if (oBtnAceptar!=null) oBtnAceptar.disabled=false;
						if (oBtnAtras!=null) oBtnAtras.disabled=false;
						if (NavegadorIE())
						{
							oEvent.cancelBubble = true;
							oEvent.returnValue = false;
						}
						else
						{
							oEvent.stopPropagation();
							oEvent.preventDefault();
						}
						break;
					}else{
//				    if (oCampo.type != 'hidden'){
						    if (typeof colorAvisoCampoVacio != 'undefined'){ //OMC 13/03/2008
						        pintaFondoCampo(oCampo, true)                     //OMC 13/03/2008
						    } //OMC 13/03/2008 Para activarlo en scriptCampos.js declarar a true el boolean.
//                  }					    
					}
				}
			}
			else
			{
				var iOffset;
				
				if (j==1) 
				{
					//** AGA 20/07/2006: Cuando el campo es de tipo fecha, hay un control intermedio 
					//				(el botón que desplega el calendario de selección), cosa que hace que 
					// 				el resto de datos, aparezcan una posición más allá de lo esperado.
					if (theForm.elements[i].name == 'btn_'+name)
					{
						i++;
					}
					sTipoCampo=theForm.elements[i].value;
				}
				else
				{
					if (j==2) lLongitud=theForm.elements[i].value;
					else
					{
						if (j==3) sDescripcion=theForm.elements[i].value;
						else 
						{
							if (j==5) 
							{
									if (sTipoCampo=='date')
									{
										//** AGA: 24/10/2006 
										// Campos de tipo fecha y hora, actualizamos el valor del hidden antes de comprobar si es
										// obligatorio o no y si está vacío
										var sNew;
										sNew = ActualizarFechaHora(theForm.elements[i].name);
										if (value != sNew && sNew.length > 0)
											value = sNew;
									}
							
								sOblig=theForm.elements[i].value;
								if ((theForm.elements[i].value=="not null") && ((value.length==0) || (value=="<p>&nbsp;</p>"))) //tinyMCE
								{
									// Campo obligatorio no informado
									bError=true;
									sMensajeError=strCampoObligatorio;
								}
								else
								{
									if (sTipoCampo=='date')
									{
										// Podemos tener un campo de tipo fecha o de tipo fecha y hora, los distinguimos
										// porque en este último caso tenemos dos campos auxiliares
										if (document.getElementById(theForm.elements[i].name + '0') &&
												document.getElementById(theForm.elements[i].name + '1'))

										{
											var sData, sHora;
											sData = document.getElementById(theForm.elements[i].name + '0').value;
											sHora = document.getElementById(theForm.elements[i].name + '1').value;
									
											if ((sData.length == 0 && sHora.length != 0))
											{
												// Fecha y/o hora incorrectas
												bError=true;
												sMensajeError=strCampoIncorrecto;
												document.getElementById(theForm.elements[i].name + '0').focus();
											}
											else if ((sData.length != 0 && sHora.length == 0))
											{
												// Fecha y/o hora incorrectas
												bError=true;
												sMensajeError=strCampoIncorrecto;
												document.getElementById(theForm.elements[i].name + '1').focus();
											}
											else if (sData.length > 0 && !Validar_Data(sData))
											{
												// Fecha y/o hora incorrectas
												bError=true;
												sMensajeError=strCampoIncorrecto;
												document.getElementById(theForm.elements[i].name + '0').focus();
											}
											else if(sHora.length > 0 && !Validar_Hora(sHora))
											{
												bError=true;
												sMensajeError=strCampoIncorrecto;
												document.getElementById(theForm.elements[i].name + '1').focus();										
											}
										}
										else if (!Validar_Data(value))
										{
												// Fecha incorrecta
												bError=true;
												sMensajeError=strCampoIncorrecto;										
										}
									}
									
									if ((sTipoCampo=='decimal') && (!Validar_Numero(value,lLongitud)))
									{
										// Campo numérico incorrecto
										bError=true;
										sMensajeError=strCampoIncorrecto;
									}
								}

								
								// Si se ha producido un error, mostramos un mensaje y paramos la validación
								if (bError)
								{
									if (oCampo.type != 'hidden') 
									{
										try
										{
											oCampo.focus();
										}
										catch(err)
										{}

									}
									alert(sMensajeError);
									pintaFondoCampo(oCampo, true)                     //OOF 30/10/2008
									if (oBtnAceptar!=null) oBtnAceptar.disabled=false;
									if (oBtnAtras!=null) oBtnAtras.disabled=false;
									if (NavegadorIE())
									{
										oEvent.cancelBubble = true;
										oEvent.returnValue = false;
									}
									else
									{
			  						oEvent.stopPropagation();
										oEvent.preventDefault();
									}
									break;
								}

							}
							else
							{
								if(j==9)
								{
									if (sTipoCampo == 'varchar' && theForm.elements[i].value == '|WTCESIMAG=S|')
									{
										// Validación obligatoriedad campo de tipo imagen.
										// Dado que en el valor del campo se pasan códigos de control (concretamente
										// las dimensiones de la imagen) tanto si se ha informado el campo
										// como si no, el control de obligatoriedad no funciona ya que aparentemente
										// el campo nunca está vacío.
										
										// Para ver si se ha informado el campo miramos si el campo span donde se 
										// introduce información de los adjuntos seleccionados está vacío o no.
										
										oSpanImg=document.getElementById('spanAttachText' + name);
										
										if (oSpanImg)
										{										
				
											if (sOblig == 'not null' && TrimNoTxt(oSpanImg.innerHTML)=='')
											{
												// Campo obligatorio no informado
												bError=true;
												if (sDescripcion != '')
													sMensajeError= '"' + sDescripcion + '": ' + strCampoObligatorio;
												else
													sMensajeError= strCampoObligatorio;
												
												alert(sMensajeError);
		
												document.getElementById('linkAttachImg' + name).focus();
		
												if (oBtnAceptar!=null) oBtnAceptar.disabled=false;
												if (oBtnAtras!=null) oBtnAtras.disabled=false;
												if (NavegadorIE())
												{
													oEvent.cancelBubble = true;
													oEvent.returnValue = false;
												}
												else
												{
						  						oEvent.stopPropagation();
													oEvent.preventDefault();
												}
												break;
											}
										}
									}
								}
							}
		
						}
					}
				}
			}
			j++;	
		}
		
		//SMP 14/05/07
		var HayAlgunError = false;
		if (i<(theForm.length ))
		{
		 // alert((theForm.length - 1 ) + "   " + i);
		  //SMP 10/05/07
		  HayAlgunError = true;
		  if (typeof ActualizaAfterShowError != 'undefined')
	        {		 
			  ActualizaAfterShowError(theForm.id,HayAlgunError); 
			  
			  
			 }
		
		
		}
		
			//SMP 14/05/07
		if (!bError)
		{
			if (winAttachEDF)
			{
				if (!winAttachEDF.closed) winAttachEDF.close();
			}
			// AGA >> Secciones consulta: No se envía el form, pq la petición se realiza mediante AJAX
			var bSeccConsulta = ((theForm.onsubmit + '').indexOf('return false;') >= 0)

				if (bSeccConsulta)
				{
					var TipoSecc = theForm.elements.namedItem('TIPO_SECCION').value
					if (TipoSecc == "busqueda")
					{
						CargarSeccionBusqueda('c' + theForm.elements.namedItem('ID_SECCION').value, theForm);
						// Anulamos el envío
						if (NavegadorIE())
						{
							oEvent.cancelBubble = true;
							oEvent.returnValue = false;
						}
						else
						{
							oEvent.stopPropagation();
							oEvent.preventDefault();
						}
						
						if (oBtnAceptar!=null) oBtnAceptar.disabled=false;
						if (oBtnAtras!=null) oBtnAtras.disabled=false;
					}
					else
					{
						CargarSeccionConsulta('c' + theForm.elements.namedItem('ID_SECCION').value, theForm);
						// Anulamos el envío
						if (NavegadorIE())
						{
							oEvent.cancelBubble = true;
							oEvent.returnValue = false;
						}
						else
						{
							oEvent.stopPropagation();
							oEvent.preventDefault();
						}
						
						if (oBtnAceptar!=null) oBtnAceptar.disabled=false;
						if (oBtnAtras!=null) oBtnAtras.disabled=false;
					}
				}
				else
				{
					// **********************************************************************
					// CHECK THE MINIMUN NUMBER OF ATTACHED DOCUMENTS  **********************
					// ONLY IF NECESSARY  ***************************************************
					// si existe el campo minarch
					var minArchivos = "minArchivos"
					if ( typeof document.getElementsByName(minArchivos)[0] != 'undefined')
					{
						var ficOk;
						ficOk = comprobarMinimoFicherosAdjuntos(theForm,minArchivos);
						if (!ficOk)
						{
							if (oBtnAceptar!=null) oBtnAceptar.disabled=false;
							if (NavegadorIE())
							{
								oEvent.cancelBubble = true;
								oEvent.returnValue = false;
							}
							else
							{
								oEvent.stopPropagation();
								oEvent.preventDefault();
							}
						return false;
						}
					}
					// **********************************************************************
					if (hayElementoFirma(theForm))
					{				
						if (!firmar(theForm,oEvent))
						{alert('Error Firmando');}	
						if (NavegadorIE())
						{
							oEvent.cancelBubble = true;
							oEvent.returnValue = false;
						}
						else
						{
							oEvent.stopPropagation();
							oEvent.preventDefault();
						}
					}
					else
					{			
						remplazoEuros(theForm);
						theForm.submit();
					}	
				}
		}
	}
}
function remplazoEuros(theForm)
{
	var i;
	for (i = 0; i < theForm.length; i++) 
	{
		if ((name!=theForm.elements[i].name) && (theForm.elements[i].name != 'btn_'+name))
		{		
			theForm.elements[i].value = theForm.elements[i].value.replace(/€/g,"&euro;")
		}
	}
}

function TrimNoTxt(s) 
{
	if((s==null)||(typeof(s)!='string')||!s.length)return'';
	
	return s.replace(/^\s+/,'').replace(/\s+$/,'') 
}

function generarDocumentoTramite(theForm,plantilla,nombre,firmado)
//OOF hace la llamada al metodo que genera el documento associado a este tramite
{	
	var sURL, sParams, sIdioma;	
	var value, name, oCampo;
	var sIdEntidad,sNomTab,idFile;
	
	//Obtenemos la entidad y el idioma
	if (theForm.elements.namedItem('WTGCODENT'))
	{
		sIdEntidad=theForm.elements.namedItem('WTGCODENT').value;
	}
    if (theForm.elements.namedItem('WTGIDIOMA'))
	{
		sIdioma=theForm.elements.namedItem('WTGIDIOMA').value;     
	}
	/*if (theForm.elements.namedItem('WTXTITULO'))
	{
		sIdioma=theForm.elements.namedItem('WTGIDIOMA').value;     
	}*/
	
	var inputs = "";
	for (i = 0; i < theForm.length; i++) 
	{
		if ((name!=theForm.elements[i].name) && (theForm.elements[i].name != 'btn_'+name))
		{
			oCampo=theForm.elements[i];
			name=theForm.elements[i].name;
			value=theForm.elements[i].value;
			inputs += name + "#" + value + "|"
		}
	}
	

	sParams = "sIdEntidad="+sIdEntidad+"&sNomTab="+plantilla+"&sIdioma="+sIdioma+"&sInputs="+inputs;
	sURL    = "../src/asp/selecFicheros/CreacionFicheroTramite.asp"
	
	
    idFile = makePOSTRequest(sURL, sParams);	
	var i = 0;
	var Existe = false;
	while(document.getElementsByName("fileAttach"+i).length > 0)
	{		
		if(document.getElementsByName("fileAttach"+i)[0].value == idFile)
		{
			Existe = true;
		}
		i++;
	}

	if(!Existe)
	{ 
		oCampo = crearCampoForm('INPUT','fileAttach'+i);
		oCampo.setAttribute('id','fileAttach'+i);
		oCampo.setAttribute('type','hidden');
		oCampo.setAttribute('value',idFile);				
		theForm.appendChild(oCampo)
			
		oCampo = crearCampoForm('INPUT','fileAttach'+i);
		oCampo.setAttribute('id','fileAttach'+i);
		oCampo.setAttribute('type','hidden');	
		oCampo.setAttribute('value',"0");				
		theForm.appendChild(oCampo)
			
		oCampo = crearCampoForm('INPUT','fileAttach'+i);
		oCampo.setAttribute('id','fileAttach'+i);
		oCampo.setAttribute('type','hidden');
		oCampo.setAttribute('value',plantilla+"_TRAM");				
		theForm.appendChild(oCampo)
			
		oCampo = crearCampoForm('INPUT','fileAttach'+i);
		oCampo.setAttribute('id','fileAttach'+i);
		oCampo.setAttribute('type','hidden');
		oCampo.setAttribute('value',"");		
		theForm.appendChild(oCampo)
		
			oCampo = crearCampoForm('INPUT','fileAttachFirma'+i);
			oCampo.setAttribute('id','fileAttachFirma'+i);
			oCampo.setAttribute('type','hidden');
		if(firmado)
		{
			oCampo.setAttribute('value',"true");	
		}
		else
		{
			oCampo.setAttribute('value',"true");	
		}
		theForm.appendChild(oCampo)
	}
	 
}

function FormatearDecimal(sValue, iNumDecimales)
//ARL 10/10/06 >> Formatea sValue al número de decimales indicado, añadiendo ceros al final si hace falta
{
	var sParteEntera = "";
	var sParteDecimal = "";
	var aDecimal = new Array();
	var k;
	
	iNumDecimales = parseInt(iNumDecimales);
	if (iNumDecimales > 0)
	{
		if ( (sValue.indexOf(',')==-1) && (sValue.indexOf('.')==-1) )
		{
			//Solo se ha indicado parte entera. Rellenamos la parte decimal con tantos 0's como la longitud del campo indique
			sParteEntera = sValue;
			
			if (sParteEntera == "")
			{sParteEntera = "0";}
			
			for (k=0; k<iNumDecimales; k++)
			{sParteDecimal += "0"}
		}
		else
		{
			
			sValue = sValue.replace(",",".");
			aDecimal = sValue.split('.');
			sParteEntera = aDecimal[0];
			
			if (sParteEntera == "")
			{sParteEntera = "0";}
				
			if (aDecimal.length > 1)
			{sParteDecimal = aDecimal[1];}
			iNumDecimales = iNumDecimales - sParteDecimal.length;
			for (k=0; k<iNumDecimales; k++)
			{sParteDecimal += "0"}
			
			
		}
		if ( (sParteEntera!="") && (sParteDecimal!="") )
		//Forzamos que el separador decimal sea una coma. En la intratramites, al comprobar la firma, tambien lo forzaremos. De
		//esta forma se evitar problemas debido a configuraciones regionales diferentes
			sValue = sParteEntera + '.' + sParteDecimal;

	}

	return sValue;

}

//--------------------------------------------------
//	Mascara per escriure dates
//	Només permet dígits i '/'.
//  Invocar desde 'onKeyPress'.
//--------------------------------------------------
function MascaraData(oEvent,oText){
	var iNumero,iKeyCode,sData;

  	// Obtenemos el código de la tecla
	//if (oEvent.keyCode) iKeyCode=oEvent.keyCode;
  	//else iKeyCode=oEvent.which;
	
	// JAPB 23/05/2008 Obtenemos la tecla pulsada segun el navegador
	iKeyCode = ObtenerTeclaPulsada(oEvent);		
	
  	// EDR 10-07-2006 >>> se ha adaptado el script para que contemple campos fecha y hora
  	sDataHora = oText.value.split(" "); //0:Data  1:Hora
  	//sData = oText.value.split("/"); //0:Dia  1:Mes  2:Any
	sData = sDataHora[0].split("/"); //0:Dia  1:Mes  2:Any

	//Tractament de la longitud
	//Caràcters no permesos
	//if((iKeyCode<47)||(iKeyCode>57))
	if((iKeyCode<47)||(iKeyCode>57))
  	{
		if (!TeclaFuncional(iKeyCode) || iKeyCode==46 || iKeyCode==44) iKeyCode=-1;
  	}
	else{
		//Barra
		if(iKeyCode==47){
			if((oText.value.length!=1)&&(oText.value.length!=2)&&
			   (oText.value.length!=4)&&(oText.value.length!=5))
					iKeyCode=-1;
			else{
				//Tractament d'un sol dígit.  Ex.: '3/' -> '03/'
				if(oText.value.length==1) 
					if(sData[0]==0) iKeyCode=-1;
					else oText.value="0"+oText.value;
				else if(oText.value.length==4)
					if(sData[1]==0) iKeyCode=-1;
					else oText.value=sData[0]+"/0"+sData[1];
			}
		}
		//Número
		else{ 
			//Barra automàtica
			if((oText.value.length==2)||(oText.value.length==5))
					oText.value=oText.value + "/";
			//Tractament de números
			iNumero=iKeyCode-48;
			switch (oText.value.length){
				case 0:  //Posició: 0 (Primer dígit de dia)
					if(iNumero>3) oText.value="0"+oText.value;		  //Ex.: '5' -> '05'
					break;
				case 1:  //Posició: 1 (Segon dígit de dia)
					if((sData[0]==0)&&(iNumero==0)) 
						iKeyCode=-1;
					else if((sData[0]==3)&&(iNumero>1))
						oText.value="0"+sData[0]+"/0";    //Ex.: '35'->'03/05'
					break;
				case 3:  //Posició: 3 (Primer dígit de mes)
					if(iNumero>1){ 
						//Restricció mesos per nº de dies (*)
						if((sData[0]==31)&&((iNumero==2)||(iNumero==4)||
						   (iNumero==6)||(iNumero==9)))
								iKeyCode=-1; 
						//Restricció mesos per nº de dies (*) 
						else if((sData[0]==30)&&(iNumero==2))
								iKeyCode=-1;
						else oText.value=sData[0]+"/0";   //Ex.:'14/5'->'14/05'
					}
					break;
				case 4:  //Posició: 4 (Segon dígit de mes)
					if((sData[1]==0)&&(iNumero==0)) 
						iKeyCode=-1;
					else if((sData[1]==1)&&(iNumero>2))
						iKeyCode=-1; 
					//Restricció mesos per nº de dies (*)
					else{
						if((sData[0]==31)&&(sData[1]==0)&&((iNumero==2)||
						   (iNumero==4)||(iNumero==6)||(iNumero==9)))
								iKeyCode=-1;
						else if((sData[0]==31)&&(sData[1]==1)&&(iNumero==1))
								iKeyCode=-1;
						else if((sData[0]==30)&&(sData[1]==0)&&(iNumero==2))
								iKeyCode=-1;
					}
					break;
				case 6:  //Posició:6 (Primer dígit d'any)
					if((iNumero==0)||((iNumero>2)&&(iNumero<6)))  //20**
						oText.value=sData[0]+"/"+sData[1]+"/20";
					else if(iNumero>=6)						      //19**
						oText.value=sData[0]+"/"+sData[1]+"/19";
					break;
				case 7:  //Posició: 7 (Segon dígit d'any)
					if((sData[2]==1)&&(iNumero<9)) iKeyCode=-1;
					break;
				//Restricció d'anys de traspàs (*)
				case 9:  //Posició: 9 (Quart dígit d'any)
					if((sData[0]==29)&&(sData[1]==2)&&
				       (!Traspas(sData[2]+iNumero))) iKeyCode=-1;
					break;
				default:
		  }
	  }
  }

	if (iKeyCode==-1)
	{	
		if(oEvent.preventDefault) 
			oEvent.preventDefault();
		else 
			oEvent.returnValue = false; 
	}
}


//--------------------------------------------------
//	Mascara per escriure hores 
//	Només permet dígits i '/'.
//  Invocar desde 'onKeyPress'.
//--------------------------------------------------
function MascaraHora(oEvent,oText)
{
	var iNumero,iKeyCode,sData;

	
	// JAPB 23/05/2008 Obtenemos la tecla pulsada segun el navegador
	iKeyCode = ObtenerTeclaPulsada(oEvent);	

  	// EDR 10-07-2006 >>> se ha adaptado el script para que contemple campos fecha y hora
	sHora = oText.value.split(":"); 


	//Tractament de la longitud
	//Caràcters no permesos
	//if((iKeyCode<47)||(iKeyCode>57))
	if((iKeyCode<48)||(iKeyCode>58))
  	{
		if (!TeclaFuncional(iKeyCode) || iKeyCode==46 || iKeyCode==44) iKeyCode=-1;
  	}

	else
	{
		//Dos punts
		if(iKeyCode==58)
		{
			if((oText.value.length!=1)&&(oText.value.length!=2))
					iKeyCode=-1;
			else{
				//Tractament d'un sol dígit.  Ex.: '3:' -> '03:'
				if(oText.value.length==1) 
				{
					if(sHora[0]==0) iKeyCode=-1;
					else oText.value="0"+oText.value;
				}
//				else if(oText.value.length==4)
//					if(sHora[1]==0) iKeyCode=-1;
//					else oText.value=sHora[0]+":0"+sHora[1];
			}
		}
		//Número
		else{ 
			//Dos punts automàtics
			if(oText.value.length==2)
					oText.value=oText.value + ":";
			//Tractament de números
			iNumero=iKeyCode-48;
			switch (oText.value.length)
			{
				case 0:  //Posició: 0 (Primer dígit de hora)
					if(iNumero>2) oText.value="0"+oText.value;		  //Ex.: '5' -> '05'
					break;
				case 1:  //Posició: 1 (Segon dígit de hora)
					if((sHora[0]>=2)&&(iNumero>=4))
						oText.value="0"+sHora[0]+":0";    //Ex.: '35'->'03:05'
					break;
				case 3:  //Posició: 3 (Primer dígit de minuts)
					if(iNumero>5)
						oText.value=sHora[0]+":0";   //Ex.:'14:6'->'14:06'
					break;
			}
		}
	}

	if (iKeyCode==-1)
	{	
		if(oEvent.preventDefault) 
			oEvent.preventDefault();
		else 
			oEvent.returnValue = false; 
	}
  
}


function TeclaFuncional(iKeyCode)
{
	if ((iKeyCode==8) || (iKeyCode==9) || (iKeyCode==46) || (iKeyCode==37) || (iKeyCode==39) || (iKeyCode==36) || (iKeyCode==35))
		return true;
  	else return false;
}


function tratarOcultar(id){
	if (document.getElementById)
	{ 
		var oEle = document.getElementById(id); 
		oEle.style.display = (oEle.style.display == 'none') ? 'block' : 'none'; 
	}
}
//--------------------------------------------------
//	Funció que canvia el color del texte depenent
//	de si té o no un format de data correcte.
//  Invocar desde 'onBlur'.
//--------------------------------------------------
function SortirData(oText,ColorCorrecte,ColorErroni){

//alert('sortirdata:' + oText.value.length);
	if ((oText.value.length==0) || (Validar_Data(oText.value)))
	{ 
		oText.style.color=ColorCorrecte; 
		return(true); 
	}
	else
	{ 
		oText.style.color=ColorErroni; 
		return(false); 
	}
}

function SortirHora(oText,ColorCorrecte,ColorErroni){

		sHora = oText.value.split(":"); //0:Hores  1:Minuts  

		//Si sólo hay los dígitos de la hora, añadimos los minutos a 00
		if(sHora.length==1) 
		{ 
			//Tractament de l'hora
			if (parseInt( sHora[0]) >= 24 ) iHora ='00';
		  	else if(sHora[0].length==1) iHora="0" + sHora[0];
			else iHora=sHora[0];
			
			if (iHora.length > 0)
				oText.value = iHora + ":00"
		}	


	if ((oText.value.length==0) || (Validar_Hora(oText.value)))
	{ 
		oText.style.color=ColorCorrecte; 
		return(true); 
	}
	else
	{ 
		oText.style.color=ColorErroni; 
		return(false); 
	}
}



//--------------------------------------------------
//	Mascara per comprovar que una data és correcte.
//	Només permet dígits i '/'.
//--------------------------------------------------
function Validar_Data(sData){
   var bTraspas;
   var dataTrans;

if (sData == '') return true;

  dataTrans=Transformar_Data(sData);
   
  // IHR 04-08-2006 >>> se ha adaptado el script para que contemple campos fecha y hora

  if (dataTrans != ''){
	tmpData = dataTrans.split(" "); // 0:Data 1:Hora
  	sData = tmpData[0].split("/"); //0:Dia  1:Mes  2:Any
  	if (tmpData.length!=1) sHora = tmpData[1].split(":"); //0:Hores  1:Minuts  2:Segons
  	else sHora = '';
  }
  else
  	return false;
	  
  //Si és buit o null retornem true
  if(sData)
  {
    if(sData.length!=0)
    {
    	//Comprovació del nombre de camps
    	if(sData.length!=3)
    	{
    		return(false); 
    	}
    	else
    	{ 
    		//Comprovació de la longitud dels camps
    		if((sData[0].length!=2)||(sData[1].length!=2)||(sData[2].length!=4))
    		{
    			return(false);
    		}
    		//Tractament d'any
    		if((sData[2]<1900)||(sData[2]>2100))
    		{
    			return(false); 
    		}
    		else
    		{ 
    			if ((sData[1]<1)||(sData[1]>12)){
    				return(false);
    			}
    			else
    			{
	    			//Tractament de mes(amb 31 dies)
    				if((sData[1]==1)||(sData[1]==3)||(sData[1]==5)||(sData[1]==7)||
    				   (sData[1]==8)||(sData[1]==10)||(sData[1]==12))
    				{
    					if((sData[0]<1)||(sData[0]> 31))
	    				{
    						return(false);
    					}
    				} 
	    			//Tractament de mes (amb 30 dies) 
    				else if((sData[1]==4)||(sData[1]==6)||(sData[1]==9)||(sData[1]==11))
    				{
    					if((sData[0]<1)||(sData[0]>30))
    					{
    						return(false);
	    				}
    				}
    				//Tractament de Febrer (28 o 29 dies)
    				else if(sData[1]==2)
	    			{
    					bTraspas=Traspas(sData[2]);
    					if((bTraspas)&&((sData[0]<1)||(sData[0]>29)))
    					{ 
    						return(false);
	    				}
    					else if((!bTraspas)&&((sData[0]<1)||(sData[0]>28))) 
    					{
    						return(false);
    					}
    				}
    			}
    		}
    	}
    }
  }
  return(true);
}

//--------------------------------------------------
//	Mascara per comprovar que una hora és correcta.
//	Només permet dígits i '/'.
//--------------------------------------------------
function Validar_Hora(sHora){
	var bTraspas;
	var horaTrans;
	horaTrans=Transformar_Hora(sHora);
  
	if (horaTrans != '')
  		return(true);
	else
		return false;
}

//--------------------------------------------------
//	Funció que donada una data en format incorrecte
//	la transforma correctament.
//--------------------------------------------------
function Transformar_Data(sData){
	var iDia;
	var iMes;
	var iAny;

	// IHR 08-04-2006 >>> se ha adaptado el script para que contemple campos fecha y hora
	var iHora, iMinuts, iSegons;
	if (sData!='')
	{
		tmpData = sData.split(" "); // 0:Data 1:Hora
		sData = tmpData[0].split("/"); //0:Dia  1:Mes  2:Any
		if (tmpData.length!=1) sHora = tmpData[1].split(":"); //0:Hores  1:Minuts  2:Segons
		else sHora = '';
		//Comprovació del nombre de camps de la data
		if(sData.length!=3) return '';
		else{ 
			//Tractament de dia
			if(sData[0].length==1) iDia="0" + sData[0];
			else iDia=sData[0];
		
			//Tractament de mes
			if(sData[1].length==1) iMes="0" + sData[1];
			else iMes=sData[1];
		
			//Tractament d'any
			if(sData[2].length==2){
				if(sData[2][0]>=6) iAny="19" + sData[2];
				else iAny="20" + sData[2];
			}
			else iAny=sData[2];
		}
		if(sHora.length!=3){
			return(iDia + "/" + iMes + "/" + iAny);
		}
		else{ 
			//Tractament de l'hora
			if (parseInt( sHora[0]) > 24 ) iHora ='00';
		  	else if(sHora[0].length==1) iHora="0" + sHora[0];
			else iHora=sHora[0];
		
			//Tractament dels segons
			if (parseInt( sHora[1]) > 60 ) iMinuts ='00';
	  		else if(sHora[1].length==1) iMinuts="0" + sHora[1];
			else iMinuts=sHora[1];
			
			//Tractament dels segons
			if (parseInt( sHora[2]) > 60 ) iSegons ='00';
		  	else	iSegons=sHora[2];
		}	
		return(iDia + "/" + iMes + "/" + iAny + " " + iHora + ":" + iMinuts+ ":" +iSegons);
	}
	else
	{
		return sData;	
	}
}

//--------------------------------------------------
//	Funció que donada una hora en format incorrecte
//	la transforma correctament.
//--------------------------------------------------
function Transformar_Hora(sHora){
	var iDia;
	var iMes;
	var iAny;

	// IHR 08-04-2006 >>> se ha adaptado el script para que contemple campos fecha y hora
	var iHora, iMinuts, iSegons;
	if (sHora!='')
	{
		sHora = sHora.split(":"); //0:Hores  1:Minuts  

		//Comprovació del nombre de camps de la data
		if(sHora.length!=2) return '';
		else{ 
			//Tractament de l'hora
			if (parseInt( sHora[0]) >= 24 ) iHora ='00';
		  	else if(sHora[0].length==1) iHora="0" + sHora[0];
			else iHora=sHora[0];
		
			//Tractament dels segons
			if (parseInt( sHora[1]) > 60 ) iMinuts ='00';
	  		else if(sHora[1].length==1) iMinuts="0" + sHora[1];
			else iMinuts=sHora[1];
			
		}	
		return(iHora + ":" + iMinuts);
	}
	else
	{
		return sHora;	
	}
}

//--------------------------------------------------
//  Funció que retorna la data actual
//  Invocar desde 'onFocusIn'
//--------------------------------------------------
function FechaActual(oText)
{
  var d,s;
  if (oText.value.length==0)
  {
    d=new Date();
    s = d.getDate() +  "/" +  (d.getMonth()+1) +  "/" +  d.getFullYear();
    oText.value=Transformar_Data(s);
  }
}

//--------------------------------------------------
//  Funcion que devuelve la fecha y hora actual
//  Invocar desde 'onFocusIn'
//--------------------------------------------------
function FechaHoraActual(oText)
{
  var d,s;
   
  if (oText.value.length==0)
  {
    d=new Date();
    // EDR 10-07-2006 >>> se ha adaptado el script para que contemple campos fecha y hora
    s = d.getDate() +  "/" +  (d.getMonth()+1) +  "/" +  d.getFullYear()+' '+d.getHours()+':'+d.getMinutes()+':'+d.getSeconds();
    oText.value=Transformar_Data(s);
  }
}

//--------------------------------------------------
//  Funcion que usada internamente para actualizar el campo fechaHora
//  Invocar desde 'onchange'
//--------------------------------------------------
function ActualizarFechaHora(sNomCampo)
{
	var oFechaHora, oFecha, oHora, sNew;
  
  oFechaHora = document.getElementById(sNomCampo);
  oFecha = document.getElementById(sNomCampo + '0');
  oHora = document.getElementById(sNomCampo + '1');
  
  sNew = "";
  
  if (oFechaHora && oFecha && oHora)
  {
  	if (oFecha.value.length == 0 && oHora.value.length == 0 )
  		sNew = "";
  	else if (oFecha.value.length == 0 && oHora.value.length != 0 )
  		sNew = '01/01/1900 ' + oHora.value + ':00';
  	else if (oFecha.value.length != 0 && oHora.value.length == 0 )
  		sNew = oFecha.value + '00:00:00';
  	else
  		sNew= oFecha.value + ' ' + oHora.value + ':00';
  		
  	if (sNew != oFechaHora.value)
	 		oFechaHora.value = sNew;
  }
  
  return sNew;
}

//--------------------------------------------------
//  Funcion que usada internamente para actualizar los campos auxiliares fecha y hora
//  Invocar desde 'onchange'
//--------------------------------------------------
function ActualizarFechaAndHora(sNomCampo)
{
  var oFechaHora, oFecha, oHora;
  
  oFechaHora = document.getElementById(sNomCampo);
  oFecha = document.getElementById(sNomCampo + '0');
  oHora = document.getElementById(sNomCampo + '1');
  
  if (oFechaHora && oFecha && oHora)
  {
  	// parsear fecha, validar y partir...
  	var sFechaHora, sHora;
  	
  	sFechaHora = oFechaHora.value.split(' ');

  	if (Validar_Data(sFechaHora[0]) && (oFecha.value != sFechaHora[0]))
  		oFecha.value = sFechaHora[0];


		if (sFechaHora.length == 2)
		{
			sHora = sFechaHora[1].split(":");

			if (sHora.length >= 2)	
			{
				sHora = sHora[0] + ':' + sHora[1];
			  	if (Validar_Hora(sHora) && (oHora.value != sHora))
		  			oHora.value = sHora;
			}			
		}
  }
}

//--------------------------------------------------
//  Funcion que devuelve la hora actual
//  Invocar desde 'onFocusIn'
//--------------------------------------------------
function HoraActual(oText)
{
  var d,s;
   
  if (oText.value.length==0)
  {
    d=new Date();
    s = d.getHours()+':'+d.getMinutes();
    oText.value=Transformar_Hora(s);
  }
}

function ObtenerTeclaPulsada(oEvent){
	var iTeclaPulsada;
 //Se ha modificado esta sección del código porque en los campos de tipo fecha en exploradores tipo Firefox no interpretaba bien la tecla Suprimir
	if(NavegadorNetscape()){
	//Mozilla y Netscape.
		if (oEvent.charCode!=0){
			iTeclaPulsada = oEvent.charCode; 
		}else{
			iTeclaPulsada = oEvent.keyCode;
			if (iTeclaPulsada==46) iTeclaPulsada=127;
		}
	}else{
	//IExplorer, GChrome y Opera.
		//confirm("Tecla pulsada en Explorer: \nKeyCode: " + oEvent.keyCode + " \nCharCode: " + oEvent.charCode + "\n¿Navegador es Opera?" + NavegadorOpera());		
		iTeclaPulsada = oEvent.keyCode;
		if (iTeclaPulsada==46 && NavegadorOpera()) iTeclaPulsada=127;
	}
	return iTeclaPulsada;
}

//--------------------------------------------------
//	Mascara per escriure números [decimals] [negatius].
//	Només permet dígits, -..
//  Invocar desde 'onKeyPress'.
//--------------------------------------------------
function Mascara_Numero(oEvent,oText,intMaxDecimals,blnNegatiu){
var intNumero,strNumero,intPosicionDecimal,bCancel;

	//if (oEvent.keyCode) intNumero=oEvent.keyCode;
	//else intNumero=oEvent.which;
	strNumero=oText.value;
	
	// JAPB 23/05/2008 Obtenemos la tecla pulsada segun el navegador
	intNumero = ObtenerTeclaPulsada(oEvent);	
	
	//Caràcters no permesos
	bCancel=false;
	
	// NRG 09/08/2008 Los caracteres con codigo 0 los permitimos, para permitir usar las flechas, el retroceso, el supr,... Si no Firefox no lo permite.
	if(intNumero != 0)
	{
		// JAPB 23/05/2008 No aceptamos el caracter /
		if((intNumero<44)||(intNumero>57) || intNumero == 47)// 47 = /
		{
			if (!TeclaFuncional(intNumero) || intNumero == 47) bCancel=true; // 47 = /
		}
		else{
			//Comprovem on està el separador decimal
			intPosicioDecimal=strNumero.search(/[,]|[.]/);
			//Signe menys (-)
			if(intNumero==45){ 
					// JAPB 23/05/2008
					// Si hay un numero ya escrito, no podemos poner un negativo [strNumero.length > 0]
					if((!(blnNegatiu)) || strNumero.length > 0)
						bCancel=true;
			} 
			//Separador decimal (,.) 
			else if((intNumero==44)||(intNumero==46)){ 
					if(intMaxDecimals>0){
						if(intPosicioDecimal>=0) bCancel=true;
					}
					else bCancel=true;
			}
			//Número
			else{ 
					if((intPosicioDecimal>=0)&&(intMaxDecimals>0)){
							//Màxim número de decimals cobert
							if(strNumero.length-intPosicioDecimal-1-intMaxDecimals>=0)	
								bCancel=true;
					}
			}
		}
	}
	
	if (bCancel) 
	{
		if (NavegadorIE()) oEvent.returnValue=0;
		else oEvent.preventDefault();
	}
}

function Validar_Numero(sNumero,lNumDecimales)
{
	var iPosNeg,iPosDec,bOk;

	iPosNeg=sNumero.indexOf("-");
	bOk=(iPosNeg<=0);

	if (bOk)
	{
		iPosDec=sNumero.indexOf(".");
		if (iPosDec==-1) iPosDec=sNumero.indexOf(",");
	
		if (iPosDec==-1) bOk=(sNumero.length<=(19-lNumDecimales));
		else bOk=(iPosDec<=(19-lNumDecimales));
	}

	return(bOk);
}


//--------------------------------------------------
//	Función para llenar el contenido de una lista
//	asociada a otra lista
//--------------------------------------------------
function LlenarListas(oSelect,oElemXML,sLista,sCodElem,bSoloListasPagina,oSelected)
{
  var oListas,oElemento,oListaElementos,oOption,sXPath,oLista,xmlHttpReq,bListaCargada,sBase,bBlanco,oBlanco, sOSelectName;

	
	bBlanco = false;

	if (oSelect.options.length >= 1)
	{
		oSelected = oSelect.value;

		if (oSelect.options[0].value == "")
		{
			bBlanco = true;
			oBlanco = oSelect.options[0].text;
		}
		
	}
	
	//oSelect.options.length = 0;	
	EliminarElementosSubLista(oSelect);


	bListaCargada=false;
	oListas=oElemXML;
	
	if (oListas!=null)
	{
			
		sXPath="e[@i='" + sCodElem + "']";
		oElemento=SelectSingleNode(oListas,sXPath);
		
		
		if (oElemento!=null)
		{
			if (oElemento.getAttribute("s")!=null)
			{
				if (('INF_'==oSelect.name.substr(0,4)) || ('FIL_'==oSelect.name.substr(0,4)))
				{
						sOSelectName = oSelect.name.substr(4,oSelect.name.length);
				}
				else
				{
						sOSelectName = oSelect.name;
				}
				sBase = sOSelectName.concat("B");
				document.getElementById(sBase).value = oElemento.getAttribute("s");
				//Comprobamos si existe la lista o hay que pedirla al servidor
				sXPath="f[@i='" + oElemento.getAttribute("s") + "']";
				if (SelectSingleNode(oListas,sXPath)==null)
				{
					
					//Hay que pedir la lista al servidor
					if (!bSoloListasPagina)
					{
						oLista = peticionListaAsincrona(oElemento.getAttribute("s"));
						oListaElementos=oLista.getElementsByTagName("e");
					}
				}
				else
				{
					//Obtenemos los elementos de la pagina
					sXPath=sXPath.concat("/e");
	        oListaElementos=oListas.selectNodes(sXPath);
				}

				//Anadimos los elementos
				if (oListaElementos!=null)
				{
					bListaCargada=true;
					EliminarElementosSubLista(oSelect);

	        for (i=0;i<oListaElementos.length;i++)
	        {
						oElemento    = oListaElementos.item(i);
						oOption      = document.createElement("OPTION");
						
						if (NavegadorIE())	oOption.text = oElemento.nodeTypedValue;
						else                oOption.text = oElemento.firstChild.nodeValue;

			
						// 14/01/08 NRG >> Si el campo es filtro solo cargamos el codigo, pq en la bd solo se guarda el codigo.
						if(oSelect.id.substr(0,4)=="FIL_")
						{
							oOption.value = oElemento.getAttribute("i");
						}
						else
						{
							//Sino cargamos codigo - descripcion
							if (NavegadorIE())	oOption.value=oElemento.getAttribute("i") + "-" + oElemento.nodeTypedValue;
							else oOption.value=oElemento.getAttribute("i") + "-" + oElemento.firstChild.nodeValue;
						}						
						oSelect.options.add(oOption);						
						if (oOption.value == oSelected)
						{
								oOption.selected = true;
								oSelect.value = oOption.value;
						}
				  }
				}
      }
    }
  }
	return(bListaCargada);
}
function peticionListaAsincrona(id)
{

		var xmlHttpReq,oLista,oListaElementos;
		if(NavegadorIE())
		{
			xmlHttpReq = new ActiveXObject("MSXML2.XMLHTTP");
			xmlHttpReq.open("GET", "../Comun/Listas.asp?id=" + id, false);
			xmlHttpReq.send("");
			if (xmlHttpReq.responseXML!=null)
			{
				oLista=xmlHttpReq.responseXML.documentElement;				
			}
		}
		else
		{
			xmlHttpReq=new XMLHttpRequest();
			xmlHttpReq.open("GET", "../Comun/Listas.asp?id=" + id, false);
			xmlHttpReq.send("");
			if (xmlHttpReq.responseXML!=null)
			{				
				oLista=xmlHttpReq.responseXML.documentElement;
			}
		}
		return oLista;
}
function SelectSingleNode(xmlDoc, elementPath)
 {
       if(NavegadorIE())
       {
           return xmlDoc.selectSingleNode(elementPath);
       }
       else
       {
          var xpe = new XPathEvaluator();
          var nsResolver = xpe.createNSResolver( xmlDoc.ownerDocument == null ? xmlDoc.documentElement : xmlDoc.ownerDocument.documentElement);
          var results = xpe.evaluate(elementPath,xmlDoc,nsResolver,XPathResult.FIRST_ORDERED_NODE_TYPE, null);
          return results.singleNodeValue; 
       }
 }

function EliminarElementosSubLista(oSelect)
{
  if (oSelect.options)
  {
  	//Eliminamos todos los elementos menos el primero que es un elemento en blanco
   	while (oSelect.options.length>1) oSelect.removeChild(oSelect.options[1]);
   	
  	if (oSelect.options.length == 1) 
  	 	if (oSelect.options[0].value != '') 
   			oSelect.removeChild(oSelect.options[0]);
  }
}

function EliminarElementosSubListaMenosBlanco(oSelect)
{
	//Eliminamos todos los elementos menos el primero que es un elemento en blanco
 	 while (oSelect.options.length>1) oSelect.removeChild(oSelect.options[1]);
 	 
	 if(oSelect.options.length == 1)
	 {
			if (oSelect.options[0].value != "") 
        oSelect.removeChild(oSelect.options[0]);
	 }
	 
	 if(oSelect.options.length == 0)
    {
         oOption = document.createElement("OPTION");
    				oOption.text='';
    			  oOption.value='';
    				if(NavegadorIE()) oSelect.add(oOption);
    	      else oSelect.appendChild(oOption);     
    }
}


function LlenarListaAsociadaOnFocus(oSelect,sLista,sElemento,bSoloListasPagina,bOrigenListaAsociada,oSelected)
{
	if (!NavegadorIE())
	{LlenarListaAsociada(oSelect,sLista,sElemento,bSoloListasPagina,bOrigenListaAsociada,oSelected);}	
}

function LlenarListaAsociadaOnMouseOver(oSelect,sLista,sElemento,bSoloListasPagina,bOrigenListaAsociada,oSelected)
{
	try
	{
		if (NavegadorIE())
		{LlenarListaAsociada(oSelect,sLista,sElemento,bSoloListasPagina,bOrigenListaAsociada,oSelected);}
	}
	catch(err)
	{}
}

function LlenarListaAsociada(oSelect,sLista,sElemento,bSoloListasPagina,bOrigenListaAsociada,oSelected)
{
		var i,oElemXML,bCargar,bListaCargada,sValor,xmlHttpReq;

		if (typeof sElemento.value != "undefined")
		{
				//Si se trata de una consulta				
				sElemento = sElemento.value;
				if (oSelect[0].tagName != "OPTION") oSelect = oSelect[0];
		}
		else
		{
				//Si se trata de un formulario
				sElemento = sElemento[0].value;
				if (oSelect[0].tagName != "OPTION") oSelect = oSelect[0];
		}

		//Buscamos la sublista asociada al elemento de la lista indicada
		bListaCargada=false;
		sValor=oSelect.value;
		sCodElem="";
		for(i=0;i<sElemento.length;i++)
		{
			if ('-'==sElemento.substr(i,1)) break;
			else sCodElem=sCodElem.concat(sElemento.substr(i,1));
		}
				
		
		oElemXML = peticionListaAsincrona(sLista);				
		if (oElemXML != null)
		{
			 bListaCargada=LlenarListas(oSelect,oElemXML,sLista,sCodElem,bSoloListasPagina,oSelected);
		}				
	    	    
	    
		if (bListaCargada)
		{ 			
			oSelect.setAttribute("bPrimeraVez","N");
			//Al cargar la pagina mantenemos el valor que tuviera la lista
			if (bSoloListasPagina) oSelect.value=sValor;
		}
		
		if( document.createEvent ) 
		{
			try
			{
				var ev = document.createEvent("HTMLEvents"); 
				ev.initEvent('change', true, true ); // event type,bubbling,cancelable
				oSelect.dispatchEvent(ev); 
			}
			catch(err)
			{
				alert(err);
			}
	} 
	else if( document.createEventObject ) 
	{
		oSelect.fireEvent("onchange");
	}
}

function Longitud(sLista)
{	
	try
	{			
		return peticionListaAsincrona(sLista).childNodes.length;			
	}
	catch(e)
	{
		return 0;
	}
}


function CargarListaMouseOver(oSelect,sLista)
{
	if (NavegadorIE())
		CargarLista(oSelect,sLista);
}
// AGD >> Cargamos todas las listas dinamicas de tipo EDC
function CargarListaHijosEDC(sCombo, sValor)
{
	var sLista;
	var oComboColec;
	sLista = sListas.split('|');
	
	for (var j=0; j<sLista.length; j++)
	{
		if (typeof aDinList[sLista[j]] != "undefined")
		{
			oComboColec = aDinList[sLista[j]]['campos'].split("|")
			for (var i=0; i<oComboColec.length; i++)
			{
				if (oComboColec[i] == sCombo)
				{	
						CargarAndLlenarComboDinamicaEDC(document.getElementById(sCombo) , sLista[j], sValor);
						return;
				}
			} 
		}
	}
}

// AGD >> Cargamos todas las listas dinamicas de tipo EDC
function CargarListasEDC()
{
	var sLista;
	var oComboColec;
	var sValor;
	
	if (typeof(sListas) != "undefined")
	{
		sLista = sListas.split('|')

		for (var j=0; j<sLista.length; j++)
		{
			if (typeof aDinList[sLista[j]] != "undefined")
			{
				oComboColec = aDinList[sLista[j]]['campos'].split("|")
				for (var i=0; i<oComboColec.length; i++)
				{
					if (aDinCmp[oComboColec[i]]['lst'] == 'EDC')
					{					
						//Solo cargamos la lista en este punto, si no depende de un campo padre 'padre' o
						//si éste ya tiene valor...
						if (aDinCmp[oComboColec[i]]['fil'] == '')
							CargarAndLlenarComboDinamicaEDC(document.getElementById(oComboColec[i]) , sLista[j], -1);
						else
						{
						   sValor = document.getElementById(aDinCmp[oComboColec[i]]['fil']).value;
	             if (sValor != '')  
	                CargarAndLlenarComboDinamicaEDC(document.getElementById(oComboColec[i]) , sLista[j], sValor.split('-')[0]);
	          }					
					}
				} 
			}
		}
	}
}

//AGD >> Nos hacen click en una lista
function CargarSubListaEDC(oSelect)
{
		var sValor;
		var oHijo;
		
	if (typeof aListaPadres != "undefined")
	{
		if (typeof aListaPadres[oSelect.id] != "undefined")
		{
				sValor = oSelect.value.split("-");
				oHijo = document.getElementById(aListaPadres[oSelect.id]);
				EliminarElementosSubListaMenosBlanco(oHijo);
				
				if (typeof sValor[0] != "undefined")
				{
				
					CargarListaHijosEDC(aListaPadres[oSelect.id], sValor[0]);
				}
				else
				{
					CargarListaHijosEDC(aListaPadres[oSelect.id], sValor);
				}
		}
	}
}

//AGD >> Cargamos las listas dinamicas de tipo EDC
function CargarAndLlenarComboDinamicaEDC(oSelect, sListaEDC, sValor)
{

	if(oSelect && aDinCmp)
	{			
		if (oSelect.value == '')
		{
			//var sLista = aDinCmp[oSelect.id]['lst'];
			var sLista = sListaEDC;
			if ((!aDinList[sLista]['cargada']) || (typeof aDinCmp[oSelect.id]['fbd'] != "undefined"))
			{
			
				EliminarElementosSubLista(oSelect);

				if (aDinCmp[oSelect.id]['fil'] != '')
				{
				
					var urlASP='../../forms_base/ListasEDC.asp?codigoWeb=' + aDinCmp[oSelect.id]['web'] + '&codigoConsulta=' + aDinCmp[oSelect.id]['met'] + '&tipo=' + aDinCmp[oSelect.id]['tpc'] + '&filtro='+aDinCmp[oSelect.id]['fbd']+'|$|'+sValor+'|$|varchar|$|1' +'&cod=' + aDinCmp[oSelect.id]['cod'] + '&des=' + aDinCmp[oSelect.id]['des'];
				}
				else
				{
					var urlASP='../../forms_base/ListasEDC.asp?codigoWeb=' + aDinCmp[oSelect.id]['web'] + '&codigoConsulta=' + aDinCmp[oSelect.id]['met'] + '&tipo=' + aDinCmp[oSelect.id]['tpc'] + '&filtro=' +'&cod=' + aDinCmp[oSelect.id]['cod'] + '&des=' + aDinCmp[oSelect.id]['des'];
				}
				
				
				var sNomCampo = oSelect.id;
				var aCampos = new Array(sNomCampo);
				var idtargetDIV='targetLst_' + sNomCampo;  
    			new Ajax.Listcompleter( sNomCampo, 
    									idtargetDIV, 
    									urlASP, new Array(), sLista, true, true, false).getValues();
    	}
	    else
	    {
	    	LlenarComboDinamica(oSelect, true);
	    }
    }
    else
    {
    	LlenarComboDinamica(oSelect, true);
    }
	}
}

function CargarLista(oSelect,sLista)
{
	var j,oElemXML,oElemento,oOption,bSelected,sIdSelected,bCargar,bBlanco,oBlanco;
	
	bSelected = true;
	bCargar = false;
	bBlanco = false;
	
	// AGA >> Problema página login/alta usuario, como hay campos con el mismo id
	// en la sección del tipo de login y en el formulario de alta, hay que acceder al de
	// esta última sección, ya que los otros son hiddens sin opciones...
	var oFormAlta = document.getElementById('frmAltaUsuario');
	if (oFormAlta && !oSelect.options) 
	{
		// buscamos el campo al que en realidad queremos acceder...
		var oListaCampos = oFormAlta.getElementsByTagName("select")
		for (var i=0; i<oListaCampos.length; i++)
		{
			if (oListaCampos[i].id == oSelect.id)
				oSelect = oListaCampos[i];
		}
	}
	
	sIdSelected = oSelect.value.split('-')[0];
	
	//OMC 15/04/2008
	var count = 1; //Contador de items de la lista que usaremos para saber cuantos tiene sin tener en cuenta el elemento por defecto " ".
	for (var i=0; i <oSelect.options.length; i++){
			if (oSelect.options[i].value ==  "" )
				count++;
	}
	if (oSelect.options.length - (count - 1) < Longitud(sLista)) 
	{
		bCargar = true;
		if ((oSelect.options[0] != null) && (oSelect.options[0].value == ""))
		{
			bBlanco = true;
			oBlanco = oSelect.options[0].innerHTML;
		}
	}
	//OMC FIN 15/04/2008
	
	if (bCargar)
	{
		//oSelect.options.length = 0;
		EliminarElementosSubListaMenosBlanco(oSelect);
		
  		  
		oElemXML = peticionListaAsincrona(sLista);
	
	   if (oElemXML!=null)
	  {
	    for (j=0;j<oElemXML.childNodes.length;j++)
					{
						oElemento=oElemXML.childNodes[j];
						if (oElemento.nodeType!=3)
						{
							
							oOption = document.createElement("OPTION");
							if (NavegadorIE()){
								oOption.text=oElemento.text;
								
								// 14/01/08 NRG >> Si el campo es filtro solo cargamos el codigo, pq en la bd solo se guarda el codigo.
								if(oSelect.id.substr(0,4)=="FIL_"){
									oOption.value=oElemento.getAttribute("i");
								}else{//Sino cargamos codigo - descripcion
									oOption.value=oElemento.getAttribute("i") + "-" + oElemento.text;
								}
								if (bSelected && oOption.value.split('-')[0] == sIdSelected)
								{
										oOption.selected = true;

								}
								oSelect.add(oOption);
								
								if (bSelected && oOption.value.split('-')[0] == sIdSelected)
								{										 
										oSelect.value = oOption.value;
										
								}
							}
							else	{
								oOption.text=oElemento.textContent;
								
								// 14/01/08 NRG >> Si el campo es filtro solo cargamos el codigo, pq en la bd solo se guarda el codigo.
								if(oSelect.id.substr(0,4)=="FIL_"){
								  oOption.value=oElemento.getAttribute("i");
								}else{//Sino cargamos codigo - descripcion
								  oOption.value=oElemento.getAttribute("i") + "-" + oElemento.textContent;
								}
								oSelect.appendChild(oOption);
								if (bSelected && oOption.value.split('-')[0] == sIdSelected)
								{
										oOption.selected = true;
										oSelect.value = oOption.value;
								}
							}
						}
					}
			
	  }
	  
	  
		if( document.createEvent ) 
		{
			var ev = document.createEvent("HTMLEvents"); 
			ev.initEvent("change", true, true); 
			oSelect.dispatchEvent(ev); 
		} 
		else if( document.createEventObject ) 
			oSelect.fireEvent("onchange");
	}
}

function CargarListaAsociada(oSelect,sLista,sElemento,bSoloListasPagina,bOrigenListaAsociada)
{
	CargarLista(oSelect,sLista);
	LlenarListaAsociada(oSelect,sLista,sElemento,bSoloListasPagina,bOrigenListaAsociada);
}

function CargarListaSub(oSelect,oSelectPrev)
{
		var sLista;

		sLista = (oSelectPrev[0].value.split("-"))[0];
		if (oSelect[0].options.length <= 2)
			CargarLista(oSelect[0],sLista);
}

function ActualizarListas()
{
	var i,aElementos,aElemAux,aListas,sName;

	//Actualizamos todas las combos y los options
  aElementos=document.getElementsByTagName("SELECT");
  for(i=0;i<aElementos.length;i++)
  {
		sName=aElementos.item(i).name;
		sName=sName.substr(0,sName.length-1) + '1';
		if (sName!=aElementos.item(i).name)
		{
			if (window.location.search.indexOf('procedencia=Confirmacion')>=0){
						(aElementos.item(i))[1].selected = true;
				}
			aListas=document.getElementsByName(sName);
			if (aListas.length>=12)
			{
				aElemAux=document.getElementsByName(aElementos.item(i).name);
				LlenarListaAsociada(aListas.item(0),aElemAux.item(aElemAux.length-1).value,aElementos.item(i).value,true,false);
			}
		}
  }
  aElementos=document.getElementsByTagName("INPUT");
  for(i=0;i<aElementos.length;i++)
  {
	  if (aElementos.item(i).type=="radio")
    {
      if (aElementos.item(i).checked)
			{
				sName=aElementos.item(i).name;
				sName=sName.substr(0,sName.length-1) + '1';
				if (sName!=aElementos.item(i).name)
				{
					aListas=document.getElementsByName(sName);
					if (aListas.length>=12)
					{
						aElemAux=document.getElementsByName(aElementos.item(i).name);
						LlenarListaAsociada(aListas.item(0),aElemAux.item(aElemAux.length-1).value,aElementos.item(i).value,true,false);
					}
				}
			}
    }
  }
}

function InicializarFormulario()
{
   try
   {
      InicializarCampos(); 

			// Si la check de representante está marcada por defecto, propagamos los datos del solicitante hacia el representante
			var oDatosRepre = document.getElementById('datosRepresentante');
			var oCheckRepre = document.getElementById('checkRepresentante');
			if  (oDatosRepre && oCheckRepre)
			{
				if (oCheckRepre.checked)
					clickHandlerCheck(null,'datosRepresentante','checkRepresentante');
			}

   }
   catch(ex)
   {
    
   }
   
  //Actualizamos las listas
  ActualizarListas();
  
}


//--------------------------------------------------
//	Funcion para verificar los digitos de control
//	de una cuenta bancaria
//--------------------------------------------------
function ValidarDigitoControlCueBan(sEntidad,sOficina,sDC,sCuenta)
{
  if ((sEntidad.length>0) && (sOficina.length>0) && (sCuenta.length>0))
  {
    sDC=FormatearCadena(sDC,2,'0');
    if (sDC!=CalcularDigitosControlCueBan(sEntidad,sOficina,sCuenta))
    {
      alert(strDCCuentaBancaria);
    }
  }
}

function CalcularDigitosControlCueBan(sEntidad,sOficina,sCuenta)
{
  var sDC,sCode,iFirstDigit,iSecondDigit;

	//Formateamos las diferentes partes de la cuenta bancaria
	sEntidad=FormatearCadena(sEntidad,4,'0');
	sOficina=FormatearCadena(sOficina,4,'0');
	sCuenta=FormatearCadena(sCuenta,10,'0');
  sCode=FormatearCadena(sEntidad+sOficina,10,'0');

	//Calculamos el primer digito
  iFirstDigit=CalcularDigitoControlCueBan(sCode);

	//Calculamos el segundo digito
	iSecondDigit=CalcularDigitoControlCueBan(sCuenta);

	//Devolvemos los digitos de control
  sDC=iFirstDigit.toString() + iSecondDigit.toString();
  return(sDC);
}

function CalcularDigitoControlCueBan(sCadena)
{
  var k,iTemp,iDigito;
	var aCoef = new Array(1, 2, 4, 8, 5, 10, 9, 7, 3, 6);

	//Calculamos el segundo digito
  iTemp=0;
  for(k=0;k<10;k++)
    iTemp=iTemp+(sCadena.substr(k,1)*aCoef[k]);
  iTemp=11-(iTemp%11);
  
  switch (iTemp)
  {
    case 10: 
			iDigito=1;
			break;
		case 11:
			iDigito=0;
			break;
		default:
			iDigito=iTemp;
  }

  return(iDigito);
}

function FormatearCadena(sCadena,iCaracteres,sCaracter)
{
  var i;

  sResultado=sCadena;
  if (sCadena.length<iCaracteres)
  {
    for(i=0;i<(iCaracteres-sCadena.length);i++) 
		{
			sResultado=sCaracter+sResultado;
		}
  }
  return(sResultado);
}

function ComprobarLongitudTexto(oTexto,lMaximo)
{
  if (lMaximo-oTexto.value.length < 0)
    oTexto.value = oTexto.value.substring(0,lMaximo);
}

function LimitarTexto(oEvent,oTexto,lMaximo)
{
  var iKeyCode;

  // JAPB 23/05/2008 Obtenemos la tecla pulsada segun el navegador
  iKeyCode = ObtenerTeclaPulsada(oEvent);
 
  if ((oTexto.value.length >= lMaximo) && (!TeclaFuncional(iKeyCode)))
  {
	  if (NavegadorIE())
	  {
      oEvent.cancelBubble=true;
	    oEvent.returnValue=false;
	  }
	  else
	  {
		  oEvent.stopPropagation();
		  oEvent.preventDefault();
	  }
  }
}

function CampoObligatorio(valor){
//  if (valor.length>0){
//  } else{
//  	alert (strInformarCampo);
//  }
}

//----------------------------------------------------------
//	Funciones para la gestión del botón de modificar
//  datos que tiene el paso de confirmación de un formulario
//----------------------------------------------------------
function ModificarDatos(oFormulario)
{
	if(oFormulario == null)
	{
		oFormulario = document.getElementsByName("frmConfirmacion").item(0);
	}
	var surl=window.document.referrer;
	var aUrl;
	aUrl=surl.split('?');
	if (aUrl.lenght>1)
		surl=aUrl[0] + '?procedencia=Confirmacion&' + aUrl[1];
	else
		surl=aUrl[0] + '?procedencia=Confirmacion';
		
	oFormulario.action=surl;
	oFormulario.submit();
}

var aCmpNoIni;

function  TieneSelected(aCampos)
{   
   var booleano = false;
   
   
   for(j=0;j<aCampos.options.length;j++)
	{
	    
	   if (aCampos.options[j].selected ) 
	   {
	      booleano= booleano || true
	   }
	
	}
   return booleano;

}


function EstablecerValorCampo(theForm,nombreCampo,valorCampo,habilitado) 
{
  var aCampos,oCampo;
  var sName,aElemAux,aListas,i, sOrden,z;
  var bValorCompuesto;
  var aListaAux, aCamposAux;
  var iLength;
  var formLogin;
  try
  {
//  alert(document.forms.length);
	//OMC 22/01/2009
	//###CASO ESPECÍFICO PARA FORMULARIOS DE ALTA DE USUARIO.
		iLength=document.forms.length;
		//Para todos los formularios que contiene la página.
		for(z=0;z<iLength;z++){
			//Los formularios que contiene la página los vamos asignando 1 a 1 dentro del FOR a la variable formLogin para tratarlos.
			formLogin = document.forms[z];
			//Comprobamos que alguno de ellos contenga en la cadena del Id al final la subString '_TABLOGIN'.
			if(formLogin.id.substr(formLogin.id.length-9)=="_TABLOGIN"){
				//En ese caso asignaremos al parámetro theForm el valor del formulario que hemos detectado como de Login. A partir de aquí el proceso del método es el mismo.
				theForm = formLogin
			}
		}
	//###FÍN CASO ESPECÍFICO PARA FORMULARIOS DE ALTA DE USUARIO.
	//OMC FIN  22/01/2009
	
	
	aCampos=window.document.getElementsByName(nombreCampo);

	iLength = aCampos.length;
	for(z=0;z<iLength;z++){	
		if(aCampos[z].form.id == theForm.id){
			oCampo=aCampos[z];
			break;
		}
	}
	
	//mantenemos la compatibilidad con el funcionamiento anterior
	if(oCampo==null && aCampos.length>0)
		oCampo=aCampos[0];
	
 	  	
  	if (oCampo!=null) 
  	{
  		
  		if (oCampo.type=='checkbox')
  		{
  			if (valorCampo=='S'){
  				oCampo.checked=true;		
				if(oCampo.disabled)
				{
					document.getElementsByName(oCampo.name)[1].value = "S";
				}				
  				if (oCampo.title==''){
					var oRep;
					oRep=document.getElementById('datosRepresentante');
					oRep.style.display='';
				}
  			}
  			else{
  				oCampo.checked=false;
  			}
  		}
  		else
  		{
  			if ((oCampo.type=='select-one') || (oCampo.type=='radio'))
  			{
					
  				bValorCompuesto=(valorCampo.indexOf('-')>0);
  			  if (oCampo.type=='select-one') 
  				{
  				
							
  						// Miramos si es una select de carga dinámica porque seguramente
  						// todavía no ha recibido los valores
  						if (typeof aDinCmp!="undefined")
  						{
  							if (aDinCmp[nombreCampo]) 	// está entre las select a llenar dinámicamente!
  							{
									
									//AGD
									if (typeof aDinList[aDinCmp[nombreCampo]['lst']] != "undefined")
									{
	  								if (aDinList[aDinCmp[nombreCampo]['lst']]['cargada'] == false )
	  								{
	  									// La lista asociada todavía no está cargada
	  									aDinCmp[nombreCampo]['val'] = valorCampo;
	  									return;
	  								}
									}
									//else
									{
									//Se trata de una EDC
										aListaAux = sListas.split("|")										
										for (var i=0;i<aListaAux.length;i++)
										{
										
											aCamposAux =  aDinList[aListaAux[i]]['campos'].split("|")
												
											for (var j=0;j<aCamposAux.length;j++)
											{
												if (aCamposAux[j] == nombreCampo)
												{													
													if (aDinList[aListaAux[i]]['cargada'] == false )
						  						{
						  								// La lista asociada todavía no está cargada
						  								aDinCmp[nombreCampo]['val'] = valorCampo;
						  								return;
						  						}
												}												
											}												
										}										
									}
  							}
  						}

  						sOrden=nombreCampo.substr(nombreCampo.length-1,1);
							if (sOrden == '0' || ((sOrden != '1') && (sOrden != '2') && (sOrden != '3') && (sOrden != '4')) ||
							 (((sOrden == '1') || (sOrden == '2') || (sOrden == '3') || (sOrden == '4')) && ((aCampos.length==11 && aCampos[0].disabled) || (aCampos.length==10 && !aCampos[0].disabled))))
							{
								CargarLista(oCampo,aCampos[aCampos.length-1].value);
							}
							
							
  				    //if (bValorCompuesto)
  				    //{
							//		oCampo.options.length = 0;
							//		EliminarElementosSubLista(oCampo);
							//		oCampo.options.add(new Option(((valorCampo.split('-'))[1]),valorCampo,true,true))
									 
  				    //}
  				    //else
  				    //{
  				      for (i=0;i<oCampo.options.length;i++)
  				      {
      						var aPartes=oCampo.options[i].value.split('-');							
									if (!bValorCompuesto)
									{
										if (aPartes[0]==valorCampo)
	      						{
	      						 	oCampo.value=oCampo.options[i].value;
	      							break;
	      						}
									}
									else
									{
										var auxValorCampo = valorCampo.split('-')
										
										if (aPartes[0]==auxValorCampo[0])
	      						{
	      						 	oCampo.value=oCampo.options[i].value;
	      							break;
	      						}
									}
      						
  				      }
  				    //}
  				}			
  				else
  				{
    					for (i=0;i<aCampos.length-1;i++)
  					{
  					  if (bValorCompuesto)
  					  {
    						if (aCampos[i].value==valorCampo)
    						{
    							aCampos[i].checked=true;
    							break;
    						}
  					  }
  					  else
  					  {
  					  	var aPartes=aCampos[i].value.split('-');    						
      						if (aPartes[0]==valorCampo)
      						{
      					    		valorCampo=aCampos[i].value;
      							aCampos[i].checked=true;
  							break;
	      					}
  					  }
  					}
  				}
  				sName=nombreCampo;
					sOrden=nombreCampo.substr(nombreCampo.length-1,1);
					switch (sOrden)
					{
						case '0':
  					sName=sName.substr(0,sName.length-1) + '1';
						break
						case '1':
  					sName=sName.substr(0,sName.length-1) + '2';
						break
						case '2':
  					sName=sName.substr(0,sName.length-1) + '3';
						break
						case '3':
  					sName=sName.substr(0,sName.length-1) + '4';
						break
					}
  				if (sName!=nombreCampo)
  				{
  					aListas=document.getElementsByName(sName);
  					if ((aListas.length>11 && aListas[0].disabled) || (aListas.length>=11 && !aListas[0].disabled))
  					{
  						aElemAux=document.getElementsByName(nombreCampo);
  						LlenarListaAsociada(aListas,aElemAux.item(aElemAux.length-1).value,aElemAux,false,false);
  					}
  				}
  			}
  			else
  			{
  				// En cualquier otro caso copiamos el valor excepto si el destino
  				// es un campo de imagen y el valor es nulo
  				if (! (valorCampo == '' && oCampo.value.split('|$|').length == 2))
  				{
					//OOF tratamiento del simbolo de euro
  					oCampo.value=valorCampo.replace(/&euro;/g,"€");
  				}
  				
  				// Navegador NO InternetExplorer: en un campo Fecha-Hora hay que inicializar explícitamente
  				// los campos auxiliares porque no se dispara el evento onpropertychange
  				if ((!NavegadorIE()) && ( (oCampo.getAttribute('onpropertychange')+'').indexOf('ActualizarFechaAndHora') >=0) )
  					ActualizarFechaAndHora(nombreCampo);
  			}
  		}
  		
  		//Si el campo no es editable y es de tipo lista,radio,checkbox o textarea, entonces ecemos su valor en el hidden
  		if (oCampo.disabled && ((oCampo.type=='select-one') || ((oCampo.type=='radio') || (oCampo.type=='checkbox') || (oCampo.type=='textarea'))))
  		{
  		  if (oCampo.type=='radio')
  		  {
  		    //Buscamos el primero que no es de tipo radio
	       for (i=0;i<aCampos.length-1;i++)
  			 {
  				  if (aCampos[i].type!='radio')
    					{    							
    							break;
    					}					  
  			 }
  			 aCampos[i].value=valorCampo;
  		  }
  		  else if (oCampo.type=='select-one')
  		  {
  		  	// Es un campo de tipo select deshabilitado originalmente con un campo adicional para guardar el texto
	  		 if (aCampos.length == 13 || aCampos.length == 11 || aCampos.length == 12 ) aCampos[1].value=oCampo.value;
  		  }
  		  else
  		  {
  		  	aCampos[1].value=oCampo.value;
  		  }
  		}
  		
  		//Habilitamos/Deshabilitamos el campo en funcion del parametro que nos pasan
  		if (habilitado=='N'){
  			oCampo.readOnly = true;
  		}
  		else if(habilitado=='S') {
  		 	oCampo.readOnly = false;
  		}
  	}	
  	else
  	{
  		// No se ha inicializado porque no se ha encontrado el campo
  		// guardamos el campo y el valor en un array por si se van a 
  		// utilizar luego...
  		
  		
  		if (!aCmpNoIni)
  			aCmpNoIni = new Array();
 			
  		aCmpNoIni[nombreCampo] = valorCampo;
 		//alert('Campo no encontrado ' + nombreCampo + ':' + aCmpNoIni[nombreCampo] + '--' + valorCampo);
  	}

  }
  catch(ex)
  {}
}


//----------------------------------------------------------
//	Funciones para la gestion de los servicios
//----------------------------------------------------------
function InicializarPaginaServicio()
{
	var i,j,aElemOri,aElemDes,oCampoDes;

	for (i=0;i<aRFSCamposDestino.length;i++)
  {
		//Buscamos el campo destino
    aElemDes=document.getElementsByName(aRFSCamposDestino[i]);
    if (aElemDes.length>0)
		{ 
			oCampoDes=aElemDes.item(0);
			//Buscamos el campo origen
			aElemOri=document.getElementsByName(aRFSCamposOrigen[i]);
			if (aElemOri.length>0)
			{
				if (oCampoDes.type=='radio')
				{
					for(j=0;j<aElemDes.length;j++)
					{
						if (aElemDes[j].type!='radio') break;
						else
						{
							aElemDes[j].checked=(aElemDes[j].value==aElemOri.item(0).value);
						}
					}
					if (oCampoDes.disabled) aElemDes[j].value=aElemOri.item(0).value;
				}
				else if (oCampoDes.type=='checkbox')
				{
					if (aElemOri.length>7) oCampoDes.checked=(aElemOri.item(0).value='S');
					else oCampoDes.checked=false;
					if (oCampoDes.disabled)
					{
						if (oCampoDes.checked) aElemDes[1].value='S';
						else aElemDes[1].value='N';
					}
				}
				else if ((oCampoDes.type=='select-one') && (oCampoDes.disabled))
				{
					oCampoDes.value=aElemOri.item(0).value;
					aElemDes[1].value=aElemOri.item(0).value;
				}
				else
					oCampoDes.value=aElemOri.item(0).value;
			}
		}
  }
}

//----------------------------------------------------------
// Permite conertir una web a PDF
//----------------------------------------------------------
function ConvertToPDF()
{
		var sEntidad,sIdioma,sNumInt,sDlg,sParametros,URL;
		
		sIdTramite = document.getElementById("IdTramite").value;  
		sIdioma = document.getElementById("WTGIDIOMA").value;  		
		sNumInt = document.getElementById("NumInt").value; 
		sEntidad = document.getElementById("WTGCODENT").value; 
		sDlg = document.getElementById("Dlg").value; 	
		
		sParametros = "sIdTramite=" + sIdTramite + "&sNumInt=" + sNumInt + "&sDlg=" + sDlg + "&sEntidad=" + sEntidad + "&Idioma=" + sIdioma;		
		URL = "../../forms_base/convertToPdf.asp?" + sParametros;				
		window.open(URL, "mywindow");		 
		
}
function getDocHeight() 
	{
		var D = document;
		return Math.max(
			Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
			Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
			Math.max(D.body.clientHeight, D.documentElement.clientHeight)
		);
	}
	function establirAlturaDoc()
	{
		var am = getDocHeight();
		document.body.style.height = am + "px";
		//alert(document.body.style.height)
	}
//----------------------------------------------------------
//	Funciones para la gestión de los botones que llaman al 
//  validador de certificados
//----------------------------------------------------------
function InvocarFormularioValidadorCertificados(oFormulario)
{
  var oCampoTipoLoginOrigen,oCampoTipoLogin;
  //Buscamos el tipo de login
	oCampoTipoLoginOrigen=oFormulario.elements.namedItem('TIPO_LOGIN');
	if(oCampoTipoLoginOrigen)
	{
	  oCampoTipoLogin=document.FormLoginCertificatDigital.elements.namedItem('tipoLogin');
	  if(oCampoTipoLogin)
	  {
	    oCampoTipoLogin.value=oCampoTipoLoginOrigen.value;
	  }
	}
	//Buscamos la clase del tipo de login
	oCampoTipoLoginOrigen=oFormulario.elements.namedItem('CLASE_TIPO_LOGIN');
	if(oCampoTipoLoginOrigen)
	{
	  oCampoTipoLogin=document.FormLoginCertificatDigital.elements.namedItem('claseTipoLogin');
	  if(oCampoTipoLogin)
	  {
	    oCampoTipoLogin.value=oCampoTipoLoginOrigen.value;
	  }
	}

  //CONTRUIM CADENA VALIDADORA DE CERTIFICATS
  var sUrlVal = document.FormLoginCertificatDigital.elements.namedItem('urlValidador').value;  
  if(sUrlVal.toLowerCase().indexOf("dlg/cer/dlgvalidarcertificado.aspx")== -1)
   {
	  if (sUrlVal.substr(sUrlVal.length-2,1)!="/")
	  {
		sUrlVal = sUrlVal + "/"
	  }   
		sUrlVal = sUrlVal + "DLG/CER/dlgValidarCertificado.aspx";
	}
	var sParamsVal = '?tipoDlg=2&atributo=NIF&atributo=Nombre&atributo=Apellido1&atributo=Apellido2&atributo=EMail&atributo=Emisor';
    if(document.getElementsByName("urliFrame")[0].value.indexOf("http://localhost",0)== -1 && document.getElementsByName("urliFrame")[0].value.indexOf("https://localhost",0)== -1 && document.getElementsByName("urliFrame")[0].value.indexOf("://127.0.0.1",0)== -1)
	{
		//SI HEM POSAT UNA URI NO LOCAL UTILITZEM METODE CROSS-DOMAIN
		sParamsVal = sParamsVal + '&urlRespuesta=' + escape(document.getElementsByName("urliFrame")[0].value);	
	}  
  
  sParamsVal = sParamsVal + '&idioma=' + document.FormLoginCertificatDigital.elements.namedItem('idioma').value
  abrirDlgCross(sUrlVal + sParamsVal,520,300, strTitAppletCert,2,'no','tratarSelecCert()');
}

function tratarSelecCert()
{
  if (typeof (m_absResDlg) == 'undefined' || m_absResDlg == null) return;
  
  if (typeof (m_absResDlg['NIF']) != 'undefined')
  {
    // Certificado seleccionado correcto
    
    // Incorporamos los datos del ciudadano al formulario
    var oCampo;
    oCampo=document.createElement('INPUT');
		oCampo.type='hidden';
		oCampo.name='NIF';
		oCampo.value=m_absResDlg['NIF'];
		document.FormLoginCertificatDigital.appendChild(oCampo);

    if (typeof (m_absResDlg['Nombre']) != 'undefined')
    {
      oCampo=document.createElement('INPUT');
  		oCampo.type='hidden';
  		oCampo.name='Nombre';
  		oCampo.value=m_absResDlg['Nombre'];
  		document.FormLoginCertificatDigital.appendChild(oCampo);
    }

    if (typeof (m_absResDlg['Apellido1']) != 'undefined')
    {
      oCampo=document.createElement('INPUT');
  		oCampo.type='hidden';
  		oCampo.name='Apellido1';
  		oCampo.value=m_absResDlg['Apellido1'];
  		document.FormLoginCertificatDigital.appendChild(oCampo);
    }
    
    if (typeof (m_absResDlg['Apellido2']) != 'undefined')
    {
      oCampo=document.createElement('INPUT');
  		oCampo.type='hidden';
  		oCampo.name='Apellido2';
  		oCampo.value=m_absResDlg['Apellido2'];
  		document.FormLoginCertificatDigital.appendChild(oCampo);
    }
        
    if (typeof (m_absResDlg['EMail']) != 'undefined')
    {
      oCampo=document.createElement('INPUT');
  		oCampo.type='hidden';
  		oCampo.name='EMail';
  		oCampo.value=m_absResDlg['EMail'];
  		document.FormLoginCertificatDigital.appendChild(oCampo);
    }
    
    if (typeof (m_absResDlg['Emisor']) != 'undefined')
    {
      oCampo=document.createElement('INPUT');
  		oCampo.type='hidden';
  		oCampo.name='Emisor';
  		oCampo.value=m_absResDlg['Emisor'];
  		document.FormLoginCertificatDigital.appendChild(oCampo);
    }
    
    document.FormLoginCertificatDigital.submit();
  }
}
function SelecCertCallback(sNIF,sNombre,sApellido1,sApellido2,sEMail,sEmisor)
{
     // Certificado seleccionado correcto
    
    // Incorporamos los datos del ciudadano al formulario
	if(typeof (sNIF) != 'undefined' &&  sNIF.length)
	{
		var oCampo;
		oCampo=document.createElement('INPUT');
			oCampo.type='hidden';
			oCampo.name='NIF';
			oCampo.value = sNIF;
			document.FormLoginCertificatDigital.appendChild(oCampo);

		if (typeof (sNombre) != 'undefined' && sNombre.length)
		{
		  oCampo=document.createElement('INPUT');
			oCampo.type='hidden';
			oCampo.name='Nombre';
			oCampo.value = sNombre;
			document.FormLoginCertificatDigital.appendChild(oCampo);
		}

		if (typeof (sApellido1) != 'undefined' && sApellido1.length)
		{
		  oCampo=document.createElement('INPUT');
			oCampo.type='hidden';
			oCampo.name='Apellido1';
			oCampo.value= sApellido1;
			document.FormLoginCertificatDigital.appendChild(oCampo);
		}
		
		if (typeof (sApellido2) != 'undefined' && sApellido2.length)
		{
		  oCampo=document.createElement('INPUT');
			oCampo.type='hidden';
			oCampo.name='Apellido2';
			oCampo.value= sApellido2;
			document.FormLoginCertificatDigital.appendChild(oCampo);
		}
			
		if (typeof (sEMail) != 'undefined' && sEMail.length)
		{
		  oCampo=document.createElement('INPUT');
			oCampo.type='hidden';
			oCampo.name='EMail';
			oCampo.value= sEMail;
			document.FormLoginCertificatDigital.appendChild(oCampo);
		}
		
		if (typeof (sEmisor) != 'undefined' && sEmisor.length)
		{
		  oCampo=document.createElement('INPUT');
			oCampo.type='hidden';
			oCampo.name='Emisor';
			oCampo.value= sEmisor;
			document.FormLoginCertificatDigital.appendChild(oCampo);
		}
    
    document.FormLoginCertificatDigital.submit();
  }
}
// -------------------- Calendario -------------------------------------
/* 	DESTINATARIO -CONSULTAS-
	Muestra un calendario para seleccionar una fecha, se utiliza para rellenar 
	un campo fecha
*/
      //var idCalendario='calendario0'; 
       function updateInputDate(strDate, idField){
          
		 //SERGIO MANZANO PEREZ 26-11-2007  LE AÑADO EL EVENTO ONCHANGE AL CAMPO ORIGEN DEL FORMULARIO
		 var fieldDate=$(idField);
         //SERGIO MANZANO PEREZ 26-11-2007 INI 
		 var valor_antiguo = document.getElementById(idField).value;  
		 //SERGIO MANZANO PEREZ 26-11-2007 FIN
		 strDate=Transformar_Data(strDate);
		 fieldDate.value=strDate;
		 fieldDate.focus(); // Para forzar que se ejecuten los scripts de validación...
         fieldDate.blur();
         fieldDate.focus();
    	 //SERGIO MANZANO PEREZ 26-11-2007 INI 
		 if ( fieldDate.onchange!=null)
		 {
			if(valor_antiguo.length>0) 
			{
				if (valor_antiguo.toString()!=fieldDate.value.toString())
				{
					fieldDate.onchange();
				}		   
			} 
			else
			{
				fieldDate.onchange();
			}
		 }
		  //SERGIO MANZANO PEREZ 26-11-2007 FIN
		 
          //alert('validar Fecha='+Validar_Data(strDate));
          Element.remove( 'cal_' + idField );
      } 
      function mostrarCalendario(id,idField){
          var dimensions = Element.getDimensions( idField );
          var html_calendario='<div id="cal_' + idField + '" class="cont_calendario" style="display:none;"></div>';
          
          if(!document.getElementById('cal_' + idField)){
            new Insertion.After(id, html_calendario);                     
            clone_position(idField, 'cal_' + idField,{offsetTop:dimensions.height});
            new Draggable('cal_' + idField,{revert:true});
            var fecha = $F(idField);
            var aFecha=fecha.split(' ');
            fecha=aFecha[0];
            var cal_0=new Calendarios( fecha , 'cal_' + idField , '' , -1 , '', idField, {} );
            //new Effect.toggle($('cal_' + idField),'appear',false);
            //new Effect.toggle($('cal_' + idField),'blind');
            //new Effect.toggle($('cal_' + idField),'appear',false);
            Element.show('cal_' + idField);
            
          }else{
            Element.remove( 'cal_' + idField );
            cal_0='';
          }
      }
      function clone_position(source, target) {
          var options = Object.extend({
            setLeft:    true,
            setTop:     true,
            setWidth:   false,
            setHeight:  false,
            offsetTop:  0,
            offsetLeft: 0
          }, arguments[2] || {})
          source = $(source);
          var p = Position.page(source);
          // coordenadas
          target = $(target);
          var delta = [0,0];
          var parent = null;
          if (Element.getStyle(target,'position') == 'absolute') {
            parent = Position.offsetParent(target);
            delta = Position.page(parent);
          }      
          // correct by body offsets (fixes Safari)
          if (parent == document.body) {
            delta[0] -= document.body.offsetLeft;
            delta[1] -= document.body.offsetTop;
          }
          if( options.setLeft)   target.style.left  = (p[0] - delta[0] + 
                                                       options.offsetLeft) + 'px';
          if(options.setTop)    target.style.top   = (p[1] - delta[1] +
                                                       options.offsetTop) + 'px';
          if(options.setWidth)  target.style.width = source.offsetWidth + 'px';
          if(options.setHeight) target.style.height = source.offsetHeight + 'px';
        }
        
        // -------------------- Mostrar Fecha actual al cargar la página -------------------------------------
/* 	DESTINATARIO -CAMPOS FECHA-
	  Busca los campos fecha que tengan el evento onfocus="FechaActual(...)" y llama a la funcion fecha actual
	  para cargar la fecha.
*/
 
 	function CargarFechaActual(){
        var oForms = document.getElementsByName("frmTramite");
        for (j=0;j<oForms.length;j++)
        {        
	        var elementList = oForms[j].getElementsByTagName("input");
	        for (i=0;i<elementList.length;i++)
	        {
	            if (elementList[i].type=='hidden' &&  elementList[i].value=='date')
	            {
								var idCampo=elementList[i].name
	
								//** AGA: 23/10/2006 >> Modificación para contemplar también campos de tipo fecha y hora
	            	if (document.getElementById(idCampo + '0') && document.getElementById(idCampo + '1'))
	            	{
	              	FechaActual($(idCampo + '0'));
	              	HoraActual($(idCampo + '1'));
	            	}
								else            	
								{
	              	FechaActual($(idCampo));
	              }
	            }
	        }
	     }
    }

    function EDC_fechaAccionCalendario(idCampo,sCampo){
      //EDR 1/09/06 Consultas con calendario-reservas, Necesitamos cambiar dinamicamente el valor del campo fecha de filtro
      var oCampoFiltroCal = document.getElementById(idCampo);
      oCampoFiltroCal.value=sCampo;
     }
     
     
/////////////////////////////////////////////////////////////////////////////////////////////
// LISTAS DINÁMICAS
//------------------------------------------------------------------------------------------
// Funciones genéricas para la carga de una lista de manera dinámica mediante AJAX
/////////////////////////////////////////////////////////////////////////////////////////////     

function CargaListaDinamicaById(idElemento)
{
   var oSelect= document.getElementById(idElemento);
   var actual;
   var value;
   var padre;
   if (!oSelect) return true;
   padre= oSelect.parentNode;
   var hijos = padre.childNodes;
   
   for (var i=1; i<hijos.length; i++)
   {
      actual = hijos[i];
	  if (actual.id == idElemento)
	  {
	     value = actual.value;
		break; 
	  }
	  
   }
   CargarListaDinamicaByValue(idElemento,value);
}

var gNumListasPorCargar=0;
var gPestanaCargada;

function CargarListasDinamicas()
{
	// En caso que vengamos de una consulta llenamos las combos sólo con el valor seleccionado

	if(aDinList && iNumList && sListas && window.location.search.indexOf('procedencia') > 0)
	{
	  // Excepcion: si hay tabs no se carga nada pq se hace al ir navegando
	  if (getElementsByClassName)
      if (getElementsByClassName('tabcontentstyle').length > 0) return; 
	  
		var aTmp = sListas.split('|');
		for (var i=0; i<aTmp.length; i++)
		{
			var sLista = aTmp[i];
		    var urlASP='../../forms_base/ListaDinamica.asp?IdLista=' + sLista;
			
			aCampos=aDinList[sLista]['campos'].split('|');
			
			var sNomCampo = aCampos[0];

			var idtargetDIV='targetLst_' + sNomCampo;  

	    	new Ajax.Listcompleter(sNomCampo, 
    							idtargetDIV, 
    							urlASP, new Array(), sLista, false, true, true).getValues();
		}
	}	
}


// Explora todos los elementos SELECT contenidos en el parámetro
// y si corresponden a listas dinámicas se cargan 
function CargarCombosDinamicasDe(oElemPadre)
{
	if (oElemPadre)
	{
		var aCombos = oElemPadre.getElementsByTagName('SELECT');
		
		for (var i=0; i<aCombos.length; i++)
		{
			if (EsComboDinamicaMaestra(aCombos[i]))
			{
//			alert(aCombos[i].id);
				CargarAndLlenarComboDinamica(aCombos[i]);
			}
		}
	}
}

//Cierto si es una combo dinámica padre, es decir, la lista de valores
//disponibles no depende del valor de alguna otra lista
function EsComboDinamicaMaestra(oSelect)
{
	if (typeof aDinCmp!="undefined") // Hay listas dinámicas
	{
		// Está entre las listas dinámicas independientes
		
		if (typeof aDinCmp[oSelect.id]!="undefined") // Hay listas dinámicas
      if (typeof aDinList[aDinCmp[oSelect.id]['lst']] != "undefined")
      	if (aDinList[aDinCmp[oSelect.id]['lst']]['load'] == true ) return true;
			
		if(aDinCmp[oSelect.id])
			if(aDinCmp[oSelect.id]['val'] != '')
				return true;			
	}
	return false;
}

// Hace la petición AJAX para obtener los valores de una lista.
// El resultado se guarda en la seccion xml correspondiente a todas las combos que
// utilizan esa lista, por eso si se invoca esta operación sobre una combo para la
// cual ya se dispone de los valores ya no se hace otra petición al WS de listas
function CargarAndLlenarComboDinamica(oSelect)
{
	if(oSelect && aDinCmp)
	{			
		if (oSelect.value == '')
		{
			var sLista = aDinCmp[oSelect.id]['lst'];

			if (!aDinList[sLista]['cargada'])
			{
				EliminarElementosSubLista(oSelect);

				var urlASP='../../forms_base/ListaDinamica.asp?IdLista=' + sLista;
				var sNomCampo = oSelect.id;
				var aCampos = new Array(sNomCampo);
				var idtargetDIV='targetLst_' + sNomCampo;  

    			new Ajax.Listcompleter( sNomCampo, 
    									idtargetDIV, 
    									urlASP, new Array(), sLista, true, true, false).getValues();
    	}
	    else
	    {
	    	LlenarComboDinamica(oSelect, true);
	    }
    }
    else
    {
    	LlenarComboDinamica(oSelect, true);
    }
	}
}

// Rellena un elemento SELECT a partir de los datos almacenados en la sección XML
// adjunta destinada a tal efecto
function LlenarComboDinamica(oSelect)
{
	LlenarComboDinamica(oSelect, true);
}

function LlenarComboDinamica(oSelect, bMantenerEstado)
{
	var bLlenar = false;
	var bStatus = oSelect.disabled;
	var sValor;

	 // 1.- Miramos si ya tenemos valores o no
	if (!oSelect.options) bLlenar=true;
	else if (oSelect.options.length == 0) bLlenar=true;
	else if (oSelect.options.length <= 2)
	{
		// Si sólo tenemos un elemento, seguramente es el valor nulo por defecto
		// si es así hay que recargar
		if (oSelect.options[0].value == '') bLlenar=true;
	}


	// 2.- Miramos si este campo está en la lista global de campo dinámicos
	if (bLlenar && aDinCmp)
		if (aDinCmp[oSelect.id]) bLlenar=true;

	
	// 3.- Cargamos las opciones
	if (bLlenar)
	{
//alert('LlenarComboDinamica: ' + oSelect.id);
	
		EliminarElementosSubLista(oSelect);
		

		var oTarget = document.getElementById('targetLst_' + oSelect.id);
		if (oTarget)
		{		
			if (NavegadorIE())
			{
  			var oListaElems = oTarget.XMLDocument.selectNodes("//e");	      
  			if (oSelect.disabled && oListaElems.length != 0) oSelect.disabled = false;
      		
				for (i=0;i<oListaElems.length;i++)
				{
					oOption = document.createElement("OPTION");
					oOption.text=oListaElems(i).nodeTypedValue;
					var sNombreCombo=oSelect.id;
					if(sNombreCombo.match("FIL_") || sNombreCombo.match("INF_") ){
						oOption.value=oListaElems(i).getAttribute("i");
					}else{
						oOption.value=oListaElems(i).getAttribute("i") + "-" + oListaElems(i).nodeTypedValue;
					}
					oSelect.add(oOption);
				}
			}
			else
			{
	  			var oLista = oTarget.childNodes[1].getElementsByTagName('E');
	  			if (oSelect.disabled && oLista.length != 0) oSelect.disabled = false;
					var sNombreCombo=oSelect.id;
					if(sNombreCombo.match("FIL_") || sNombreCombo.match("INF_") ){
						for (i=0;i<oLista.length;i++)
						{
							oSelect.options[oSelect.options.length] = new Option(
							oLista[i].innerHTML, 
							oLista[i].getAttribute('i'));
						}
					}else{
						for (i=0;i<oLista.length;i++)
						{
							oSelect.options[oSelect.options.length] = new Option(
							oLista[i].innerHTML, 
							oLista[i].getAttribute('i') + '-' + oLista[i].innerHTML);
						}
					}
					
				}

				if (bMantenerEstado) 
				{
					//alert(oSelect.id + ':' + bStatus);
					oSelect.disabled = bStatus;
				}
				
				if(aDinCmp[oSelect.id]['val'] != '')
				{
					// Se le ha asignado un valor mientras se estaba cargando,
					// lo marcamos ahora como seleccionado
					
					EstablecerValorCampo(window.document, oSelect.id, aDinCmp[oSelect.id]['val'], '=');
					aDinCmp[oSelect.id]['val'] = '';
				}
			else
			{
        if (oSelect.options)
        {
  				if (oSelect.options.length == 1) oSelect.selectedIndex = 0; 
  				else if (oSelect.options.length == 2) {
  					if (oSelect.options[0].value == '') oSelect.selectedIndex = 1; 
  				}
        }	
			}
		}
		//AGD >> Hemos llenado una combo dinamica, ahora miramos si tiene hijos
		if (typeof aListaPadres[oSelect.id] != "undefined") 
		{
			sValor = oSelect.value.split("-");
			if (typeof sValor[0] != "undefined")
			{
			
				CargarListaHijosEDC(aListaPadres[oSelect.id], sValor[0]);
			}
			else
			{
				CargarListaHijosEDC(aListaPadres[oSelect.id], sValor);
			}
			
		}
		
	}
}




function LlenarUnValorComboDinamica(oSelect, bMantenerEstado)
{

	var bLlenar = false;
	var bStatus = oSelect.disabled;

	 // 1.- Miramos si ya tenemos valores o no
	if (!oSelect.options) bLlenar=true;
	else if (oSelect.options.length == 0) bLlenar=true;
	else if (oSelect.options.length == 1)
	{
		// Si sólo tenemos un elemento, seguramente es el valor nulo por defecto
		// si es así hay que recargar
		if (oSelect.options[0].value == '') bLlenar=true;
	}

	// 2.- Miramos si este campo está en la lista global de campo dinámicos
	if (bLlenar && aDinCmp)
		if (aDinCmp[oSelect.id]) bLlenar=true;

	
	// 3.- Cargamos las opciones
	if (bLlenar)
	{
		var oTarget = document.getElementById('targetLst_' + oSelect.id);
		if (oTarget)
		{		
			if (NavegadorIE())
			{
      			var oListaElems = oTarget.XMLDocument.selectNodes("//e");	      
      			oSelect.disabled = (oListaElems.length == 0);
      			
      			
						for (i=0;i<oListaElems.length;i++)
						{
							if(aDinCmp[oSelect.id]['val'].split('-')[0] == oListaElems(i).getAttribute("i"))
							{
									oOption = document.createElement("OPTION");
									oOption.text=oListaElems(i).nodeTypedValue;
									oOption.value=oListaElems(i).getAttribute("i") + "-" + oListaElems(i).nodeTypedValue;
									oSelect.add(oOption);
							}
						}
			}
			else
			{
  			var oLista = oTarget.childNodes[1].getElementsByTagName('E');
  			oSelect.disabled = (oLista.length == 0);
				for (i=0;i<oLista.length;i++)
				{
					if(aDinCmp[oSelect.id]['val'].split('-')[0] == oLista[i].getAttribute("i"))
					{
							oSelect.options[oSelect.options.length] = new Option(
							oLista[i].innerHTML, 
							oLista[i].getAttribute('i') + '-' + oLista[i].innerHTML);
					}
				}
			}
			if (bMantenerEstado) 
			{
				//alert(oSelect.id + ':' + bStatus);
				oSelect.disabled = bStatus;
			}
			EstablecerValorCampo(window.document, oSelect.id, aDinCmp[oSelect.id]['val'], '=');
		}
		//AGD >> Hemos llenado una combo dinamica, ahora miramos si tiene hijos
		if (typeof aListaPadres[oSelect.id] != "undefined") 
		{
			CargarListaHijosEDC(aListaPadres[oSelect.id], oSelect.value);
		}
	}
}




// Llamada para cargar una sublista dinámica, de la cuál se obtienen los valores
// en función del valor seleccionado en una lista padre
function CargarSubComboDinamica(oSelectDest, sListaPadre, sValor, sSubLista)
{
	if (oSelectDest) EliminarElementosSubLista(oSelectDest);
		

	if (window.location.search.indexOf('procedencia=Confirmacion')>=0)
    {
	  
		if (aDinList)
		{
			if (aDinList[sListaPadre])
			{
		
				if ( aDinCmp[aDinList[sListaPadre]['campos']])
				{
				ValorAux = aDinCmp[aDinList[sListaPadre]['campos']]['val'];
				}	
			}
			if (ValorAux.length>0)
			{
	       
			sValor= ValorAux;
	 
			}	     
	
		}
	
	          
	}

	
	var urlASP='../../forms_base/SubListaDinamica.asp?IdListaPadre=' + sListaPadre + '&valor='  + sValor.split('-')[0] + '&IdSubLista='  + sSubLista ;

	var sNomCampo = oSelectDest.id;

	oSelectDest.disabled = true;

	var aCampos = new Array(sNomCampo);

	var idtargetDIV='targetLst_' + oSelectDest.id;  

	if (typeof(aDinList)=='undefined') return;
	
	aDinList[sSubLista]['cargada'] = false;

  	new Ajax.Listcompleter( sNomCampo, 
  						idtargetDIV, 
  						urlASP, aCampos, sSubLista, true, false, false).getValues();
}


/////////////////////////////////////////////////////////////////////////////////////////////
// TABS
//------------------------------------------------------------------------------------------
// Funciones genéricas para la inicialización y navegación por una estructura de tabs
/////////////////////////////////////////////////////////////////////////////////////////////     

// Variables globales tabs
var enabletabpersistence=1; 
var tabcontentIDs=new Object();
var pestanaActual="";

var selectedTabs=new Array();
var idsTabs=new Array();

// -------------------- INICIALIZAR TABS (PESTAÑAS) -------------------------------------
// Inicializa los tabs de la página (invocar desde onload pasando como parametros los ids de
// las secciones a inicializar)


function GetPagina()
{
  var aTmp = window.location.pathname.split('/');
  var idPagina = aTmp[aTmp.length-1].substring(0, 32);
  return idPagina;
}

function RecuperandoDatos()
{
   var resultado= false;
  var aTmp = window.location.search;
  aTmp= aTmp.toLowerCase();
  resultado= aTmp=="?procedencia=consulta";
  return resultado;
}
function InicializarPestana(pestana)
{	
	CargarCombosPestanaVisible(pestana);
	var idPagina = GetPagina();
	if (RecuperandoDatos() && GetCampoValidacion(pestana)== "S") 
	{
		RecuperacionDatosLogicaNegocioPestana(idPagina,pestana);
		return;
	}
	if (GetCampoValidacion(pestana)== "S") return;
	
	InicializacionLogicaNegocioPestana(idPagina,pestana); 
}


function CargarCombosPestanaVisible(idPestana)
{
	// Buscamos en las listas de tabs seleccionados para que en el caso de que el
	// pasado por parámetro tenga subtabs, se carguen solo las combos del
	for (var k=0; k<idsTabs.length; k++)
	{
		if (selectedTabs[idsTabs[k]])
		{
			if (selectedTabs[idsTabs[k]].substring(0, idPestana.length) == idPestana)
				idPestana = selectedTabs[idsTabs[k]];			
		}
	}
	CargarCombosDinamicasDe(document.getElementById(idPestana)); 
}

function initializetabcontent(){

	var primeroDeTodos=true;		
	
	idsTabs = arguments;
	
	for (var i=0; i<arguments.length; i++)
	{ 
		var primeroDeTab=true;		
		
		if (enabletabpersistence==0 && getCookieTab(arguments[i])!="") setCookieTab(arguments[i], "");
		var clickedontab=getCookieTab(arguments[i]);
		var ulobj=document.getElementById(arguments[i]);
		var ulist=ulobj.getElementsByTagName("li");
		for (var x=0; x<ulist.length; x++)
		{ 		
			var ulistlink=ulist[x].getElementsByTagName("a")[0];
			if (ulistlink.getAttribute("rel"))
			{
				ulistlink.onclick=function(){
								if (validaPestana(pestanaActual)) {
									expandcontent(this); 
									pestanaActual=this.getAttribute("rel"); 
						
									
									// Entre los otros selectores de tabs buscamos alguno que tenga pestañas hijas
									// (tienen el mismo id seguido del sufijo a, b, c, d...
									for (var k=0; k<idsTabs.length; k++)
									{
										if (idsTabs[k] != this.parentNode.parentNode.id)
											if (selectedTabs[idsTabs[k]].substring(0, pestanaActual.length) == pestanaActual)
												pestanaActual=selectedTabs[idsTabs[k]]; 
										else
											selectedTabs[idsTabs[k]]=pestanaActual; 
									}
								    InicializarPestana(pestanaActual);
								} 
								return false;
				}
				savetabcontentids(arguments[i], ulistlink.getAttribute("rel"));
				if (ulist[x].className=="selected" && clickedontab=="")
				{
					if (primeroDeTodos)
					{
						primeroDeTodos=false; 
						pestanaActual=ulistlink.getAttribute("rel");
					}
				
					if (primeroDeTab)
					{
						primeroDeTab=false;
						idsTabs[i]=arguments[i];
						selectedTabs[arguments[i]] = ulistlink.getAttribute("rel");
					}
		
					expandcontent(ulistlink);
				}
			}
		} 
		if (clickedontab!="")
		{ 
			var culistlink=getullistlinkbyId(arguments[i], clickedontab);
			if (typeof culistlink!="undefined") {expandcontent(culistlink);	}
			else {expandcontent(ulist[0].getElementsByTagName("a")[0]);}
			if (primeroDeTodos){
				pestanaActual=culistlink.getAttribute("rel"); 
				primeroDeTodos=false; 
			}
			
			if (primeroDeTab){
				primeroDeTab=false;
				idsTabs[i]=arguments[i];
				selectedTabs[arguments[i]] = culistlink.getAttribute("rel"); 
			}
			
			
									// Entre los otros selectores de tabs buscamos alguno que tenga pestañas hijas
									// (tienen el mismo id seguido del sufijo a, b, c, d...
									for (var k=0; k<idsTabs.length; k++)
									{
										if (idsTabs[k] != culistlink.parentNode.parentNode.id)
											if (selectedTabs[idsTabs[k]])
												if (selectedTabs[idsTabs[k]].substring(0, pestanaActual.length) == pestanaActual)
													pestanaActual=selectedTabs[idsTabs[k]]; 
									}
		}
	} 

     
}


// -------------------- VALIDACION  TABS (PESTAÑAS) -------------------------------------
// Valida la pestaña con el id pasado por parámetro mirando la validez los campos que contiene
// (obligatorio/no obligatorio, incorrecto <== color rojo)       
// Además se invoca a la función ValidacionLogicaNegocioPestana, que se puede redifinir en 
// el fichero scriptsCampos.js para hacer validaciones más específicas, propias de cada 
// formulario

function validaPestana(idPestana, bSubmit) 
{   
	var oCampo, sMensajeError;
	var bError=false;
	var pestana=document.getElementById(idPestana);
	/* VALIDAMOS INPUTS */
	var listaInputs=pestana.getElementsByTagName('input');
	for (var i=0;i<listaInputs.length;i++)
	{
		if ((listaInputs[i].getAttribute('type')!="hidden")&&(listaInputs[i].getAttribute('onblur')!=null))
		{
			if((((listaInputs[i].getAttribute('onblur')+'').indexOf('CampoObligatorio')>=0) && (listaInputs[i].value.length==0))||((listaInputs[i].style.color=='Red')||(listaInputs[i].style.color=='red')))
			{
				bError=true; oCampo=listaInputs[i]; sMensajeError=strCampoObligatorio + ' ' + listaInputs[i].getAttribute('title').toUpperCase();
			}
		}
		if (bError){break;}
	}
	/* VALIDAMOS SELECTS */
	var listaInputs=pestana.getElementsByTagName('select')
	for (i=0;i<listaInputs.length;i++)
	{
		if ((listaInputs[i].getAttribute('type')!="hidden")&&(listaInputs[i].getAttribute('onblur')!=null))
		{
			if(((listaInputs[i].getAttribute('onblur')+'').indexOf('CampoObligatorio')>=0) && (!listaInputs[i].disabled) &&(listaInputs[i].value.length==0))
			{
				bError=true;oCampo=listaInputs[i];sMensajeError=strCampoObligatorio + ' ' + listaInputs[i].getAttribute('title').toUpperCase();
			}
		}
		if (bError){break;}
	}
	/* TRATAMIENTO DE ERRORES */
	if (bError)
	{
		actualizaCampoValidacion(idPestana,"N");
		alert(sMensajeError);
		if (oCampo.type != 'hidden'){ try {oCampo.focus(); } catch(ex) {}}
		return false;
	}
	else 
	{
		// Validación de la lógica de negocio:
		// Se llama a una función generica que por defecto devuelve cierto y que se
		// debe reprogramar si hay que hacer validaciones especificas para una página
		// y/o pestaña. Los mensajes de error pertinentes se han de mostrar desde 
		// dentro de esta funcion
		
		// Si no hay errores
		var aTmp = window.location.pathname.split('/');
		var idPagina = aTmp[aTmp.length-1].substring(0, 32);
		
		if (!ValidacionLogicaNegocioPestana(idPagina, idPestana, bSubmit))
		{
			actualizaCampoValidacion(idPestana,"N");
			return false;
		}
		else
		{
			actualizaCampoValidacion(idPestana,"S");
			return true;
		}
	}
}



// Campo de validación: En cada pestaña podemos tener un campo hidden que se usa
// para saber si el conenido de la misma es válido o no.
// Las siguientes funciones auxiliares se utilizan para actualizar el valor
// segun corresponda
function GetCampoValidacion(nombrePestana)
{
	var oCampoVal = document.getElementById(nombreCampoValidacion(nombrePestana));
	return oCampoVal.value;
}

function nombreCampoValidacion(nombrePestana)
{
	var nombreCampo="WTXVAL";
	var letra="a";
	i=nombrePestana.length;
	if (isNaN(nombrePestana.substr(i-1,1))) { letra=nombrePestana.substr(i-1,1); nombrePestana=nombrePestana.substr(0,i-1);}
	i=nombrePestana.length;
	while (isNaN(nombrePestana.substr(0))) { 	nombrePestana = nombrePestana.substr(nombrePestana.length- (i--));	}
	if (nombrePestana.length==1) {nombrePestana= '0' + nombrePestana;}
	nombreCampo= nombreCampo + nombrePestana + letra;
	return nombreCampo;
}

function actualizaCampoValidacion(nombrePestana, valor)
{
	var oCampoVal = document.getElementById(nombreCampoValidacion(nombrePestana));
	if (oCampoVal) oCampoVal.value=valor;
}

//FUNCIONES AUXILIARES VISUALIZACION TABS:

function expandcontent(linkobj)
{
	var oLoad = document.getElementById('tcontent0');
	var bMensajeCarga = false;
	
	if (typeof oLoad != 'undefined')
	{
		if (oLoad.style.display != 'none') bMensajeCarga = true;
	}
	
  var ulid=linkobj.parentNode.parentNode.id;
    
/* Las siguientes lineas es código para no depender de una estructura estática de capas */
	
    var ullist=document.getElementById(ulid).getElementsByTagName("li");

    for (var i=0; i<ullist.length; i++)
		{
		    ullist[i].className="";  
			if (typeof tabcontentIDs[ulid][i]!="undefined"){document.getElementById(tabcontentIDs[ulid][i]).style.display="none";}
		}


	if ( (pestanaActual!='') || (pestanaActual==linkobj.getAttribute("rel")))
	{
	
		if (!bMensajeCarga || ulid != 'maintab') 
		{
	    linkobj.parentNode.className="selected";  
			document.getElementById(linkobj.getAttribute("rel")).style.display="block";
	    saveselectedtabcontentid(ulid, linkobj.getAttribute("rel"));
	  }
	  else
	  {
	  	oLoad.style.display="block";
			document.getElementById(linkobj.getAttribute("rel")).style.display="none";
			gPestanaCargada = linkobj;
	  } 
	}
	else
	{
		
		if (pestanaActual=='' && typeof oLoad == 'undefined')
		{
			linkobj.parentNode.className="selected";
			document.getElementById(linkobj.getAttribute("rel")).style.display="block";
		}
		else
		{
			oLoad.style.display="block";
			document.getElementById(linkobj.getAttribute("rel")).style.display="none";
		}
	}
	
	self.scroll(0,0);
}

function expandtab(tabcontentid, tabnumber){ var thetab=document.getElementById(tabcontentid).getElementsByTagName("a")[tabnumber]; if (thetab.getAttribute("rel")){expandcontent(thetab);}}
function savetabcontentids(ulid, relattribute){if (typeof tabcontentIDs[ulid]=="undefined") {tabcontentIDs[ulid]=new Array();} tabcontentIDs[ulid][tabcontentIDs[ulid].length]=relattribute;}
function saveselectedtabcontentid(ulid, selectedtabid){ if (enabletabpersistence==1) setCookieTab(ulid, selectedtabid);}
function getCookieTab(Name){ return "";var re=new RegExp(Name+"=[^;]+", "i"); if (document.cookie.match(re)) {return document.cookie.match(re)[0].split("=")[1];}return "";}
function setCookieTab(name, value){ document.cookie = name+"="+value;}

function getullistlinkbyId(ulid, tabcontentid){
    var ullist=document.getElementById(ulid).getElementsByTagName("li");
    for (var i=0; i<ullist.length; i++)
	{if (ullist[i].getElementsByTagName("a")[0].getAttribute("rel")==tabcontentid){return ullist[i].getElementsByTagName("a")[0]; break;}}
}



// showElementsTab: Se ejecuta al hacer submit en un formulario con pestañas
function showElementsTab(oEvent, theForm, idPestana) {   
  var oBtnAceptar,idPagina,oSelTab;

	if (NavegadorIE()) oBtnAceptar=oEvent.srcElement;
	else oBtnAceptar=oEvent.target;

	if (oBtnAceptar!=null) oBtnAceptar.disabled=true;


	var aTmp = window.location.pathname.split('/');
	idPagina = aTmp[aTmp.length-1].substring(0, 32);

	// Campo oculto para guardar el identificador
	// de la pestaña seleccionada, si existe se llama WTXSELTAB
	oSelTab = document.getElementById('WTXSELTAB');
	if (oSelTab) oSelTab.value = idPestana;
	
	
	if (!validaPestana(idPestana, true))
	{
		if (oBtnAceptar!=null) oBtnAceptar.disabled=false;
		if (NavegadorIE())
		{
			oEvent.cancelBubble = true;
			oEvent.returnValue = false;
		}
		else
		{
			oEvent.stopPropagation();
			oEvent.preventDefault();
		}
	}
	else
	{
		// Si existe un subtab de espera por envío de datos lo mostramos		
		var oSend = document.getElementById('tcontent0b');
		if (oSend)
		{
			document.getElementById(idPestana).style.display = 'none';
			oSend.style.display = 'block';
			self.scroll(0,0);
		}

		if (winAttachEDF)
		{
			if (!winAttachEDF.closed) winAttachEDF.close();
		}
		
		if (hayElementoFirma(theForm))
		{
			if (firmar(theForm,theForm.FIRMA_SOLICITUD,oEvent))
			{
				theForm.submit();
			}						
		}
		else
		{
			theForm.submit();
		}		
	}
}


function FinCargaListasDinamicas() 
{
	var oLoad = document.getElementById('tcontent0');
	if ((typeof oLoad != 'undefined') && (typeof gPestanaCargada != 'undefined'))
	{
		oLoad.style.display = 'none';
		expandcontent(gPestanaCargada);
		gPestanaCargada = undefined;
	}
}


//SERGIO MANZANO PEREZ 26/02/2008 FIN
//OMC 13/03/2008
function pintaFondoCampo(oCampo){
    if (oCampo.value == "" && (oCampo.onblur+' ').indexOf('CampoObligatorio')>=0)
    { //<--- Mira si es un campo + sus 8 hidden y, si está vacío.
			oCampo.style.backgroundColor = colorAvisoCampoVacio; //<-- Pinta el color del fondo del que en scriptsCampos.js se indique (A elección libre).
    }else{	
        oCampo.style.backgroundColor = "white"; //<-- Devuelve el campo a su estado normal (fondo de color blanco).
    }
}
//OMC 13/03/2008 FIN




//////////////////////////////////////////////////////////////////////////////////////////
// FUNCIONES ACCESO DOM
//////////////////////////////////////////////////////////////////////////////////////////
//OOF 30/04/2008
//funcion para crear un formulario
function getNewForm(){
 var submitForm = document.createElement("FORM");
 document.body.appendChild(submitForm);
 submitForm.method = "POST";
 return submitForm;
}
//funcion para añadir elementos al form
function createNewFormElement(inputForm, elementName, elementValue){
 var newElement = document.createElement("input");
 newElement.value = elementValue;
 newElement.name = elementName;
 newElement.type = "hidden"; 
 inputForm.appendChild(newElement); 
 return newElement;
}

function crearCampoForm(tag,name)
{
	var oCampo;
	if (NavegadorIE())
	{
		oCampo=document.createElement('<'+tag+' name="' + name +'">');
	}
	else
	{
			oCampo = document.createElement(tag);
			oCampo.setAttribute('name',name);
	}
	return oCampo;
}

//////////////////////////////////////////////////////////////////////////////////////////
// FUNCIONES FICHEROS ADJUNTOS
//////////////////////////////////////////////////////////////////////////////////////////

function AbrirFormSeleccAdjuntos(sCampoImagen,link)
{
	var oFormLink,oAttachments,i,oCampoOri,oCampoDes,iLeft,iTop,iWidth,iHeight,sFeatures,sEnlace,sEstilo,iIni,iFin,iNumCampAtt,paramsGenerales;
	
	paramsGenerales = "";
	
	//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));
	//Añadimos todos los campos que hay en los ficheros adjuntos
	oAttachments=document.getElementsByTagName('span');

	iNumCampAtt=0;
	
	for (j=0; j<oAttachments.length; j++)
	{
		if(oAttachments.item(j).id.substring(0,15) == 'spanAttachFiles')
		{
			iNumCampAtt++;	
			
			// se acumula la información de todos los ficheros adjuntos,
			// ya sean adjuntos convencionales, o campos de tipo imagen
			for(i=0;i<oAttachments.item(j).childNodes.length;i++)
			{
				//Creamos un campo oculto y lo anadimos al formulario
				oCampoOri=oAttachments.item(j).childNodes.item(i);
				oCampoDes=document.createElement('INPUT');
				oCampoDes.type='hidden';
				oCampoDes.name=oCampoOri.name;
				oCampoDes.value=oCampoOri.value;
				if (oCampoOri.name != undefined && oCampoOri.name != undefined)
					oFormLink.appendChild(oCampoDes);
			}
			var hiddens = link.getElementsByTagName("input");
			for(i=0;i<hiddens.length;i++)
			{
				if(hiddens.item(i).name=="maxArchivos")
				{						
					paramsGenerales = "&maxArchivos="+hiddens.item(i).value;
				}
				if(hiddens.item(i).name=="extensionesAdmitidas")
				{					
					paramsGenerales += "&extensionesAdmitidas="+hiddens.item(i).value;
				}
			}
			
		}
	}

	// existe al menos un <span> para tener información de documentos / imágenes adjuntos
	if (iNumCampAtt > 0)
	{
		//Obtenemos las coordenadas de la nueva ventana
		iWidth=530;
		iHeight=350;
		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;

		sFeatures="height=" + iHeight + ",width=" + iWidth + ",left=" + iLeft + ",top=" + iTop + ",scrollbars=1,directories=no,status=yes,toolbar=no,menubar=no,location=no,resizable=yes,titlebar=no"
		winAttachEDF=window.open('about:blank','winAttachFiles',sFeatures);
		sEnlace='../src/asp/selecFicheros/SelecFicheros.asp';


		// ARL 13/09/06 >> Añadir los parametros a la URL
	 	if (sCSS.length>0)	
			// Ya nos habian indicado el css (la variable sCSS esta definida en absBase.js)
			sParamEstilo = '?css=' + sCSS;
		else
		{		
			// JAPB 07/05/2009 >> Modificacion para pasar por parametro el ultimo css que no sea media = print (normalmente el ayuntamiento.css, eColabora.css, eAtiende.css, etc)
			if(document.styleSheets.length>0){
				var z = document.styleSheets.length - 1;
				var strSearch;
				while(z >= 0){
					if(document.styleSheets.item(z).media.mediaText){
						strSearch = new String(document.styleSheets.item(z).media.mediaText);
					}else {
						strSearch = new String(document.styleSheets.item(z).media);
					}
					//JAPB: Evita los problemas con las hojas de estilo del tiny_mce
					strHref = new String(document.styleSheets.item(z).href);
					if(strSearch.search(/print/i) == -1 && strHref.search(/tiny/i) == -1){
						sEstilo=document.styleSheets.item(z).href;
						break;
					}
					z--;
				}
			}			
			if(sEstilo == null)
			{sEstilo="";}

			var i = 2;
			var sParamEstilo = "";
			while ((sEstilo == "") && (i <= document.styleSheets.length))
			{
				sEstilo=document.styleSheets.item(document.styleSheets.length-i).href;
				i++;
			}
			if (sEstilo != "")
			{
						iIni=sEstilo.lastIndexOf('/');
						iFin=sEstilo.lastIndexOf('.');
						if ((iIni>=0) && (iFin>=0) && (iIni<iFin))
							sParamEstilo = '?css=' + sEstilo.substr(iIni+1,iFin-iIni-1);
			}
		}
		if (sParamEstilo != "")
				sEnlace = sEnlace + sParamEstilo + '&img=' + sCampoImagen +paramsGenerales;
		else
				sEnlace = sEnlace + '?img=' + sCampoImagen + paramsGenerales;

		oFormLink.action=sEnlace;
		oFormLink.target='winAttachFiles';
		oFormLink.submit();
		if (winAttachEDF) winAttachEDF.focus();
	}
}

function AnadirFicheroAdjuntoFormulario(sKey,sNombre,sTamano,sId,sCampoImagen,vaFirmado)
{
	var oSpanCampos,oSpanTexto,oCampo,sTexto;

	//OOF 20/03/09 -> Si no se utiliza la funcion que devuelve los adjuntos con las firmas puede generar falsos positivos al poner el valor undefined.
	if(!(vaFirmado == 'true' || vaFirmado == true) )
	{vaFirmado = false;} 
	//Buscamos donde hay que anadir los campos
	oSpanCampos=document.getElementById('spanAttachFiles' + sCampoImagen);

	if (oSpanCampos)
	{
		
		//Anadimos los campos		
		oCampo=crearCampoForm("INPUT",sKey);		
		oCampo.type='hidden';
		oCampo.value=sNombre;
		oSpanCampos.appendChild(oCampo);
		
		oCampo=crearCampoForm("INPUT",sKey);	
		oCampo.type='hidden';
		oCampo.value=sTamano;
		oSpanCampos.appendChild(oCampo);
		
		oCampo=crearCampoForm("INPUT",sKey);		
		oCampo.type='hidden';
		oCampo.value=sId;
		oSpanCampos.appendChild(oCampo);
		
		//SERGIO MANZANO PÉREZ 10-12-2007 FIN		
		// Si el campo es de tipo imagen adjunta, añadimos el nombre del campo
		if (sCampoImagen != '')
		{
			oSpanCampos.appendChild(oCampo);
			oCampo=document.createElement('INPUT');
			oCampo.type='hidden';
			oCampo.name=sKey;
			oCampo.value=sCampoImagen;
			oSpanCampos.appendChild(oCampo);
		}
		else
		{
		 //SERGIO MANZANO PEREZ 10-12-2007 INI 
		 
			oSpanCampos.appendChild(oCampo);
			oCampo=crearCampoForm("INPUT",sKey);	
			oCampo.value = sCampoImagen;			
			oCampo.type='hidden';
			oCampo.name=sKey;
			
			oSpanCampos.appendChild(oCampo);
		//SERGIO MANZANO PEREZ 10-12-2007 FIN		
		}

		//Actualizamos la descripcion
		oSpanTexto=document.getElementById('spanAttachText' + sCampoImagen);
		
		//Creamos la UL si no existe
		if(oSpanTexto.getElementsByTagName("ul").length < 1)
		{
			oCampo = document.createElement('UL');
			oSpanTexto.appendChild(oCampo);
			
		}			
		
		oSpanTexto = oSpanTexto.getElementsByTagName("ul")[0];
		if (oSpanTexto)
		{			
			oCampo=crearCampoForm("LI",sKey.replace('fileAttach','fileAttachLi'));
			oCampo.id=sKey.replace('fileAttach','fileAttachLi');
			oCampo.innerHTML = sNombre + ' (' + sTamano + ' Mb)';	
			if(vaFirmado=="true")
			{
				oCampo.innerHTML+="<span><img alt='Firmado'  src='"+document.getElementsByName('imagenFirmados')[0].value+"'/><span>";				
			}
			oSpanTexto.appendChild(oCampo);
		}		
		
		if(!document.getElementById('spanAttachFirmas'))
		{
			oCampo      = document.createElement('SPAN');
			oCampo.name = 'spanAttachFirmas';
			oCampo.id   = 'spanAttachFirmas';		
			//Actualizamos la descripcion
			oSpanTexto=document.getElementById('spanAttachText' + sCampoImagen).parentNode.appendChild(oCampo)	
		}
		oCampo=crearCampoForm("INPUT",sKey.replace('fileAttach','fileAttachFirma'));
		oCampo.type ="hidden";			
		oCampo.value = vaFirmado;			
		document.getElementById('spanAttachFirmas').appendChild(oCampo);		
		
	}
}

//Funcion que codifica en base64 la cadena pasada
function Base64Encode(sTextoAConvertir)
{
	var sURL;
	sURL="../../forms_base/convertbase64.asp";
	sTextoAConvertir = escape(sTextoAConvertir);
	if (NavegadorIE())
	{
	 			xmlHttpReq = new ActiveXObject("MSXML2.XMLHTTP");
				xmlHttpReq.open("POST",sURL , false);
				xmlHttpReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
				xmlHttpReq.send("entrada="+sTextoAConvertir);
	}
	else
	{
			xmlHttpReq=new XMLHttpRequest();
			xmlHttpReq.open("POST", sURL, false);
			xmlHttpReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			xmlHttpReq.send("entrada="+sTextoAConvertir);	
	}

	return xmlHttpReq.responseText;
}

function ObtenerContenidoFichero(sIdEntidad, sIdioma, sIdFichero, bBase64)
{
	var sURL;
	
	sURL="../Comun/Ficheros.asp?id=" + sIdEntidad + "&idioma=" + sIdioma  + "&fichero=" + sIdFichero + "&base64=" +bBase64

	if (NavegadorIE())
	{
	 			xmlHttpReq = new ActiveXObject("MSXML2.XMLHTTP");
				xmlHttpReq.open("GET",sURL , false);
				xmlHttpReq.send("");
	}
	else
	{
			xmlHttpReq=new XMLHttpRequest();
			xmlHttpReq.open("GET", sURL, false);
			xmlHttpReq.send("");	
	}

	return xmlHttpReq.responseText;
}


function VisualizarFicheroAdjunto(sIdEntidad, sNomTab, sTraGen, sOrden, sIdFichero, sOrigen, sIdioma)
{
		//Obtenemos las coordenadas de la nueva ventana
		iWidth=600;
		iHeight=480;
		
		sIdioma = sIdioma.split("|$FIRMA$|")[0];
		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;

		sFeatures="height=" + iHeight + ",width=" + iWidth + ",left=" + iLeft + ",top=" + iTop + ",directories=no,status=yes,toolbar=no,menubar=yes,location=no,resizable=yes,titlebar=no"
		sEnlace='../src/asp/selecFicheros/DescargaFichero.asp';
		sEnlace=sEnlace + '?sIdEntidad=' + sIdEntidad + '&sNomTab=' + sNomTab + '&sTraGen=' + sTraGen + '&sOrden=' + sOrden + '&sIdFichero=' + sIdFichero + '&sOrigen=' + sOrigen + '&sIdioma=' + sIdioma;
		
	 	if (sCSS.length>0) sEnlace=sEnlace + '&css=' + sCSS;
		else
		{
			sEstilo=document.styleSheets.item(document.styleSheets.length-1).href;
			iIni=sEstilo.lastIndexOf('/');
			iFin=sEstilo.lastIndexOf('.');
			if ((iIni>=0) && (iFin>=0) && (iIni<iFin))
			{
				sEnlace=sEnlace + '&css=' + sEstilo.substr(iIni+1,iFin-iIni-1);
			}
		}
		winAttachEDF=window.open(sEnlace,'_blank',sFeatures);
		winAttachEDF.focus();
}

function DescargaFicheroServer(sFilePath)
{
		//Obtenemos las coordenadas de la nueva ventana
		iWidth=600;
		iHeight=480;
		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;

		sFeatures="height=" + iHeight + ",width=" + iWidth + ",left=" + iLeft + ",top=" + iTop + ",directories=no,status=yes,toolbar=no,menubar=yes,location=no,resizable=yes,titlebar=no"
		sEnlace='../src/asp/selecFicheros/DescargaFicheroServer.asp';
		
		// Pasamos el path por POST
		
		oFormLink=document.getElementById('frmLink');
		while (oFormLink.childNodes.length>0)
			oFormLink.removeChild(oFormLink.childNodes.item(0));

		oCampoOculto=document.getElementById(sFilePath);
		oCampoOculto.name='path';
		oFormLink.appendChild(oCampoOculto);


		// 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;
		oFormLink.action=sEnlace;
		oVentana.focus();

		oFormLink.submit();
}

//----------------------------------------------------------
//	Funciones para la gestion de los ficheros adjuntos
//----------------------------------------------------------
var winAttachEDF;

function SeleccionarFicheros(e)
{
	var targ;
	if (!e)
	{
	  var e=window.event;  // OMC  18/07/2008 No funcionaba para Internet Explorer, lo dejo tal y como anteriormente se llamaba al método.	  
	}
	if (e.target)
	{
	  targ=e.target;
	}
	else if (e.srcElement)
	{
	  targ=e.srcElement;
	}
	if (targ.nodeType==3) // defeat Safari bug
	{
	  targ = targ.parentNode;
	}
	targ = targ.parentNode.parentNode.parentNode;	
	AbrirFormSeleccAdjuntos('',targ);
}
function SeleccionarFicherosFirmar()
{
	if(document.getElementById("spanAttachText").getElementsByTagName("LI").length>0)
	{
		AbrirFormSeleccAdjuntosFirmar('');
	}	
}
function SeleccionarImagen(sCampoImagen, e)
{
	
	var targ;
	if (!e)
	{
	  var e = window.event;  	  
	}
	if (e.target)
	{
	  targ=e.target;
	}
	else if (e.srcElement)
	{
	  targ=e.srcElement;
	}
	if (targ.nodeType==3) // defeat Safari bug
	{
	  targ = targ.parentNode;
	}
	targ = targ.parentNode.parentNode.parentNode;	
	AbrirFormSeleccAdjuntos(sCampoImagen,targ);
}
function AbrirFormSeleccAdjuntosFirmar(sCampoImagen)
{
	var oFormLink,oAttachments,i,oCampoOri,oCampoDes,iLeft,iTop,iWidth,iHeight
	var sFeatures,sEnlace,sEstilo,iIni,iFin,iNumCampAtt, sNumero,sFirma,i2,sListaFicheros;
	
	
	
	//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));
		
	//Miramos si ya existe algun elemnto firma sino lo creamos
	if(!document.getElementById('spanAttachFirmas'))
	{
		oCampoDes      = document.createElement('SPAN');
		oCampoDes.name = 'spanAttachFirmas';
		oCampoDes.id   = 'spanAttachFirmas';		
		document.getElementById('spanAttachFiles').parentNode.insertBefore(oCampoDes,null);		
	}
	//Añadimos todos los campos que hay en los ficheros adjuntos	
	oAttachments = document.getElementsByTagName('span');
	iNumCampAtt=0;
	sListaFicheros = "";
	
	for (j=0; j<oAttachments.length; j++)
	{
		if(oAttachments.item(j).id.substring(0,15) == 'spanAttachFiles')
		{						
			
			//Buscamos los parametros nombre y firma de los ficheros y se los pasamos al formulario
			//Solo copiamos nombre y firma
			for(i=0;i<oAttachments.item(j).childNodes.length-1;i=i+4)
			{
				i2 = 0;
				while(i2<4)
				{
					//Creamos un campo oculto y lo anadimos al formulario con el nombre
					oCampoOri       = oAttachments.item(j).childNodes.item(i+i2);					
					oCampoDes       = crearCampoForm('INPUT',oCampoOri.name);
					oCampoDes.setAttribute('type','hidden');
					oCampoDes.setAttribute('value',oCampoOri.value);
					if (oCampoOri.name != undefined)
						oFormLink.appendChild(oCampoDes);		
					i2++;
				}
				//Añadimos el nombre a la lista  pasada
				sListaFicheros += oCampoOri.name +"|";
				//Cogemos el identificador de fichero
				sNumero = oCampoDes.name.replace(/fileAttach/g,'');
				//generamos el campo para guardar la firma o simplemente lo añadimos al formulario si ya existe
				sFirma = document.getElementsByName("fileAttachFirma"+sNumero);		
				
				//Miramos Navegador debido al uso defectuso de la funcion createElement de IE que no permite generar atributo nombre
			
			
			    oCampoDes = crearCampoForm("INPUT", "fileAttachFirma"+sNumero);			   		
				oCampoDes.setAttribute('type','hidden');
				if(sFirma.length == 1)
				{
					oCampoDes.setAttribute('value',sFirma[0].value);					
					oFormLink.appendChild(oCampoDes);	
				}
				else
				{			
										
					oCampoDes.setAttribute('value','false');					
					oFormLink.appendChild(oCampoDes);					
					document.getElementById("spanAttachFirmas").appendChild(oCampoDes)
				}
				
				iNumCampAtt++;	
			}
				
				
		}
		
	}
	//Guardamos cuantos adjuntos tenemos
	
	oCampoDes=document.createElement('INPUT');
	oCampoDes.type='hidden';
	oCampoDes.name  = 'ListaFicheros';
	oCampoDes.value = sListaFicheros;	
	oFormLink.appendChild(oCampoDes);	
	
	// existe al menos un <span> para tener información de documentos / imágenes adjuntos
	if (iNumCampAtt > 0)
	{
		//Obtenemos las coordenadas de la nueva ventana
		iWidth=450;
		iHeight=350;
		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;

		sFeatures="height=" + iHeight + ",width=" + iWidth + ",left=" + iLeft + ",top=" + iTop + ",directories=no,status=yes,toolbar=no,menubar=no,location=no,resizable=yes,titlebar=no,scrollbars=yes"
		winAttachEDF=window.open('about:blank','winAttachSign',sFeatures);
		sEnlace='../src/asp/selecFicheros/firmarFicheros.asp';


		// ARL 13/09/06 >> Añadir los parametros a la URL
	 	if (sCSS.length>0)	
			// Ya nos habian indicado el css (la variable sCSS esta definida en absBase.js)
			sParamEstilo = '?css=' + sCSS;
		else
		{		
			// ARL 13/09/06 >> Si no nos han indicado un CSS, se coge el ultimo definido en la pagina (el de mas bajo nivel). Se
			// corrige una incidencia que provocaba error si en la cabecera se definia un <STYLE>
			if(document.styleSheets.length>0)
			{sEstilo=document.styleSheets.item(document.styleSheets.length-1).href;}			
			if(sEstilo == null)
			{sEstilo="";}

			var i = 2;
			var sParamEstilo = "";
			while ((sEstilo == "") && (i <= document.styleSheets.length))
			{
				sEstilo=document.styleSheets.item(document.styleSheets.length-i).href;
				i++;
			}
			if (sEstilo != "")
			{
						iIni=sEstilo.lastIndexOf('/');
						iFin=sEstilo.lastIndexOf('.');
						if ((iIni>=0) && (iFin>=0) && (iIni<iFin))
							sParamEstilo = '?css=' + sEstilo.substr(iIni+1,iFin-iIni-1);
			}
		}
		if (sParamEstilo != "")
				sEnlace = sEnlace + sParamEstilo + '&img=' + sCampoImagen;
		else
				sEnlace = sEnlace + '?img=' + sCampoImagen;

		oFormLink.action=sEnlace;
		oFormLink.target='winAttachSign';
		oFormLink.method = 'POST';
		oFormLink.submit();
		if (winAttachEDF) winAttachEDF.focus();
	}
}
var gNumAdjuntos=0;
function EstablecerValorCampoImagen(theForm,nombreCampo,valorCampo) 
{     	
  var oHiddenImg, oTextoSpan, oFilesSpan;
  var sName,aElemAux,aListas,i;
  var bValorCompuesto;
  var aFirma,sFirma,oSpanFirmas

  try
  {
   	oHiddenImg=theForm.getElementById(nombreCampo);
  	if (oHiddenImg) 
  		oHiddenImg.value = valorCampo;
  	
		aFirma = valorCampo.split('|$|');
		if(aFirma.lenght>0)
		{
			sFirma = aFirma[1]			
		}
		sFirma = false;
		valorCampo = aFirma[0]
		aListas=aFirma;
  	
 		var oSpanCampos,oSpanTexto,oCampo,sTexto;

		//Buscamos donde hay que anadir los campos
		oSpanCampos=document.getElementById('spanAttachFiles' + nombreCampo);	
		oSpanFirmas=document.getElementById('spanAttachFirmas');
		
		if (oSpanCampos)
		{
			//Anadimos los campos
			
			
			oCampo = crearCampoForm('INPUT','fileAttach' + gNumAdjuntos);
			oCampo.setAttribute('type','hidden');
			oCampo.setAttribute('value',aListas[5]);			
			oSpanCampos.appendChild(oCampo);
			
			
			oCampo = crearCampoForm('INPUT','fileAttach' + gNumAdjuntos);
			oCampo.setAttribute('type','hidden');
			oCampo.setAttribute('value',0);			
			oSpanCampos.appendChild(oCampo);	
			
	
			oCampo = crearCampoForm('INPUT','fileAttach' + gNumAdjuntos);
			oCampo.setAttribute('type','hidden');
			oCampo.setAttribute('value',aListas[4]);			
			oSpanCampos.appendChild(oCampo);			
			
			oCampo = crearCampoForm('INPUT','fileAttach' + gNumAdjuntos);
			oCampo.setAttribute('type','hidden');
			oCampo.setAttribute('value',nombreCampo);			
			oSpanCampos.appendChild(oCampo);
			
				
			//Actualizamos la descripcion
			oSpanTexto=document.getElementById('spanAttachText' + nombreCampo);
			if (oSpanTexto)
			{
				//Creamos la UL si no existe
				if(oSpanTexto.getElementsByTagName("ul").length < 1)
				{
					oCampo = document.createElement('UL');
					oSpanTexto.appendChild(oCampo);				
				}
				oSpanTexto = oSpanTexto.getElementsByTagName("ul")[0];
				
				oCampo=crearCampoForm('LI','fileAttachLi' + gNumAdjuntos);
				oCampo.id='fileAttachLi' + gNumAdjuntos;
				oCampo.innerHTML = aListas[5];
        
				if(sFirma)
				  oSpanTexto.innerHTML+="<span><img alt='Firmado'  src='"+document.getElementsByName('imagenFirmados')[0].value+"'/><span>";
				  
				oSpanTexto.appendChild(oCampo);
			}
			gNumAdjuntos++;			
			
			if(!document.getElementById('spanAttachFirmas'))
			{
				oCampo      = document.createElement('SPAN');
				oCampo.name = 'spanAttachFirmas';
				oCampo.id   = 'spanAttachFirmas';		
				document.getElementById('spanAttachFiles').parentNode.insertBefore(oCampoDes,null);		
			}
				
			
		}
  }
  catch(ex)
  {
  }
}

function EstablecerValorListaAdjuntos(theForm, listaAdjuntos)
{
	
	var aFiles=listaAdjuntos.split('|$$|');
	var arrayFirmas;
	var vaFirmado = false;
	var aData;
	for (var i=0;i<aFiles.length;i++)
	{
		if (aFiles[i] != '')
		{
			arrayFirmas = aFiles[i].split('|$FIRMA$|');
			if(arrayFirmas.length == 1)
			{				
				vaFirmado = false;
			}
			else
			{
				vaFirmado = arrayFirmas[1];				
			}			
					
			
			aFiles[i] = arrayFirmas[0];
			aData     = aFiles[i].split('|$|');			
			descargarAdjuntoPasados(aData[0],aData[1],aData[2],aData[3],aData[4],aData[5],aData[aData.length - 1])
			AnadirFicheroAdjuntoFormulario('fileAttach'+gNumAdjuntos,aData[5],0,aData[4],'',vaFirmado);		
			gNumAdjuntos++;			
		}
	}
}


function descargarAdjuntoPasados(sIdEntidad,sNomTab,sTraGen,sOrden,sIdFichero,sOrigen,sIdioma)
{
	var sURL;
	var sParams;
	sParams = "sIdEntidad="+sIdEntidad+"&sNomTab="+sNomTab+"&sTraGen="+sTraGen+"&sOrden="+sOrden+"&sIdFichero="+sIdFichero+"&sOrigen=TraGen&sIdioma="+sIdioma;
	sURL    = "../src/asp/selecFicheros/DescargaFicheros.asp?"+sParams
	makePOSTRequest("../src/asp/selecFicheros/DescargaFicheros.asp", sParams); 		
}


function makePOSTRequest(url, parameters) {
      http_request = false;
      if (window.XMLHttpRequest) { // Mozilla, Safari,...
         http_request = new XMLHttpRequest();
         if (http_request.overrideMimeType) {
         	// set type accordingly to anticipated content type
            //http_request.overrideMimeType('text/xml');
            http_request.overrideMimeType('text/html');
         }
      } else if (window.ActiveXObject) { // IE
         try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
         } catch (e) {
            try {
               http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
         }
      }
      if (!http_request) {
         alert('Cannot create XMLHTTP instance');
         return false;
      }
      //http_request.onreadystatechange = function(){if ( http_request.readyState == 4 ) {alert(http_request.responseText);return http_request.responseText;}};
      http_request.open('POST', url, false);
      http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      http_request.setRequestHeader("Content-length", parameters.length);
      http_request.setRequestHeader("Connection", "close");
      http_request.send(parameters);	 
	  return http_request.responseText;	  
		
   }
//////////////////////////////////////////////////////////////////////////////////////////
// GESTIÓN DE LA FIRMA
//////////////////////////////////////////////////////////////////////////////////////////
var oFirma;

function objetoFirma()
{
	var respuesta;
    this.sXmlDoc;                      //XML que generaremos con la firma y su información.
	this.signature;					 //Campo donde guardaremos el xml con la firma
	this.theForm;					 //Formulario con la informacion
	this.absArchivo      = 'N';      //S | N
	this.proveedor       = '';//CatCert (Agencia Catala de Certificació) | Afirma( @Firma) | ACCV(Autoritat de Certificació de la Comunitat Valenciana)
	this.avisar          = 'N';	     //S | N
	this.ejecutar        = 'N';      //S | N
	this.estilo          = 'GRIS';   //GRIS | AZUL
	this.timestamp       = 'N';      //S | N
	if(window.location.href.lastIndexOf("?")>0 || window.location.href.lastIndexOf("#")>0)
	{
		respuesta = window.location.href;		
		if(respuesta.lastIndexOf("?")>0)
		{
			respuesta =  respuesta.substring(0,window.location.href.lastIndexOf("?"))
		}
		if(respuesta.lastIndexOf("#")>0)
		{
			respuesta =  respuesta.substring(0,window.location.href.lastIndexOf("#"))
		}		
	}
	else
	{
		respuesta = window.location.href;
	}
	this.urlRespuesta    = respuesta +'/../../../forms_base/FirmaRespuesta.asp';       
	this.targetRespuesta = 'frmRespuestaFirma';
	this.identificadores =''         //cadena de identificadores de documentos adjuntos firmados
	this.firmas          =''         //cadena de firmas de documentos adjuntos firmados
	this.NIF             = ''         // NO Filtraremos por DNI
	if(document.getElementsByName("WTXNIFUSU").length>0)
	{		
		this.NIF = document.getElementsByName("WTXNIFUSU")[0].value//Filtraremos por DNI introducido al EDIWEB
	}
	if(this.NIF =='' && document.getElementsByName("WTXDNIFIR").length>0)
	{		
		if(document.getElementsByName("WTXDNIFIR")[0].value.length > 0)
		{
			this.NIF   = document.getElementsByName("WTXDNIFIR")[0].value//Filtraremos por DNI del certificado
		}
		var NIFUSU = crearCampoForm("input","WTXNIFUSU");
		NIFUSU.setAttribute("type","hidden");
		NIFUSU.value = this.NIF;
		document.getElementsByName("WTXDNIFIR")[0].parentNode.insertBefore(NIFUSU, document.getElementsByName("WTXDNIFIR")[0]);
	}
	this.vaFirmado       = false     //marca si el tramite ira firmado o no (no editar lo marca el ediweb)
	this.ventana          //refernecia a la ventana de firma
	this.realizada = false;
}
function hayElementoFirma(theForm)
{
	//*** OOF 22/05/8
	//Miramos si estamos loginados con certificado o si tenemos algun attachment a firmar
	return 	(firmarElTramite(theForm) || hayAdjuntosAFirmar(theForm));
}
function firmarElTramite(theForm)
{
	//*** OOF 22/05/8
	//Miramos si estamos loginados con certificado por lo que tenemos que firmar el tramite
	return (theForm.elements.namedItem('FIRMA_SOLICITUD')!=null);
}
function hayAdjuntosAFirmar(theForm)
{
	//*** OOF 22/05/8
	//Miramos si se ha decidido firmar algun adjunto
	
	var input;
	var i = 0;
	var hayadjuntos = false;
	
	//input = theForm;
	if (theForm.name != "")
	{
		input = document.getElementsByName(theForm.name)[0].getElementsByTagName("input");
		while(i<input.length && !hayadjuntos)
		{				
			if(input[i].type=="hidden" && (input[i].id.substring(0,15)=="fileAttachFirma" || input[i].name.substring(0,15)=="fileAttachFirma") )
			{
				if(input[i].value == "true")
				hayadjuntos = true;
			}
			i++;
		}
		if(hayadjuntos)
		{
			if(document.getElementsByName("frmRespuestaFirma").length == 0)
			{
				hayadjuntos = false;
			}
		}
	}
	return 	hayadjuntos;
}
function hayElementoIdCertificado(theForm)
{
	return 	(theForm.elements.namedItem('ID_CERTIFICADO').value!="#|#");
}

function firmar(theForm,oEvent)
{
	// OOF 05/05/2008
	//Se crea de nuevo para usuar el WebService de firma  ( Proyecto:IDiCCOFIRM )  
	var name,value;
	var sXmlCampo,sTextoAFirmarTemp,sFirma;
	var bTipoLista,bTipoSubLista
	var numElems,z;
	var aCod;
	var oBtnAceptar,oBtnAtras;
	var sIdEntidad,sIdioma;
	var bOk,bJaDecimal;
	var iNumDecimales,sXmlDocTemp,oFormLink;
	var parentFormLink,bQuitadoFormLink;
	
	//NRG 26/06/2008 >> Ponemos la cortina de espera.
	PonerCortinaEspera(strFirmando);
	
	
	//OOF 03/10/2008 >> quitamos el formulario usado para pasar los datos a las asp de adjuncion i firma de archivos
	oFormLink = document.getElementById('frmLink');
	if (oFormLink != null)
	{	
		if(oFormLink.length > 0)
		{
			parentFormLink = oFormLink.parentNode;
			parentFormLink.removeChild(oFormLink);
			bQuitadoFormLink = true;
		}
	}
	
		
	oFirma = new objetoFirma();
	oFirma.theForm   = theForm;
	oFirma.signature = oFirma.theForm.FIRMA_SOLICITUD;	
	oFirma.vaFirmado = firmarElTramite(theForm);
	

	//Rellenamos el campo e identificadores
	buscarIdentificadoresFirma();
	
	bOk=true;
	sTextoAFirmarTemp="";
	sXmlDocTemp="<datosFirma><campos>";
 
	//Obtenemos la entidad y el idioma
	if (theForm.elements.namedItem('WTGCODENT'))
	{
		sIdEntidad=theForm.elements.namedItem('WTGCODENT').value;
	}
    if (theForm.elements.namedItem('WTGIDIOMA'))
	{
		sIdioma=theForm.elements.namedItem('WTGIDIOMA').value;     
	}
	value=theForm.elements[0].value;
	//Recorremos los campos mirando cuales deben entrar en la firma
	for (i = 0; i < theForm.length; i++) 
	{		
		bTipoLista    = false;
		bTipoSubLista = false;
		bJaDecimal    = false;
		//oCampo contiene el campo actual
		oCampo = theForm.elements[i];      
		name   = theForm.elements[i].name;
		value  = Trim(theForm.elements[i].value);
		
		if (name)
		{
			if ((name.substr(0,4) != "RFS_")&&((name.substr(0,3) != "WTS")))
			{
				numElems = document.getElementsByName(name).length;
				if (!numElems){numElems=1;}
				/* ARL 11-01-07 >> Comprobar si se trata de un campo que se ha de guardar en BD. Si no es así, no se ha */
				/* de incluir en el cálculo de la firma */
				var bIncluirEnFirma = true;
				if (numElems>=9 && document.getElementsByName(name)[8].value == 'false')
				{
					// El campo está configurado para que no se guarde en BD
					bIncluirEnFirma = false;
				}
				//OOF 18703/09 -> si se trata de una check que no se debe guardar
				if (numElems>=8 && document.getElementsByName(name)[0].value == 'boolean' &&  document.getElementsByName(name)[7].value == 'false')
				{
					// El campo está configurado para que no se guarde en BD
					bIncluirEnFirma = false;
				}
				if (bIncluirEnFirma)
				{
					z=-1;
					//ARL 10/10/06 >> Si se trata de un decimal, ponemos una marca en el campo para que al comprobar la firma se sepa
					//que se ha de utilizar la coma como separador del valor decimal
					if ( (numElems>=9) && (document.getElementsByName(name)[1].value == 'decimal') && (value!="") )
					{						
						sXmlCampo="<campo dec='"+document.getElementsByName(name)[2].value+"'>" + name + "</campo>"
						bJaDecimal = true;
					}
					//NRG 5/11/07 >> Puede ser 3 o 4 en caso de tratarse de fichero adjunto
					if (numElems==3 || numElems==4)
					{
						//Es un fichero adjunto, obtenemos su contenido	
						//IMPORTANTE
						//OOF 03/10/2008 >> Se quita la concatenacion de los ficheros en la firma del tramite.											
						//name  = theForm.elements[i+2].value;
						//value = ObtenerContenidoFichero(sIdEntidad,sIdioma,theForm.elements[i+2].value,"N");
						value = "";
						//Descodificamos los adjuntos para codificarlos todos juntos.
						//value = Base64.decode(value);
						//sXmlCampo="<fichero>" + name + "</fichero>";
					}
					else
					{
						if(!bJaDecimal)
						{sXmlCampo="<campo dec='0'>" + name + "</campo>";}
					}
					if (numElems==8)
					{
						//Si hay 8 parametros, se trata de una check que no ha sido marcada
						z=1;
						value='N';
					}
					
					if (numElems>=9)
					{
						z=2;
						//ARL 10/10/06 >> Si se trata de un numérico decimal, formateamos el valor añadiendo los ceros decimales necesarios
						//al final en función de la longitud. Esto es necesario porque el valor almacenado en BD tendrá todos los ceros decimales
						//al final, y si al firmar no se tienen en cuenta posteriormente la validación de la firma no será correcta
						//Forzamos a que el separador decimal sea una ',', para evitar problemas de configuración regional. En la intratramites, al
						//recuperar el valor de la BD, tambien usaremos como separador decimal la coma para comprobar la firma
						if ( (document.getElementsByName(name)[1].value == 'decimal') && (value!="") )
						{						
							iNumDecimales = document.getElementsByName(name)[2].value;
							value = FormatearDecimal(value,iNumDecimales);
						}
						
						
						if(document.getElementsByName(name)[0].getAttribute("type") == "checkbox")
						{
							//ARL 15/01/2007 >> Corrección para el caso de formularios sin documento de validación previo a la confirmación
							//SERGIO MANZANO PEREZ 26/02/2008 INI 
							if(document.getElementsByName(name)[0].getAttribute("checked")!= "")
							{
								if ( (document.getElementsByName(name)[1].value == 'boolean'))
								{
									if (document.getElementsByName(name)[0].checked == 'checked' || document.getElementsByName(name)[0].checked == true)
										value = "S";
									else
										value = "N";
								}
							
							}
						}
						else if(!bJaDecimal)
						{
							//OOF 31/09/2008 >> Corrección para el caso de campos hidden sin la check
							value = document.getElementsByName(name)[0].value;
						}
						//SERGIO MANZANO PEREZ 26/02/2008 FIN
						//ARL 15/01/2007 >> Si es un tipo de datos fecha con calendario, hay un botón entremedio de los input
						if (theForm.elements[i+1].name == 'btn_'+name)
						{
							i++;
						}
					}
					
					if (z>0)
					{
						if(numElems>=z+8)
						{
							//Se trata de un campo de tipo lista o subLista, recuperamos sólo el codificador
							if (value!="")
							{
								aCod=value.split('-');
								value=aCod[0];
							}
						}
					}
					
					i=i+numElems-1;
					if (numElems!=1)
					{
						//ARL 18-01-06 >> Solo incluiremos los campos que tengan valor, es decir, aquellos que se han utilizado para firmar
						if (value!="")
						{						 
						  //OOF 09/10/2009 -> Si es una fecha y no tiene hora establecemos hora 00:00
						  if(document.getElementsByName(name)[1].value == "date" && document.getElementsByName(name + "1").length == 0)
						  {							
							value += " 00:00:00" 							
						  }
						  sXmlDocTemp += sXmlCampo;
						  //Decodificamos los archivos adjuntos para codificarlos concadenados
						  sTextoAFirmarTemp += Trim(value);
						}
						
					}
				}
				else
				{
					i=i+numElems-1;
				}
			}
		} 
	}	
	
			oFirma.sTextoAFirmar = sTextoAFirmarTemp.replace(/€/g,"&euro;");			
			oFirma.sXmlDoc = sXmlDocTemp;
			//FIRMA DE LA SOLICITUD
			var sName,oVentana,sUrl,submitForm,params,sIdentificadoresArray,i;
			
			submitForm = getNewForm();
			if(oFirma.vaFirmado)
			{
				oFirma.sTextoAFirmar = Base64Encode(oFirma.sTextoAFirmar);			
				createNewFormElement(submitForm, "doc", oFirma.sTextoAFirmar);		
			}
			//Añadimos los documentos marcados para firmar
			sIdentificadoresArray = oFirma.identificadores.split("|");
			i = 0;
			while(i<sIdentificadoresArray.length-1)
			{
				if(sIdentificadoresArray[i].length > 0)
				{
					name  = document.getElementsByName(sIdentificadoresArray[i])[2].value;
					value = ObtenerContenidoFichero(sIdEntidad,sIdioma,name,"S");
					createNewFormElement(submitForm, "doc", value);				
				}
				i++;
			}
			params = "?";
			params += "absArchivo=" + oFirma.absArchivo;			
			params += "&avisar="    + oFirma.avisar;
			params += "&ejecutar="  + oFirma.ejecutar;
			params += "&idioma="    + sIdioma;
			params += "&estilo="    + oFirma.estilo;
			params += "&timestamp=" + oFirma.timestamp;		
			params += "&urlRespuesta=" + escape(oFirma.urlRespuesta);		
			//params += "&targetRespuesta=_self";			
			if(oFirma.NIF != null && oFirma.NIF.length > 0)
			{
				params += "&nif=" + oFirma.NIF;
			}
			//alert(params);			
			
			//OOF 03/10/2008 >> Ponemos el formulario usado para pasar los datos a las asp de adjuncion i firma de archivos
			if(bQuitadoFormLink)
			{			
					parentFormLink.appendChild(oFormLink);
			}			
			sUrl = document.getElementsByName("CampoURLValidador")				
			if(sUrl.length < 1)
			{
				sUrl = "/ABSIS/IDI/CCO/IDICCOFIRMWEB/DLG/FIR/dlgFirmar.aspx"+params;
			}
			else
			{				
				sUrl = sUrl.item(0).value
				if(sUrl.indexOf("DLG/CER/dlgValidarCertificado.aspx") > -1)
				{					
					sUrl = sUrl.replace("DLG/CER/dlgValidarCertificado.aspx","DLG/FIR/dlgFirmar.aspx");		
				}
				else if(sUrl.indexOf("DLG/FIR/dlgFirmar.aspx") == -1)
				{
					if (sUrl.substr(sUrl.length-2,1)!="/")
					{
						sUrl = sUrl + "/"
					}	
					sUrl = sUrl + "DLG/FIR/dlgFirmar.aspx"				
				} 
				
				sUrl = sUrl + params;
				
			}
			submitForm.action=sUrl;
			sName='PopUpFirmar';
			submitForm.target=sName;
			oVentana = firma_AbrirVentana('about:blank',590,145,'yes',sName,true);
			submitForm.submit();
			if (oVentana) oVentana.focus();
			oFirma.ventana = oVentana;
			validarVentanaAbierta();
			return true;
}
function buscarIdentificadoresFirma()
{
	//OOF 14/05/08
	//Busca si hay algun documento para firmar, guarda la informacion del identificador en el objeto oFirma, y borra esta informacion del formulario
	var inputs,i,j;	
	var arrayIdentificadores = new Array();
	
	j = 0;
	inputs = document.getElementsByTagName('input');
	if(inputs.length > 0 )
	{
		for(i=0;i<inputs.length;i++)
		{
			if(inputs[i].type == 'hidden' && inputs[i].name.indexOf('fileAttachFirma') >= 0)
			{
				if(inputs[i].value == 'true')
				{
					oFirma.identificadores += inputs[i].name.replace('Firma','') + "|";
				}
				arrayIdentificadores[j] = inputs[i].name;
				j++;				
			}
		}
	}
	
}
function borrarIdentificadoresFirma()
{
	var inputs,i,j;
	var inputABorrar;
	var arrayIdentificadores = new Array();
	j = 0;
	inputs = document.getElementsByTagName('input');
	if(inputs.length > 0 )
	{
		for(i=0;i<inputs.length;i++)
		{
			if(inputs[i].type == 'hidden' && inputs[i].name.indexOf('fileAttachFirma') >= 0)
			{				
				arrayIdentificadores[j] = inputs[i].name;
				j++;				
			}
		}
	}
	//Borramos los inputs	
	i = 0;
	while(i<arrayIdentificadores.length)
	{	
		inputABorrar = document.getElementsByName(arrayIdentificadores[i])[0];
		arrayIdentificadores[i] = 'elim';
		inputABorrar.parentNode.removeChild(inputABorrar);		
		i++;
	}
}
function firma_AbrirVentana(sUrl,lWidth,lHeight,sResizable,sName,bSimple)
 {
	//*** OOF
	//Funcion que genera y abre(centrada a la pantalla)  la ventana flotante para pedir la información sobre que certificado usar y realizar la firma.
	//Se le pasa la Url a abrir el tamaño de la ventana, si queremos que se pueda modificar el tamaño, el nombre de la nueva ventana, y si queremos o no menus.
	var sFeatures,oVentana,lLeft,lTop;
	
	//Calculamos la posición de la ventana
	lLeft=0;
	lTop=0;
	if (lWidth!=0) lLeft=(screen.availWidth-lWidth)/2;
	else lWidth=screen.availWidth;
	if (lHeight!=0) lTop=(screen.availHeight-lHeight)/2;
	else lHeight=screen.availHeight;
	if (!bSimple)
	{
		if (lTop>100) lTop=lTop-100;
		else lTop=0;
	}
	
	//Abrimos la ventana
	sFeatures='top='+lTop+',left='+lLeft+',width='+lWidth+',height='+lHeight+',resizable='+sResizable; 
	if (bSimple) sFeatures=sFeatures + ',directories=no,menubar=no,status=no,toolbar=no';
	else sFeatures=sFeatures + ',directories=yes,menubar=yes,status=yes,toolbar=yes';
	
	oVentana=window.open(sUrl,sName,sFeatures);		
	return oVentana;
 }
 
 function validarVentanaAbierta()
 {	
	var dialog = oFirma.ventana;
	var realizada = oFirma.realizada;
	if(!realizada)
	{	
		if ( dialog != null ) 
		{
			if ( dialog.closed ) 
			{				
				CambiarTextoCortina(strEsperando);	
			}	
			else
			{
				setTimeout("validarVentanaAbierta()",1500);
			}
				
		} 		
	}
}

function firmarArchivos(inputs,popUp)
{
	//*** OOF
	//Funcion llamda desde el popUp de firmar, que sirve para detectar que nuevos checks se han marcado por lo tanto
	//deben ser marcados para ser firmados con la funcion poner candado
	var idArxiu;
	var cadena = "";
	var submitForm;
	var algunCheck = false;
	var fileAttachFirmas;
	var li,span;
	
	for(var i=0; i<inputs.length; i++)
	{
		if(inputs[i].getAttribute('type')=='checkbox')
		{
			if (inputs[i]["checked"])
			{				
				algunCheck = true;
				ponerCandado(inputs[i].name.replace('fileAttach',''));
			}			
		}
	}	
	popUp.close();
	return true;
}
function ponerCandado(Id)
{
	//*** OOF
	//Funcion que almazena en el formulario que el documento adjunto con Id debe ser firmado y ademas genera una imagen de un candado para diferenciarlo.
	var li,hidden,span;
	if(document.getElementsByName("fileAttachFirma"+Id))
	{
		hidden = document.getElementsByName("fileAttachFirma"+Id)[0];
		hidden.value = true;
	}
	if(document.getElementById("fileAttachLi"+Id))
	{
		li = document.getElementById("fileAttachLi"+Id);
		if(document.getElementsByName("imagenFirmados"))
		{
			if(li.getElementsByTagName("span").length==0 && document.getElementsByName("imagenFirmados")[0].value.length > 0)
			{				
				span = document.createElement("span")
				span.innerHTML = '<img alt="Firmado" src="'+document.getElementsByName("imagenFirmados")[0].value+'" border="0"/>';				
				li.appendChild(span);								
			}
		}
	}
	return true;
}
function borrarCandado(Id)
{
	//*** OOF
	//Funcion que borra la información sobre que un documento adjunto quiere ser firmado y su candado
	var hidden,span,li;
	if(document.getElementsByName("fileAttachFirma"+Id).length>0)
	{
		hidden = document.getElementsByName("fileAttachFirma"+Id)[0];
		hidden.parentNode.removeChild(hidden);
	}
	if(document.getElementById("fileAttachLi"+Id))
	{
		li = document.getElementById("fileAttachLi"+Id);
		if(li.getElementsByTagName("span").length>0)
		{
			span = li.getElementsByTagName("span")[0];
			span.parentNode.removeChild(span);
		}
	}
}

//*** OOF
//Funcion que llama el frame de la firma, para devolver el resultado
function CallBackFirmar(result)
{		
	oFirma.realizada = true;
	oFirma.ventana = null;
	if ((result == "") || (result == ";"))
	{
		oBtnAceptar=document.getElementById('btnAceptar');
		if (oBtnAceptar!=null) 
		{oBtnAceptar.disabled=false;}
		//Se ha producido error al firmar
		CambiarTextoCortina("Error al firmar");	
		setTimeout("QuitarCortinaEspera()",3000);
	}
	else if(result.indexOf("undefined")>-1)
	{
		oBtnAceptar=document.getElementById('btnAceptar');
		if (oBtnAceptar!=null) 
		{oBtnAceptar.disabled=false;}
		//Se ha producido error al firmar
		CambiarTextoCortina("Firma Erronea");	
		setTimeout("QuitarCortinaEspera()",3000);
	}
	else
	{
		CambiarTextoCortina(strEnviando);		
		CallBack_Firmar(result);
	}
}

function CallBack_Firmar(sFirma)
{
//*** OOF
//Funcion que se ejecuta una vez se ha realizado la firma, no s devuelve la información sobre la firma y continua la tramitacion del formulario
var bOk = true;
var tipoFirma;
var sFirmaArray;
var i,sIdentificadoresArray,idCampoFirma,hiddenFirma,hiddenTipoFirma;
var vaFirmado;


	remplazoEuros(oFirma.theForm);

	//OOF 03/10/2008 >> quitamos el formulario usado para pasar los datos a las asp de adjuncion i firma de archivos
	var oFormLink = document.getElementById('frmLink');
	if (oFormLink != null)
	{			
		if(oFormLink.length > 0)
		{oFormLink.parentNode.removeChild(oFormLink);}
	}
	
	//OOF 29/12/08 >> Borramos los identificadores una vez se ha firmado correctamente
	borrarIdentificadoresFirma();
//Cogemos el tipo de firma realizada
sFirmaArray = sFirma.split(";");
tipoFirma   = sFirmaArray[0];

	//Si el tramite va firmado
	if(oFirma.vaFirmado)
	{
		//Cogemos la firma de la solicitud,siempre estara en la posición 1
		sFirmaArray = sFirmaArray[1].split(",");
		sFirma = sFirmaArray[0];
		vaFirmado = 1;
	}
	else
	{
		sFirmaArray = sFirmaArray[1].split(",");
		vaFirmado = 0;
	}

//Recuperamos la firma de los documentos marcados para firmar si había
sIdentificadoresArray = oFirma.identificadores.split("|");
i = 0;
while(i<sIdentificadoresArray.length-1)
{
	
	if(sIdentificadoresArray[i].length > 0)
	{
		//Guardamos las firmas de los adjuntos en campos ocultos y el tipo de firma		
		hiddenFirma     = crearCampoForm('INPUT',sIdentificadoresArray[i].replace("fileAttach","fileAttachFirma"));		
		hiddenFirma.setAttribute('type','hidden');		
		hiddenFirma.setAttribute('value',sFirmaArray[i+vaFirmado])		
		document.getElementsByName(sIdentificadoresArray[i])[0].parentNode.appendChild(hiddenFirma);
	}
	i++;
}
//Insertem el tipus de firma
hiddenTipoFirma = crearCampoForm('INPUT','tipoFirma');	
hiddenTipoFirma.setAttribute('type','hidden');
hiddenTipoFirma.setAttribute('value',tipoFirma)	

var formulario = obtenerFormularioPadre();
formulario.appendChild(hiddenTipoFirma);



if (bOk)
	{
		if (!sFirma.length) 
		{
			bOk=false;
			CambiarTextoCortina("Error al firmar");	
			setTimeout("QuitarCortinaEspera()",2000);
		}
		if(sFirma.substr(0,5)=="error")
		{
			bOk=false;
			
			if (!(bFiltrado && sFirma=='error:internalError'))
			{
				if(sFirma=='error:noMatchingCert' && strNoHayCertificados)
				{
					alert(strNoHayCertificados);
				}
				else if(sFirma!='error:userCancel')
				{
					alert(sFirma);
				}
			}
		
		}
	}	
	if(!bOk )
	{
		oBtnAceptar=document.getElementById('btnAceptar');
		oBtnAtras=document.getElementById('btnAtras');
		if (oBtnAceptar!=null) oBtnAceptar.disabled=false;
		if (oBtnAtras!=null) oBtnAtras.disabled=false;
	}
	else
	{
			if(oFirma.vaFirmado)
			{
				oFirma.sXmlDoc += "</campos><tipoFirma>"+tipoFirma+"</tipoFirma><firma>" + sFirma + "</firma></datosFirma>";				
				oFirma.signature.value = oFirma.sXmlDoc;
			}			
			oFirma.theForm.submit();			
	}	
	return (bOk);
}
//OOF -> Sirve para sacar espacios en blanco del principio y final de las cadenas
function Trim(s)
{		
	s = s.replace(/^\s+|\s+$/g,""); //sacar espacios blanco principio y final
	return s;
}
//OOF -> Sirve para obtener el formulario que contiene los archivos adjuntos
function obtenerFormularioPadre()
{
	try
	{
		var encontrado = false;
		var actual = document.getElementById("spanAttachFiles");
		while(!encontrado)
		{
			if(actual.tagName == "FORM" && (actual.name=="frmConfirmacion" || actual.name=="frmTramite"))
			{
				encontrado = true;
			}
			else
			{
				actual = actual.parentNode;
			}
		}
	}
	catch(err)
	{
		if(document.getElementsByName('frmConfirmacion').length > 0)
		{
			actual = document.getElementsByName('frmConfirmacion')[0];
		}
		else
		{
			actual = document.getElementsByName('frmTramite')[0];
		}
	}
	return actual;
}

/* ******* Funciones utiles para la espera despues de firmar una solicitud *********** */
//NRG 26/06/2008 >>
function PonerRelojEspera()
{
	document.getElementById("pagina").style["cursor"] = "wait";
}
//NRG 26/06/2008 >>
function QuitarRelojEspera()
{
	document.getElementById("pagina").style["cursor"] = "default";
}
//NRG 19/08/2008
function PonerCortinaEspera(sMensaje)
{
	
	var IE6 = false /*@cc_on || @_jscript_version < 5.7 @*/;
	var IE7 = false /*@cc_on || @_jscript_version >= 5.7 @*/;
	
		window.scrollTo(0,0)
		document.documentElement.style.overflow = "hidden";
		cortina    = document.getElementById("panelCortina");
		dialogoNot = document.getElementById("dialogoNot");
		
		if(cortina == null || cortina == 'undefined')
		{	
			var cortina = document.createElement('div');
			cortina.className = "panelCortina";
			cortina.id = "panelCortina";
			var cuerpo = document.body;
			cuerpo.insertBefore(cortina, null);
		}		
		
		if(dialogoNot == null || dialogoNot == 'undefined')
		{
		var dialogoNot = document.createElement('div');
			dialogoNot.className = "dialogoNotSinGif";
			dialogoNot.id = "dialogoNot";
			cuerpo.insertBefore(dialogoNot, null);
		}		
		//ES IE6		
		if(document.all && !IE7)
		{			
			cortina.style["filter"] ="alpha(opacity=50)";
			cortina.style["backgroundColor"] = "#666666";
			cortina.style["backgroundImage"] = "none";	
			cortina.style["height"] = "10000px";							
		}		
		cortina.style["display"] = "block";
		cortina.style["cursor"] = "wait";		
		dialogoNot.style["display"] = "block";
		dialogoNot.style["cursor"] = "wait"
		dialogoNot.innerHTML = "<center>" + sMensaje + "</center>";	
}
//NRG 19/08/2008
function CambiarTextoCortina(sMensaje)
{
	try
	{
		//var IE6 = false /*@cc_on || @_jscript_version < 5.7 @*/;
		//if(!IE6)
		//{ 
			var dialogoNot = document.getElementById("dialogoNot");
			dialogoNot.style["display"] = "block";
			dialogoNot.innerHTML = "<center>" + sMensaje + "</center>";
			dialogoNot.className = "dialogoNotSinGif";
		//}
	}
	catch(err)
	{}
}
//NRG 19/08/2008
function QuitarCortinaEspera()
{
	//var IE6 = false /*@cc_on || @_jscript_version < 5.7 @*/;
	//if(!IE6)                                      
	//{
		var cortina = document.getElementById("panelCortina");
		cortina.style["display"] = "none";
		cortina.style["cursor"] = "default";
	
		var dialogoNot = document.getElementById("dialogoNot");
		dialogoNot.style["display"] = "none";
		dialogoNot.style["cursor"] = "default";
		document.documentElement.style.overflow = "auto";
	//}
	//else
	//{
		QuitarRelojEspera();
	//}
	
	
}
/* ****** FIN Funciones utiles para la espera despues de firmar una solicitud ********* */
 
function AñadirItemMultiLista(strNamePatron, strMaxCajasTxt)
	{ //ECA 14/07/2008 >> Función necesaria para el control Texto MultiEntrada.

		var oElemDivDatos, oElemDivTmp, oElemCampo;
		var strNombreCampo, strNombreLen, strNombreRaiz, strDivDatos, strDivTemp;
		var strHiddenCampo;
		var i, strSpan, sufijoId, sOrden;
		var intNum, NumMax;
		
		//Formato del  Div que contiene el formato que se insertará:
		strNombreLen =strNamePatron.length - parseInt(strMaxCajasTxt.substring(0,1));
		//si la variable es 'WTXTELEF0', strNombreRaiz será WTXTELEF;
		strNombreRaiz = strNamePatron.substring(0, strNombreLen);
			
		switch(strMaxCajasTxt.substring(0,1))
		{
			//Dependiendo del intervalo asignado inicialmente, en la configuración de los campos de este tipo, estructuraremos la información
			//para utilizarla posteriormente para insertar en el 'DivTmp' la información.
			case "1":
				//nombres de los divs que guardarán la información, strDivDatos contendrá el patrón que se duplicará en el divDatos, 
				//con el nombre correspondiente, cada vez que se inserte un valor nuevo.
				strDivDatos = "div_" + strNombreRaiz + "0_datos";
				strDivTemp = "div_" + strNombreRaiz + "0_TMP";
				//strNamePatron = strNombreRaiz + "0";
				//si la variable es 'WTXTELEF0', sufijoId será TELEF;
				sufijoId = strNamePatron.substring(3,8);
				intNum = "0";
				NumMax = 9;
			break;
			
			case "2":
				strDivDatos = "div_" + strNombreRaiz + "00_datos";
				strDivTemp = "div_" + strNombreRaiz + "00_TMP";
				//strNamePatron = strNombreRaiz + "00";
				sufijoId = strNamePatron.substring(3,7);
				//sLinea = strNamePatron.substring(7,9);
				intNum = "00";
				NumMax = 99;
			break;
			
			case "3":
				strDivDatos = "div_" + strNombreRaiz + "000_datos";
				strDivTemp = "div_" + strNombreRaiz + "000_TMP";
				//strNamePatron = strNombreRaiz + "000";
				sufijoId = strNamePatron.substring(3,6);
				//sLinea = strNamePatron.substring(6,9);
				intNum = "000";
				NumMax = 999;
			break; 
		}

		
		//Obtenemos el div que contiene la información patrón de los campos hidden.
		oElemDivDatos = document.getElementById(strDivDatos);	
		oElemDivTmp = document.getElementById(strDivTemp);
		
		//Asignamos un nombre a este nuevo campo insertado, dependiendo de los campos que ya existen insertados.
		sOrden = (oElemDivTmp.children.length)+1;
		
		if(sOrden <= NumMax)
		{
			sOrden += ''
			switch(strMaxCajasTxt.substring(0,1))
			{
				case "1":
				strNombreCampo = strNombreRaiz + "" + sOrden;
				//Campo por el que se cambiará el nombre del patrón.
				sLinea = strNombreCampo.substring(8,9);
				break;
				
				case "2":
					if (sOrden.length == 1)
					{
						strNombreCampo = strNombreRaiz + "0" + sOrden;
					}
					else
					{
						strNombreCampo = strNombreRaiz + "" + sOrden;
					}
					
					//Campo por el que se cambiará el nombre del patrón.
					sLinea = strNombreCampo.substring(7,9);
				break;
				
				case "3":
					if (sOrden.length == 1)
					{
						strNombreCampo = strNombreRaiz + "00" + sOrden;
					}
					if (sOrden.length == 2)
					{
						strNombreCampo = strNombreRaiz + "0" + sOrden;
					}
					if (sOrden.length== 3)
					{
						strNombreCampo = strNombreRaiz + "" + sOrden;
					}
					//Campo por el que se cambiará el nombre del patrón.
					sLinea = strNombreCampo.substring(6,9);
				break; 
			}
			
			//Lo insertamos en el lugar correcto.
			strHiddenCampo = oElemDivDatos.innerHTML;

			//Rodeamos con un span xa conocer el elemento en el elemento de la eliminación...
			strSpan = "<span id='span_" + strNombreCampo + "'  class = '' >" + document.getElementById("txt_" + strNamePatron + "_TMP").value + "<img class = '' src='../img/formularios/EditDelete2.gif' alt='Eliminar elemento' id='img_" + strNombreCampo + "' onclick=\"javascript:EliminarMultiCampo('" + strNombreCampo + "', '" + sufijoId + "' , '" + intNum + "')\"/> <BR>";
			
			//Insertamos el span con el nuevo elemento en el DivTmp, que será el que nos mostrará la información en la pagina.
			if (oElemDivTmp.innerHTML != undefined)
			{
				oElemDivTmp.innerHTML = oElemDivTmp.innerHTML + "" + strSpan + "" + strHiddenCampo + "</span>";	
			}
			else
			{
				oElemDivTmp.innerHTML = strSpan + "" + strHiddenCampo + "</span>";
			}
		
			//Lo modificamos
			oElemSpan = document.getElementById("span_"+ strNombreCampo);

			//Modificamos los nombres del patrón por el nombre del elemento que se esta insertando.
			oElemSpan.innerHTML = TextoMultiEntrada_ActualizarIdentificadoresHTML(oElemSpan.innerHTML, sufijoId, sLinea, intNum);
			oElemCampo = document.getElementById(strNombreCampo);
			oElemCampo.value = document.getElementById("txt_"+ strNamePatron +"_TMP").value;
			
			//Borramos la caja de texto para la insercción de un nuevo elemento
			document.getElementById("txt_"+ strNamePatron +"_TMP").value = "";
		}
		else
		{
			alert("El número de TextosMultiEntrada es superior al intervalo especificado inicialmente.");
		}
		
	}
	
function TextoMultiEntrada_ActualizarIdentificadoresHTML(txt, sufijoId, sLinea, intNum)
{
	//ECA 14/07/2008 >> Función necesaria para el control Texto MultiEntrada.
	//Modificamos mediante expresiones regulares los nombres del patrón por el nombre del elemento que se esta insertando.
    //var reg = new RegExp("(WTX" + sufijoId + ")00", "g");
	var reg = new RegExp("(WTX" + sufijoId + ")" + intNum , "g");
	var txt2 = txt.replace(reg, "$1"+sLinea);
	
    return txt2;
}

function EliminarMultiCampo(strCampo, sufijoId, intNum)
{
	var oElemDiv;
	
		
		var oElemRemove = document.getElementById("span_" + strCampo);
		// Obtenemos el padre de dicho elemento con la propiedad “parentNode”
		var padre = oElemRemove.parentNode;
		// Eliminamos el hijo (oElemRemove del elemento padre
		padre.removeChild(oElemRemove);
		
		OrdenarElementosMultiLista(strCampo, sufijoId, intNum);
}

function OrdenarElementosMultiLista(strCampo, sufijoId, intNum)
{
	var sOrden=1;
	var sOrden2=0;
	var NumSel;

	strNombreDiv = "div_WTX" + sufijoId + "" + intNum + "_TMP";

	var oElemDiv = document.getElementById(strNombreDiv);

	for (sOrden=1;sOrden<oElemDiv.childNodes.length+1;sOrden++)
	{
	switch(intNum.length)
		{
			case 1:
				sOrden2 = sOrden + "";
				NumElement = sOrden;
				NumSel = oElemDiv.childNodes(sOrden-1).id.split("span_WTX" + sufijoId)[1];
				oElemDiv.children(sOrden-1).outerHTML = TextoMultiEntrada_ActualizarIdentificadoresHTML(oElemDiv.children(sOrden-1).outerHTML, sufijoId, NumElement, NumSel);	
			break;
			
			case 2:
				sOrden2 = sOrden + "";
				if (sOrden2.length == 1)
				{
					NumElement = "0" + sOrden;
				}
				if (sOrden.length == 2)
				{
					NumElement = sOrden;
				}
				NumSel = oElemDiv.childNodes(sOrden-1).id.split("span_WTX" + sufijoId)[1];
				oElemDiv.children(sOrden-1).outerHTML = TextoMultiEntrada_ActualizarIdentificadoresHTML(oElemDiv.children(sOrden-1).outerHTML, sufijoId, NumElement, NumSel);	
			break;

			
			case 3:
				sOrden2 = sOrden + "";
				if (sOrden2.length == 1)
				{
					NumElement = "00" + sOrden;
				}
				if (sOrden.length == 2)
				{
					NumElement = "0" + sOrden;	
				}
				if (sOrden.length == 2)
				{
					NumElement = sOrden;
				}
				NumSel = oElemDiv.childNodes(sOrden-1).id.split("span_WTX" + sufijoId)[1];
				oElemDiv.children(sOrden-1).outerHTML = TextoMultiEntrada_ActualizarIdentificadoresHTML(oElemDiv.children(sOrden-1).outerHTML, sufijoId, NumElement, NumSel);	
			break;
		}
	}
}

function InsertAutoComplete()
	{	
		//ECA >> Función Ajax que se conectará con el WebService y devolverá los resultados  para completar el autocompletador.
		
		var iCampo, jSubCampo, NumSubCampos;
		var NombresSubCampos = "";
		var NomSubCamp = "";
		var sNombreSubCampo="";
		var NomSubCampBD = "";
		var VisibleAutoComplet = "";
		var TipoDatoSubCampo = "";
		//var NumSubCampos;
		//Guardamos la información de todos los campos para pasarsela por url.
		//A nivel de CAMPOS
		for (iCampo=0; iCampo<= aCampoAjax.length-1; iCampo++)
		{
		sNombreCampo = aCampoAjax[iCampo];

		//Guardamos informacion necesaria del control bajo el cual se realizara la consulta dentro del autocompletador. 
		//Es decir, el primer subcampo será el que 'mandará'
		NomSubCamp = "NombreSubCampo0=" + sNombreCampo;
		NomSubCampBD = "NombreCampoBD0=" + aDetalleAjax[sNombreCampo]['campoBD'][0];
		VisibleAutoComplet = "visibleCompletador0=" + aDetalleAjax[sNombreCampo]['visibleComplet'][0];
		TipoDatoSubCampo = "tipoDatos=" + aDetalleAjax[sNombreCampo]['tipoDato'][0];
		
		NumSubCampos = aDetalleAjax[sNombreCampo]['campoForm'].length
			//A nivel  de subcampos
			for(jSubCampo=1; jSubCampo<=NumSubCampos-1; jSubCampo++)
			{
				//Aqui guardamos el nombre del campo dentro del formulario, asi con el nombre del campo dentro de la base de datos.
				NomSubCamp= NomSubCamp + "&NombreSubCampo"+jSubCampo+ "=" + aDetalleAjax[sNombreCampo]['campoForm'][jSubCampo];
				NomSubCampBD = NomSubCampBD + "&NombreCampoBD"+jSubCampo+ "=" + aDetalleAjax[sNombreCampo]['campoBD'][jSubCampo];
				VisibleAutoComplet = VisibleAutoComplet + "&visibleCompletador"+jSubCampo+ "=" + aDetalleAjax[sNombreCampo]['visibleComplet'][jSubCampo];
				TipoDatoSubCampo = TipoDatoSubCampo + "&tipoDatos"+jSubCampo+ "=" + aDetalleAjax[sNombreCampo]['tipoDato'][jSubCampo];
			}

			var urlASP= "../../forms_base/ConsultaAJAX.asp?codigoWeb=" + aDetalleAjax[sNombreCampo]['web'] + "&codigoConsulta=" +aDetalleAjax[sNombreCampo]['met'] + "&tipo=" + aDetalleAjax[sNombreCampo]['tpc'] + "&WebService=" + aDetalleAjax[sNombreCampo]['ws'] + "&NumSubCampos=" + NumSubCampos + "&" + NomSubCamp + "&" + NomSubCampBD + "&" + VisibleAutoComplet + "&" + TipoDatoSubCampo + "";
			var idtargetDIV='targetLst_' + sNombreCampo;
			var htmltargetDiv='<div id="'+idtargetDIV+'" class="auto_complete" ></div>';
			
				var getItemUpdate= function(resp){
				//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.
	    		var oNode=resp //document.getElementById(resp.id);
				var NumSubCampos = oNode.parentNode.getAttribute("NumSubCampos")
				var sLista = oNode.parentNode.getAttribute("listaCampos") 
				var aLista = sLista.split('|');
				var i, CampoSeleccion;
				
					//Por cada campo que contiene este control Ajax, recogeremos el valor seleccionado y lo insertaremos 
					//en la caja de texto correspondiente.
					for(i=0; i <= NumSubCampos-1; i++)
					{
					CampoSeleccion = document.getElementById(aLista[i]);
					CampoSeleccion.value=oNode.getAttribute(aLista[i])
					}

				}
			new Insertion.After(sNombreCampo, htmltargetDiv);
			new Ajax.Autocompleter(sNombreCampo, idtargetDIV, urlASP, {updateElement: getItemUpdate});
		}  	
    }
	
	function InsertSeccionBusqueda()
	{	
		//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 sNombreCampo = "";
		var iCampoBusq, jSubCampo, NumSubCampos
		var sBusqSubForm = "";
		var sBusqSubCons = "";
		var sBusqueda = "";
		var sNombreMaestro = "";

		//Guardamos la información de todos los campos para pasarsela por url.
		//A nivel de <busqAutoCompletadores>
		for (iCampoBusq=0; iCampoBusq<= aCampoBusq.length-1; iCampoBusq++)
		{
		sNombreCampo = aCampoBusq[iCampoBusq];

		//Guardamos la informacion del 'campo Maestro', que será el parametro que definirá al consulta.
		sNombreMaestro = aDetalleBusq[sNombreCampo]['CampoMaestro'];
		sTipoBusq = aDetalleBusq[sNombreCampo]['TipoBusq'];
		sOperadorBusq = aDetalleBusq[sNombreCampo]['OperadorBusq'];
		
		//Recogemos el texto que el usuario inserta en la caja de texto.
		sBusqueda = document.getElementById(sNombreCampo).value;
		
		
		NumSubCampos = aDetalleBusq[sNombreCampo]['CampoBusqForm'].length;
			//A nivel  de subcampos
			for(jSubCampo=0; jSubCampo<=NumSubCampos-1; jSubCampo++)
			{
				//Guardamos la informacion de cada subcampo de la seccion.
				sBusqSubForm = sBusqSubForm + "&BusqSubForm"+jSubCampo+ "=" + aDetalleBusq[sNombreCampo]['CampoBusqForm'][jSubCampo];
				sBusqSubCons = sBusqSubCons + "&BusqSubCons"+jSubCampo+ "=" + aDetalleBusq[sNombreCampo]['CampoBusqCons'][jSubCampo];
			}

			var urlASP= "../../forms_base/ConsultaAJAX.asp?codigoWeb=" +aDetalleBusq[sNombreCampo]['web'] + "&codigoConsulta=" +aDetalleBusq[sNombreCampo]['met'] + "&tipo=" + aDetalleBusq[sNombreCampo]['tpc'] + "&WebService=" + aDetalleBusq[sNombreCampo]['ws'] + "&NumSubCampos=" + NumSubCampos +"&TipoCampo=SeccionBusqueda&NombreCampoMaestro=" + sNombreMaestro + "&TipoBusq=" + sTipoBusq + "&OperadorBusq=" + sOperadorBusq + "" + sBusqSubForm + "" + sBusqSubCons + "&sBusqueda=" + sBusqueda + "&NombreCampo=" + sNombreCampo;
			
				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, CampoEdicion, jSubCampo, CampoSubForm, iXml;
			    		var oNode=resp;
						
						
						if (NavegadorIE())
						{
							oElement = oNode.responseXML.selectSingleNode('//SeccionBusq');
							CampoEdicion = oElement.getAttribute("NombreCampo");
						}
            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];
							CampoEdicion = oElement.getAttribute("NombreCampo");
						}
						NumSubCampos = aDetalleBusq[sNombreCampo]['CampoBusqForm'].length;

						for(jSubCampo=0; jSubCampo<=NumSubCampos-1; jSubCampo++)
						{
							//Guardamos la informacion de cada subcampo de la seccion.
							sBusqSubForm = aDetalleBusq[CampoEdicion]['CampoBusqForm'][jSubCampo];
							sBusqSubCons = aDetalleBusq[CampoEdicion]['CampoBusqCons'][jSubCampo];
							
              
              if (NavegadorIE()){                
			  if(oElement.selectSingleNode(sBusqSubCons))
                  //document.getElementById(sBusqSubForm).value = oElement.selectSingleNode(sBusqSubCons).text; 
				  if (sBusqSubCons.match("DNINIF")){ //Caso específico eAtiende, para cargar el campo del DNI con letra.
					EstablecerValorCampo(window.document, sBusqSubForm, CalculaNIFeAtiende(oElement.selectSingleNode(sBusqSubCons).text), '=');
				  }else{
					EstablecerValorCampo(window.document, sBusqSubForm, oElement.selectSingleNode(sBusqSubCons).text, '=');
				  }
              }
              else{
			  	  if (sBusqSubCons.match("DNINIF")){ //Caso específico eAtiende, para cargar el campo del DNI con letra.
					EstablecerValorCampo(window.document, sBusqSubForm, CalculaNIFeAtiende(oElement.getElementsByTagName(sBusqSubCons)[0].textContent), '=');
				  }else{
					EstablecerValorCampo(window.document, sBusqSubForm, oElement.getElementsByTagName(sBusqSubCons)[0].textContent, '=');
				  }
                
              }
							/*if (NavegadorIE())
							{		
							document.getElementById(sBusqSubForm).value = oElement.selectSingleNode(sBusqSubCons).text; 
							}
							else{
							 document.getElementById(sBusqSubForm).value = oElement.getElementsByTagName(sBusqSubCons)[0].textContent;
							}*/
						}	
					}		
				}
			new Ajax.Request(urlASP, {  method: 'get', onComplete: getItemUpdate,
													   onFailure: function() {alert(strNoRegistros)}});
		}  	
  }
  
// Single sign-on login

function SingleSignOn(sUrlWS)
{
   var sHostUrl, sHostWS;

   sHostUrl = window.location.href.substr(0, window.location.href.indexOf('/', 8));
   sHostWS = sUrlWS.substr(0, sUrlWS.indexOf('/', 8));


  // Independientemente de la configuración y de los tipos de login de la página, siempre se intentará recuperar los datos
  // del usuario via single-sign-on, porque si estos no están disponibles o no hay ningún login via usuario y password,
  // pues simplemente no se hace nada

	if (document.getElementsByName("WTGCODENT").length > 0 && document.getElementsByName("WUSCODUSU").length > 0 && document.getElementsByName("WUSPINUSU").length && sHostUrl == sHostWS)
	{
		// Llamamos al Servicio Web SrvWebTraFtp
		
	// Si tenemos un tipo de login denominado LOGINEATI, buscaremos al usuario entre los usuarios de eConstruye/ePlataforma (tabla WETUSUARI)
    // En caso contrario buscamos en la tabla _TABLOGIN, és decir, usuarios registrados en la Web
    var reg = /login=.*LOGINEATI/i
    
    if (reg.test(window.location.search))
     	sUrlWS=sUrlWS + '/SrvLDAP.asmx/LoginLDAPeConstruye?sEntidad=' + document.getElementsByName("WTGCODENT")[0].value;
  	else
  		sUrlWS=sUrlWS + '/SrvLDAP.asmx/LoginLDAP?sEntidad=' + document.getElementsByName("WTGCODENT")[0].value;

		

		if (NavegadorIE()) xmlHttpReq = new ActiveXObject("MSXML2.XMLHTTP");
		else xmlHttpReq = new XMLHttpRequest();
		 
		xmlHttpReq.open("GET", sUrlWS, false);
		xmlHttpReq.send("");
		if (xmlHttpReq.responseXML!=null)
		{
			var sUser, sPwd;
			sUser = ''; sPwd = '';
			
			if (xmlHttpReq.responseXML.xml != '')
			{
			
				//Volcar los valores obtenidos en los campos del formulario			
				if (NavegadorIE())
				{
					var sUser = xmlHttpReq.responseXML.selectSingleNode("//user").text
					document.getElementById("WUSCODUSU").value = sUser
					var sPwd = xmlHttpReq.responseXML.selectSingleNode("//pwd").text
					document.getElementById("WUSPINUSU").value = sPwd
				}
				else
				{
					var sUser = xmlHttpReq.responseXML.documentElement.getElementsByTagName("user")[0].textContent
					document.getElementById("WUSCODUSU").value = sUser
					var sPwd = xmlHttpReq.responseXML.documentElement.getElementsByTagName("pwd")[0].textContent
					document.getElementById("WUSPINUSU").value = sPwd				
				}
			}
			if ((sUser!="") && (sPwd!=""))
			{
				//Login automático
				if (document.getElementById("btnAceptar") != null)
				{
					//Si hemos pulsado el botón de desconectar, no haremos el login automático
					if (window.location.search.indexOf("salir=1")<0)
					{
						if( document.createEvent )
						{
							var evObj = document.createEvent('MouseEvents') ;
							evObj.initMouseEvent("click", true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
							document.getElementById("btnAceptar").dispatchEvent(evObj);
						}
						else if( document.createEventObject )
							document.getElementById("btnAceptar").fireEvent('onclick');
					}
				}
			}

		}	
	}
}



// Borra todos los campos no ocutos de un formulario y que no estan en modo solo lectura
function BorrarCamposTramiteAdministracion(oForm){

	var aTipos = new Array ("input","textarea","select");
	var intALength = aTipos.length;
	
		for(var x=0;x<intALength;x++)
		{
			var cItems = oForm.getElementsByTagName(aTipos[x]);
			var intCItemsLength = cItems.length;			
			for(var i=0;i<intCItemsLength;i++)
			{
				if(!cItems.item(i).id == "" && cItems.item(i).type != "hidden" && !cItems.item(i).readOnly && cItems.item(i).type != "submit"){
					EstablecerValorCampo(window.document,cItems.item(i).id,'','=');		
					if(document.getElementById(cItems.item(i).id).selectedIndex)
						document.getElementById(cItems.item(i).id).selectedIndex= "-1";
					if(document.getElementById(cItems.item(i).id + "_parent"))
						tinyMCE.activeEditor.setContent("");
				}
			}
		}	
}