//////////////////////////////////////////////////////////////////////////////////////////
// GESTIÓN DE LA AYUDA
//////////////////////////////////////////////////////////////////////////////////////////
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 = "";
	}
	/*
	if (NavegadorIE())
	{
   oEvent.cancelBubble = true;
	  oEvent.returnValue = false;
	}
	else
	{
		oEvent.stopPropagation();
		oEvent.preventDefault();
	}
	*/
}

//////////////////////////////////////////////////////////////////////////////////////////
// VALIDACIONES DE LOS CAMPOS DE EDICIÓN
//////////////////////////////////////////////////////////////////////////////////////////
function quina_lletra (Dni){
	var lletra=new Array("T","R","W","A","G","M","Y","F","P","D","X","B","N","J","Z","S","Q","V","H","L","C","K","E");
	if (isNaN(Dni)) return false;
                else  return (lletra[Dni%23]); 
}

function CalculaNIF(nif) {
	var dni;
	var lletra;
	var lletra_correcta;
	nif=nif.toUpperCase( );
	if (isNaN(nif)) {
		if ((nif.length>2)&&(nif.length<10)) {	
			dni=nif.substring(0,nif.length-1); 
			lletra=nif.substring(nif.length-1,nif.length);
			if (isNaN(dni)) {
				alert ("El NIF no tiene un formato correcto: '99999999Q'. Si se escribe solo el DNI se calculará automáticament el NIF.");
			} else {	
				lletra_correcta=quina_lletra(dni);
				if (lletra_correcta==false){
					alert ("El NIF no tiene un formato correcto: ( 99999999Q ). Si se escribe solo el DNI se calculará automáticament el NIF.");
				}
				if (lletra!=lletra_correcta) {
					alert ("Se corregirá la letra del NIF. Le corresponde la ".concat(lletra_correcta)) ;
					return dni.concat(lletra_correcta);
				}
			}
		}
        } else  {
        		if(nif.length<10){
        			//return nif.concat(quina_lletra(nif)); 
        			return quina_lletra(nif);
        		}
        }
	return "";
}

function validaDecimal(decimal){	
	
	if(decimal.indexOf(',')>=0) return false;
	separador=decimal.indexOf('.');
	
	if (separador<1) {partEntera=decimal;partDecimal=0;
	}else{
		partEntera=decimal.substring(0,separador);
		partDecimal=decimal.substring(separador+1);
	}
	
	if (!(validaNumero(partDecimal)) || (partDecimal.length>2) ) return false;
	if (!(validaNumero(partEntera)) || (partEntera.length>3) ) return false;
	return true;
}
function validaNumero(num){
	
	for(i=0;i<num.length;i++){
		if (num.charAt(i)<'0' || num.charAt(i)>'9')return false;
	}
	return true;
}

function validaLetras(num){
	
	for(i=0;i<num.length;i++){
		if (num.charAt(i)<'a' || num.charAt(i)>'Z')return false;
	}
	return true;
}

function CampoObligatorio(valor){
//  if (valor.length>0){
//  } else{
//  	alert (strInformarCampo);
//  }
}

function ValidarDatos(){
	var coll = document.all;
	if (coll!=null) {
	    for (i=0; i<coll.length; i++) 
	        alert(coll.item(i).tagName);
	}
}

function showElements(oEvent,theForm) {   
  var oCampo,value,name,sDescripcion,sTipoCampo,lLongitud,j,bError,sMensajeError,oBtnAceptar,oBtnAtras;

	oBtnAceptar=document.getElementById('btnAceptar');
	oBtnAtras=document.getElementById('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)
		{
      oCampo=theForm.elements[i];
			name=theForm.elements[i].name;
			value=theForm.elements[i].value;
			j=0;
		}
		else
		{
			if (j==1) 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) 
						{
							bError=false;
							if ((theForm.elements[i].value=="not null") && (value.length==0))
							{
								// Campo obligatorio no informado
								bError=true;
								sMensajeError=strCampoObligatorio;
							}
							else
							{
								if ((sTipoCampo=='date') && (!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)
							{
								oCampo.focus();
								alert(sMensajeError);
								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++;	
	}
	if (!bError)
	{
		if (winAttachEDF)
		{
			if (!winAttachEDF.closed) winAttachEDF.close();
		}
		
		if (hayElementoFirma(theForm))
		{
			if (firmar(theForm,theForm.FIRMA_SOLICITUD,oEvent))
			{
				theForm.submit();
			}						
		}
		else
		{
			theForm.submit();
		}		
	}
}
//---------------------------------------------
// Firma del formulario
//----------------------------------------------

function insertarObjetoFirma()
{
	if (NavegadorIE())
	{
		document.write( "<object codebase=\"http://www.catcert.net/web/cas/descarrega/FormSign.ocx\" classid=\"clsid:AC2CD8BB-8E60-45B4-B415-1EB1C04E7753\" id=crypto></object>" );
	}
}

function hayElementoFirma(theForm)
{
	return 	(theForm.elements.namedItem('FIRMA_SOLICITUD')!=null);
}

function firmar(theForm, signature,oEvent) {
	
	var name,value;
	var sXmlDoc,sXmlCampo,sTextoAFirmar,sFirma;
	var bTipoLista,bTipoSubLista
	var numElems,z;
	var aCod;
	var oBtnAceptar,oBtnAtras;
	var sIdEntidad,sIdioma;
	var bOk;

  bOk=true;
  sTextoAFirmar="";
  sXmlDoc="<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;		
	
	for (i = 0; i < theForm.length; i++) 
	{		
		bTipoLista=false;
		bTipoSubLista=false;
    oCampo=theForm.elements[i];
      
		name=theForm.elements[i].name;
		value=theForm.elements[i].value;
						
	  if (name)
	  {
			numElems=document.getElementsByName(name).length;
			if (!numElems) numElems=1;
			
			z=-1;
			sXmlCampo="<campo>" + name + "</campo>"			
			
			if (numElems==3)
			{
				//Es un fichero adjunto, obtenemos su contenido
				name=theForm.elements[i+2].value;				
				value=ObtenerContenidoFichero(sIdEntidad,sIdioma,theForm.elements[i+2].value);
				sXmlCampo="<fichero>" + name + "</fichero>"			
			}			
		
			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;	
			}
			
			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)
			{
				sTextoAFirmar=sTextoAFirmar + value;
				sXmlDoc	=sXmlDoc + sXmlCampo;
			}
		}
					
	}

  //FIRMA DE LA SOLICITUD
	try
	{
		if (NavegadorIE())
		{
			sFirma=crypto.signText(sTextoAFirmar);
		}
		else
		{
			sFirma=crypto.signText(sTextoAFirmar,"ask");
		}
	}
	catch(e)
	{
		alert('Error al firmar');
		bOk=false;
	}
	
	if (bOk)
	{
		if (!sFirma.length) 
		{
			bOk=false;
			alert('Error al firmar');
		}
		if(sFirma.substr(0,5)=="error")
		{
			bOk=false;
			
			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;
		
		if (NavegadorIE())
		{
	    oEvent.cancelBubble = true;
		  oEvent.returnValue = false;
		}
		else
		{
			oEvent.stopPropagation();
			oEvent.preventDefault();
		}
	}
	else
	{
			sXmlDoc= sXmlDoc + "</campos><firma>" + sFirma + "</firma>" + "</datosFirma>"
			signature.value = sXmlDoc;		
	}	
	return (bOk);
}

//--------------------------------------------------
//	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;

	sData = oText.value.split("/"); //0:Dia  1:Mes  2:Any					

	 //Tractament de la longitud
	//Caràcters no permesos
	if((iKeyCode<47)||(iKeyCode>57))
  {
		if (!TeclaFuncional(iKeyCode)) 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 (NavegadorIE()) oEvent.keyCode=0;
    else oEvent.preventDefault();
  }
  
}

function TeclaFuncional(iKeyCode)
{
	if ((iKeyCode==8) || (iKeyCode==9) || (iKeyCode==46) || (iKeyCode==37) || (iKeyCode==39) || (iKeyCode==36) || (iKeyCode==35))
		return true;
  else return false;
}


//--------------------------------------------------
//	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){

	if ((oText.value.length==0) || (Validar_Data(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;

  //Si és buit o null retornem true
  if(sData)
  {
    if(sData.length!=0)
    {
    	sData = sData.split("/"); //0:Dia  1:Mes  2:Any
    	//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{ 
    			//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);
}


//--------------------------------------------------
//	Funció que donada una data en format incorrecte
//	la transforma correctament.
//--------------------------------------------------
function Transformar_Data(sData){
var iDia;
var iMes;
var iAny;
	
	sData = sData.split("/"); //0:Dia  1:Mes  2:Any
	//Comprovació del nombre de camps
	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];
	}
	return(iDia + "/" + iMes + "/" + iAny);
}


//--------------------------------------------------
//	Mascara per saber si un any és de traspàs.
//	Només permet un enter de fins a 4 dígits.
//--------------------------------------------------
function Traspas(iAny){
	if((iAny % 4)==0){
			if((iAny % 100)==0){
					if((iAny % 400)==0) return(true);
					else return(false);
			}
			else return(true);
    }
	else return(false);
}


//--------------------------------------------------
//  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);
  }
}


//--------------------------------------------------
//	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;

	//Caràcters no permesos
  bCancel=false;
	if((intNumero<44)||(intNumero>57))
	{
		if (!TeclaFuncional(intNumero)) bCancel=true;
	}
	else{
		//Comprovem on està el separador decimal
		intPosicioDecimal=strNumero.search(/[,]|[.]/);		
		//Signe menys (-)
		if(intNumero==45){ 
				if((!(blnNegatiu))||(strNumero.search(/-/)>=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 LlenarListasIE(oSelect,oElemXML,sLista,sCodElem,bSoloListasPagina)
{
  var oListas,oElemento,oListaElementos,oOption,sXPath,oLista,xmlHttpReq,bListaCargada;

	bListaCargada=false;
  oListas=oElemXML.XMLDocument;
  if (oListas!=null)
  {
	  sXPath="listas/f[@i='" + sLista + "']/e[@i='" + sCodElem + "']";
	  oElemento=oListas.selectSingleNode(sXPath);
    if (oElemento!=null)
    {
			if (oElemento.getAttribute("s")!=null)
      {
				//Comprobamos si existe la lista o hay que pedirla al servidor
				sXPath="listas/f[@i='" + oElemento.getAttribute("s") + "']";
				if (oListas.selectSingleNode(sXPath)==null)
				{
					//Hay que pedir la lista al servidor
					if (!bSoloListasPagina)
					{
					  xmlHttpReq = new ActiveXObject("MSXML2.XMLHTTP");
					  xmlHttpReq.open("GET", "../Comun/Listas.asp?id=" + oElemento.getAttribute("s"), false);
					  xmlHttpReq.send("");
						if (xmlHttpReq.responseXML!=null)
						{
							oLista=xmlHttpReq.responseXML.documentElement;
							oListaElementos=oLista.selectNodes("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");
						oOption.text=oElemento.nodeTypedValue;
					  oOption.value=oElemento.getAttribute("i") + "-" + oElemento.nodeTypedValue;
					  oSelect.add(oOption);
				  }
				}
      }
    }
  }
	return(bListaCargada);
}

function LlenarListasNoIE(oSelect,oElemXML,sLista,sCodElem,bSoloListasPagina)
{
  var i,j,sSubLista,oListas,oLista,oElemento,oListaElementos,oOption,sXPath,bEncontrada,bListaCargada;

	bListaCargada=false;
  oListas=oElemXML.childNodes[1];
  if (oListas!=null)
  {
    //Primero buscamos la lista
		sSubLista='';
		for (i=0;i<oListas.childNodes.length;i++)
		{
			oLista=oListas.childNodes[i];
			if(oLista.nodeType != 3)
			{ 
				if (oLista.getAttribute('i')==sLista)
				{
					//Lista encontrada, buscamos el elemento
					for (j=0;j<oLista.childNodes.length;j++)
					{
						oElemento=oLista.childNodes[j];
						if (oElemento.nodeType !=3 )
						{
							if (oElemento.getAttribute('i')==sCodElem)
							{
								//Hemos encontrado la sublista que hay que cargar
								sSubLista=oElemento.getAttribute('s');
							break;
							}
						}
					}
					break;	
				}
			}
		}

		// Buscamos la sublista y cargamos todos sus elementos
		if (sSubLista.length>0)
		{
			bEncontrada=false;
			for (i=0;i<oListas.childNodes.length;i++)
			{
				oLista=oListas.childNodes[i];
				if(oLista.nodeType != 3)
				{ 
					if (oLista.getAttribute('i')==sSubLista)
					{
						//Lista encontrada, cargamos todos sus elementos
						bEncontrada=true;
						bListaCargada=true;
						EliminarElementosSubLista(oSelect);
						for (j=0;j<oLista.childNodes.length;j++)
						{
							oElemento=oLista.childNodes[j];
							oOption = document.createElement("OPTION");
							oOption.text=oElemento.firstChild.nodeValue;
						  oOption.value=oElemento.getAttribute("i") + "-" + oElemento.firstChild.nodeValue;
						  oSelect.appendChild(oOption);
						}
						break;
					}
				}
			}

			// Si no la hemos encontrado, la buscamos en el servidor
			if ((!bEncontrada) && (!bSoloListasPagina))
			{
				xmlHttpReq=new XMLHttpRequest();
			  xmlHttpReq.open("GET", "../Comun/Listas.asp?id=" + sSubLista, false);
			  xmlHttpReq.send("");
				if (xmlHttpReq.responseXML!=null)
				{
					bListaCargada=true;
					EliminarElementosSubLista(oSelect);
					oLista=xmlHttpReq.responseXML.documentElement;
					for (j=0;j<oLista.childNodes.length;j++)
					{
						oElemento=oLista.childNodes[j];
						if (oElemento.nodeType!=3)
						{
							oOption = document.createElement("OPTION");
							oOption.text=oElemento.textContent;
						  oOption.value=oElemento.getAttribute("i") + "-" + oElemento.textContent;
						  oSelect.appendChild(oOption);
						}
					}
				}
			}
		}
  }
	return(bListaCargada);
}

function EliminarElementosSubLista(oSelect)
{
	//Eliminamos todos los elementos menos el primero que es un elemento en blanco
 	while (oSelect.options.length>1) oSelect.removeChild(oSelect.options[1]);
}

function LlenarListaAsociada(oSelect,sLista,sElemento,bSoloListasPagina,bOrigenListaAsociada)
{
  var i,oElemXML,bCargar,bListaCargada,sValor;

	//Si el origen es la lista asociada, comprobamos que sea la primera vez
	if (bOrigenListaAsociada) bCargar=(oSelect.getAttribute("bPrimeraVez")!="N");
	else bCargar=true;

	if (bCargar)
	{
	  //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=document.getElementById("oListasXml");
	  if (oElemXML!=null)
	  {
	    if (NavegadorIE())
	    {
	      bListaCargada=LlenarListasIE(oSelect,oElemXML,sLista,sCodElem,bSoloListasPagina);
	    }
	    else
			{
	      bListaCargada=LlenarListasNoIE(oSelect,oElemXML,sLista,sCodElem,bSoloListasPagina);
	    }
	  }
		if (bListaCargada)
		{ 
			oSelect.setAttribute("bPrimeraVez","N");
			//Al cargar la pagina mantenemos el valor que tuviera la lista
			if (bSoloListasPagina) oSelect.value=sValor;
		}
	}
}

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)
		{
			aListas=document.getElementsByName(sName);
			if (aListas.length>=11)
			{
				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>=11)
					{
						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()
{
	var i,aElementos,aElemAux,aListas,sName;

  //Ponemos valores en los campos fijos del formulario
 /* if (sNumDoc.length>0)
  {
    aElementos=document.getElementsByName("WTGNUMDOC");
    if (aElementos.length>0) aElementos.item(0).value=sNumDoc;
  }
  if (sCarCon.length>0)
  {
	  aElementos=document.getElementsByName("WTGCARCON");
	  if (aElementos.length>0) aElementos.item(0).value=sCarCon;
  }
  if (sNombre.length>0)
  {
	  aElementos=document.getElementsByName("WTGNOMBRE");
	  if (aElementos.length>0) aElementos.item(0).value=sNombre;
  }
  if (sApell1.length>0)
  {
	  aElementos=document.getElementsByName("WTGAPELL1");
	  if (aElementos.length>0) aElementos.item(0).value=sApell1;
  }
  if (sApell2.length>0)
  {
	  aElementos=document.getElementsByName("WTGAPELL2");
	  if (aElementos.length>0) aElementos.item(0).value=sApell2;
  }
  if (sDirMai.length>0)
  {
	  aElementos=document.getElementsByName("WTGDIRMAI");
	  if (aElementos.length>0) aElementos.item(0).value=sDirMai;
  }

  if (sTelef1.length>0)
  {
	  aElementos=document.getElementsByName("WTGTELEF1");
	  if (aElementos.length>0) aElementos.item(0).value=sTelef1;
  }
  
  if (sTelMov.length>0)
  {
	  aElementos=document.getElementsByName("WTGTELMOV");
	  if (aElementos.length>0) aElementos.item(0).value=sTelMov;
  }
  if (sMailNot.length>0)
  {
	  aElementos=document.getElementsByName("WTGMAINOT");
	  if (aElementos.length>0) aElementos.item(0).value=sMailNot;
  }
  
  aElementos=document.getElementsByName("WTGENVMAI");
   if (aElementos.length>0 ) 
   {
   		if (aElementos.item(0).type=='checkbox')
		{
			if (sEnvMailNot=='S')
				aElementos.item(0).checked=true;
			else
				aElementos.item(0).checked=false;
		}
		else{
			if (sEnvMailNot=='S')
				aElementos.item(0).value='S';
			else
				aElementos.item(0).value='N';
		}
	}
   
   
   aElementos=document.getElementsByName("WTGENVSMS");
   if (aElementos.length>0)
   {	
   
   		if (aElementos.item(0).type=='checkbox')
		{
   			if (sEnvSMSNot=='S')
   				aElementos.item(0).checked=true;
			else
				aElementos.item(0).checked=false;
		}
		else{
			if (sEnvSMSNot=='S')
				aElementos.item(0).value='S';
			else
				aElementos.item(0).value='N';
		}
   } 
   */
   
   try
   {
      InicializarCampos(); 
   }
   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;

  if (oEvent.keyCode) iKeyCode=oEvent.keyCode;
  else iKeyCode=oEvent.which;

  if ((oTexto.value.length >= lMaximo) && (!TeclaFuncional(iKeyCode)))
  {
	  if (NavegadorIE())
	  {
      oEvent.cancelBubble=true;
	    oEvent.returnValue=false;
	  }
	  else
	  {
		  oEvent.stopPropagation();
		  oEvent.preventDefault();
	  }
  }
}


//----------------------------------------------------------
//	Funciones para la gestión del botón de modificar
//  datos que tiene el paso de confirmación de un formulario
//----------------------------------------------------------
function ModificarDatos(oFormulario)
{
	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();
}

function EstablecerValorCampo(theForm,nombreCampo,valorCampo) 
{     	
  var aCampos,oCampo;
  var sName,aElemAux,aListas,i;
  var bValorCompuesto;

  try
  {
  	aCampos=theForm.getElementsByName(nombreCampo);
  	if (aCampos.length>0) oCampo=aCampos[0];
  	
  	if (oCampo!=null) 
  	{
  		if (oCampo.type=='checkbox')
  		{
  			if (valorCampo=='S')
  				oCampo.checked=true;
  			else
  				oCampo.checked=false;
  		}
  		else
  		{
  	
  		  
  			if ((oCampo.type=='select-one') || (oCampo.type=='radio'))
  			{
  				bValorCompuesto=(valorCampo.indexOf('-')>0);
  			  if (oCampo.type=='select-one') 
  				{
  				    if (bValorCompuesto)
  				    {
  				      oCampo.value=valorCampo;
  				    }
  				    else
  				    {
  				      for (i=0;i<oCampo.options.length;i++)
  					    {
      						var aPartes=oCampo.options[i].value.split('-');    						
      						if (aPartes[0]==valorCampo)
      						{
      						 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;
  				sName=sName.substr(0,sName.length-1) + '1';
  				if (sName!=nombreCampo)
  				{
  					aListas=document.getElementsByName(sName);
  					if (aListas.length>=10)
  					{
  						aElemAux=document.getElementsByName(nombreCampo);
  						LlenarListaAsociada(aListas.item(0),aElemAux.item(aElemAux.length-1).value,valorCampo,false,false);
  					}
  				}
  			}
  			else
  			{
  				oCampo.value=valorCampo;
  			}
  		}
  		//Si el campo no es editable y es de tipo lista,radio o checkbo, entonces establecemos su valor en el hidden
  		if (oCampo.isDisabled && ((oCampo.type=='select-one') || ((oCampo.type=='radio') || (oCampo.type=='checkbox'))))
  		{
  		  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
  		  {
  		    aCampos[1].value=oCampo.value;
  		  }
  		}
  	}	
  }
  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;
			}
		}
  }
}

//----------------------------------------------------------
//	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;
	  }
	}
	document.FormLoginCertificatDigital.submit();
}



//----------------------------------------------------------
//	Funciones para la gestion de los ficheros adjuntos
//----------------------------------------------------------
var winAttachEDF;

function SeleccionarFicheros()
{
	var oFormLink,oAttachments,i,oCampoOri,oCampoDes,iLeft,iTop,iWidth,iHeight,sFeatures,sEnlace,sEstilo,iIni,iFin;
	
	//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.getElementById('spanAttachFiles');
	if (oAttachments)
	{
		for(i=0;i<oAttachments.childNodes.length;i++)
		{
			//Creamos un campo oculto y lo anadimos al formulario
			oCampoOri=oAttachments.childNodes.item(i);
			oCampoDes=document.createElement('INPUT');
			oCampoDes.type='hidden';
			oCampoDes.name=oCampoOri.name;
			oCampoDes.value=oCampoOri.value;
			oFormLink.appendChild(oCampoDes);
		}

		//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"
		winAttachEDF=window.open('about:blank','winAttachFiles',sFeatures);
		sEnlace='../src/asp/selecFicheros/SelecFicheros.asp';
	 	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);
			}
		}
		oFormLink.action=sEnlace;
		oFormLink.target='winAttachFiles';
		oFormLink.submit();
		if (winAttachEDF) winAttachEDF.focus();
	}

}

function AnadirFicheroAdjuntoFormulario(sKey,sNombre,sTamano,sId)
{
	var oSpanCampos,oSpanTexto,oCampo,sTexto;

	//Buscamos donde hay que anadir los campos
	oSpanCampos=document.getElementById('spanAttachFiles');

	if (oSpanCampos)
	{
		//Anadimos los campos
		oCampo=document.createElement('INPUT');
		oCampo.type='hidden';
		oCampo.name=sKey;
		oCampo.value=sNombre;
		oSpanCampos.appendChild(oCampo);
		oCampo=document.createElement('INPUT');
		oCampo.type='hidden';
		oCampo.name=sKey;
		oCampo.value=sTamano;
		oSpanCampos.appendChild(oCampo);
		oCampo=document.createElement('INPUT');
		oCampo.type='hidden';
		oCampo.name=sKey;
		oCampo.value=sId;
		oSpanCampos.appendChild(oCampo);

		//Actualizamos la descripcion
		oSpanTexto=document.getElementById('spanAttachText');
		if (oSpanTexto)
		{
			sTexto='<b>' + sNombre + '</b>' + ' (' + sTamano + ' Mb); ';
			oSpanTexto.innerHTML=oSpanTexto.innerHTML + sTexto;
		}
	}
}

function ObtenerContenidoFichero(sIdEntidad, sIdioma, sIdFichero)
{
	var sURL;
	
	sURL="../Comun/Ficheros.asp?id=" + sIdEntidad + "&idioma=" + sIdioma  + "&fichero=" + sIdFichero

	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;
}

