// JavaScript Document
/**********************************************
Esta varible indica el punto y se usa en la función
onlyDigits
*/
var IS_PERIOD = 46;

/**********************************************
Esta funcion hace un submit de un formulario 
asociando una accion a realizar sobre él
  pObjForm, formulario a entregar
  accion, accion solicitada
FGI
***********************************************/
function EnviarFormulario(pObjForm, accion) {  
   	// Construir el nuevo string
  	ac = new String("action=").concat(accion);
  	// Comprobar que no exista ya un parámetro acción
  	indice = pObjForm.action.indexOf(ac);
  	if (indice == -1) {	// NO Existe
  		// añadir la accion a la property "action"
  		if (pObjForm.action.indexOf("?") == -1)
  			pObjForm.action = pObjForm.action.concat("?" + ac);
  		else 
  			pObjForm.action = pObjForm.action.concat("&" + ac);
  	}
  	else {							// Existe
  		// Sustituir la accion en la property "action"
  		pObjForm.action = new String(pObjForm.action).replaceFirst("action=[a-zA-Z]+", ac);
  	}
  		
  	// Enviar el formulario
  	pObjForm.submit(); 
}

/**********************************************
Esta funcion hace un submit de un formulario 
asociando una accion a realizar sobre él
únicamente si la tecla pulsada es ENTER
  pObjForm, formulario a entregar
  accion, accion solicitada
FGI
***********************************************/
function EnviarFormularioEnter(pObjForm, accion) {
 var keycode;
 		// Recuperar la tecla pulsada
    if (window.event) 
      keycode = window.event.keyCode;
    else 
    	return true;

		// Si la tecla es ENTER enviar formulario
    if (keycode == 13)
      EnviarFormulario(pObjForm, accion);
   	else
   		return true;
}


/****************************************
Adjunta applet para verificar la version del mvj
SLA
*****************************************/
function applet_sumar()
{ 
	if (is_ie)
        document.write('<OBJECT classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"'+
        'width="1" height="1"  name="sumar" id="sumar">'+
        '<PARAM NAME="code" VALUE="Sumar.class">'+
        '<PARAM NAME="archive" VALUE="Sumar.jar">'+
        '<PARAM NAME="codebase" VALUE="recursos/">'+
        '<PARAM NAME="type" VALUE="application/x-java-applet;version=1.3">'+
        ' <PARAM NAME="scriptable" VALUE="true">'+
        '<PARAM NAME="mayscript" VALUE="true">'+
				'<'+'/OBJECT>');
	else
        document.write('<embed name = "sumar" id="sumar" archive = "Sumar.jar" src="Sumar.class" width="1" height="1" code="Sumar.class" codebase="recursos/" type="application/x-java-applet;version=1.3" scriptable="true" mayscript="true"><'+'/embed>');
			
}

/****************************************
Adjunta applet para verificar la version del mvj
SLA
*****************************************/
function applet_verifica()
{ 
	if (is_ie)
        document.write('<OBJECT classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"'+
        'width="1" height="1"  name="verifica" id="verifica">'+
        '<PARAM NAME="code" VALUE="Verifica.class">'+
        '<PARAM NAME="archive" VALUE="Verifica.jar">'+
        '<PARAM NAME="codebase" VALUE="recursos/">'+
        '<PARAM NAME="type" VALUE="application/x-java-applet;version=1.3">'+
        ' <PARAM NAME="scriptable" VALUE="true">'+
        '<PARAM NAME="mayscript" VALUE="true">'+
				'<'+'/OBJECT>');
	else
        document.write('<embed name = "verifica" id="verifica" archive = "Verifica.jar" src="Verifica.class" width="1" height="1" code="Verifica.class" codebase="recursos/" type="application/x-java-applet;version=1.3" scriptable="true" mayscript="true"><'+'/embed>');
			
}

/****************************************
Adjunta applet para verificar la version del mvj
SLA
*****************************************/
function applet_firma()
{
	applet_verifica();	

	var VersionJVM = '';
	var archivosV4 = 'Firma_ideas.jar,activation.jar,bcmail-jdk14-135.jar,bcprov-jdk14-135.jar,Ideas383_Java14.jar,mail.jar';

	var archivosVX = '';
	var version = '1.0.0.0, 1.0.0.0, 1.0.0.0,1.0.0.0, 1.0.0.0, 1.0.0.0';
 

  var tipo = typeof(document.verifica);
//alert(tipo);
	if (tipo == 'object' || tipo == 'function')
		try{
			VersionJVM = document.verifica.VMVersion();
			VersionJVM = new String(testVM(document.verifica));
		} catch (e) {VersionJVM = '4';}

	if (VersionJVM.trim() == ''.trim() ||VersionJVM == '0')
		return 0;
	else if (VersionJVM == '4' || VersionJVM == '5' || VersionJVM == '6')


		archivosVX = archivosV4;
		
	var applet_ie = '<OBJECT classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"'+
									'width="0" height="0"  name="Obtenerfirma">'+
									'<PARAM NAME="code" VALUE="Firma_ideas.class">'+
									'<PARAM NAME="codebase" VALUE="recursos/">'+
									'<PARAM NAME="type" VALUE="application/x-java-applet;version=1.'+VersionJVM+'">'+
									'<PARAM NAME="scriptable" VALUE="true">'+
									'<PARAM NAME="mayscript" VALUE="true">'+
									'<PARAM NAME="cache_archive" VALUE="'+archivosVX+'">'+
									'<PARAM NAME="cache_version" VALUE="'+version+'">'+
									'<'+'/OBJECT>';
																											
	var applet_nn = '<embed name="Obtenerfirma" archive="Firma_ideas_Firmado.jar"'+
									'width="0" height="0" code="Firma_ideas.class" codebase="recursos/"'+
									'type="application/x-java-applet;version=1.'+VersionJVM+'" scriptable="true" mayscript="true"'+
									'cache_archive="'+archivosVX+'"'+
									'cache_version="'+version+'"><'+'/embed>';


	if (is_ie)
		document.write(applet_ie);
	else
		document.write(applet_nn);
}
/****************************************
Obliga a introducir solo numeros en un input
SLA
*****************************************/
function onlyNumbers(e,id) {

  var _ret = true;
  if (id==null)
    {
      alert('El id no puede ser nulo');
      return _ret;
    }
  if (e==null)
    {
      alert('El evento de teclado no puede ser nulo');
      return _ret;
    }
  if (is_ie) 
    {
      if (window.event.keyCode < 48 || window.event.keyCode > 57) 
        {
          window.event.keyCode = 0;
          _ret = false;
        }
    }
  if (is_nav) 
    {
      if ((e.which < 48 || e.which > 57) && (e.which != 8 ) && (e.which != 0 ))
        {
          e.preventDefault();
          _ret = false;
        }
    }
  return (_ret); 
}

/****************************************
Funcion que solo permite la introduccion
de numeros decimales siendo el separador
el "." 
Función auxiliar a onlyDigits, hace lo mismo
*****************************************/
function onlyDigits2(e) {
  if (navigator.appName == "Netscape") tecla = e.which;
  if (navigator.appName == "Microsoft Internet Explorer") tecla = e.keyCode;
  if(tecla==46) return true;
  if ((tecla < 48 || tecla > 57 ) && (tecla != 8 ) && (tecla != 0 ) ) return true;
  return false;
}

/****************************************
Funcion que solo permite la introduccion
de numeros decimales siendo el separador
el "."
*****************************************/

function onlyDigits(e,id) {

  var _ret = true;
  if (id==null)
    {
      alert('El id no puede ser nulo');
      return _ret;
    }
  if (e==null)
    {
      alert('El evento de teclado no puede ser nulo');
      return _ret;
    }
    
  var tecla;
  
  if (isIE())
    	{tecla = e.keyCode;}
  else
   	{tecla = e.which;}    
   	
  if (tecla == 46) 
        {
          var completo = document.getElementById(id).value;
          if (completo.indexOf('.')!=-1)
            {
              anular_tecla(e)
              _ret = false;
            }
           else
             return true;
        }
        
      if ((tecla < 48 || tecla > 57 ) && (tecla != 8 ) && (tecla != 0 ) ) 
        {
         anular_tecla(e)
          _ret = false;
        }
   	
  return (_ret);    	
    
}

/****************************************
Funcion que evalua si el campo pasado como
parametro "id" cumple con las restricciones
impuestas, es decir la parte entera no supera
el max_length_entero y la parte decimal no
supera el max_length_fraccion, el separador
entre enteros y decimales es el ".", cuando
no es asi, lanza un alert con el mensaje de 
error
*****************************************/

function anular_tecla(e)
{
    if (isIE())
     e.keyCode = 0; 
    else
      e.preventDefault(); 
}

function max_lengthDigits(max_length_entero,max_length_fraccion,id,mensaje_error,mensaje_error_entero,mensaje_error_decimal,e)
{

  if (id==null)
    {
      alert('El id no puede ser nulo');
      return true;
    }
    
  var vector_numero = new Array();    
  
  var tecla;
  
  if (isIE())
    	{tecla = e.keyCode;}
  else
   	{tecla = e.which;}

  var numero = document.getElementById(id).value;
  
  if (tecla > 47 && tecla < 59  && (tecla != 8 ) && (tecla != 0 ) ) 
  {numero += '1';}
  
  numero = numero.replace(/[.]/,'');
  vector_numero = numero.split('.');
  
  // no mas de 1 coma
  if (vector_numero.length > 2)
  {
	error_Campo(id,mensaje_error);
     	anular_tecla(e);
	return false;
  } 

  if (max_length(max_length_entero,vector_numero[0]))
        {
          if (mensaje_error_entero!=null)
          {
              error_Campo(id,mensaje_error_entero);
          }
          anular_tecla(e);
          return false;
        } 
        
 if (vector_numero.length > 1)
 {
   if (tecla == 44 || tecla == 46)
   { 
     anular_tecla(e);
   }
   
  if (max_length(max_length_fraccion,vector_numero[1]))
        {
          if (mensaje_error_entero!=null)
          {
              error_Campo(id,mensaje_error_decimal);
          }
          anular_tecla(e);
          return false;
        } 
 }

return true;
}


/****************************************
Ajusta dimensiones tabla para el scrollbar
SLA
*****************************************/
function ListCalcSize(eHead, eCont, eBody) {
		// alert('anchos: ' + eCont.clientWidth + ', ' +  eCont.offsetWidth);    
    // Si el contenido es más alto que el contenedor...
    if (eCont.clientHeight < eBody.clientHeight) {
      //anchobarra = eCont.offsetWidth - eCont.clientWidth;
      anchobarra = 0;
      ancho = eCont.clientWidth - anchobarra;
      eHead.style.width = ancho + 'px';
      eBody.style.width = ancho + 'px';
    }
}
function ListCalcSizeLista(eCont, eBody) 
{
    // Si el contenido es más alto que el contenedor...
    if (eCont.clientHeight < eBody.clientHeight) {
      //anchobarra = eCont.offsetWidth - eCont.clientWidth;
      anchobarra = 16;
      ancho = eCont.clientWidth - anchobarra;
      eBody.style.width = ancho + 'px';
    }
}

function ListCalcSizeWithFoot(eHead, eCont, eBody, eFoot) {
		 //alert('anchos: ' + eFoot.clientWidth);
    
    // Si el contenido es más alto que el contenedor...
    if (eCont.clientHeight < eBody.clientHeight) {
      //anchobarra = eCont.offsetWidth - eCont.clientWidth;
      anchobarra = 16;
      ancho = eCont.clientWidth - anchobarra;
      eHead.style.width = ancho + 'px';
      eBody.style.width = ancho + 'px';
      eFoot.style.width = ancho + 'px';
    }
    //alert('anchos: ' + eFoot.clientWidth);
}


/****************************************
Cambia el puntero del raton a 'reloj'
SLA
*****************************************/
function puntero_espera()
{
		
 if (is_ie)
	{
		var aux = document.all;
		for (var i = (document.all.length-1);i >= 0; --i)		 
				 aux(i).style.cursor = 'wait';
  }
	else
	{
   	document.body.style.cursor="wait"
	}
}
/****************************************
Cambia el puntero del raton a 'normal'
SLA
*****************************************/
function puntero_normal()
{
 if (is_ie)
	{
		var aux = document.all;
		for (var i = (document.all.length-1);i >= 0; --i)		 
				 aux(i).style.cursor = '';
  }
	else
	{
   	document.body.style.cursor=""
	}
}
/****************************************
Comprueba que este instalada la maquina virtual 
que se necesita 1.3.1_x
SLA
*****************************************/
function testVM(objeto_verifica)
{
	if(typeof(objeto_verifica) == "object" || (typeof(objeto_verifica) == "function"))
	{ 
    	try {

				var Version="", Vendor="";
				var ok=true;
				var numero_version=0;
				var vector_version = new Array();
				var version1,version2,version3;
				var temp = new Array();
				
				Version= new String (objeto_verifica.VMVersion());
				Vendor= new String (objeto_verifica.VMVendor());

				//COMPARA LA VERSION DE LA Virtual Machine
				//TIENE QUE SER > 1.3.1

				//myRegExp = new RegExp(".", "gi");
			//	x=Version.match(myRegExp); 

				vector_version = Version.split(".");
			
				version1 = parseInt(vector_version[0]);
				version2 = parseInt(vector_version[1]);
				if (isNaN(vector_version[2]))
				{
					temp = vector_version[2].split("_");
					version3 = parseInt(temp[0]);
				}
				else
				{
					version3 = parseInt(vector_version[2]);
				}	

				if (version1 != 1 ) ok=false;
				
				else if (version1 == 1) //primero = 1
				{
					
					// comprobamos si 1.3.1 o 1.4.x
					if ((version2 != 4) && (version2 != 5) && (version2 != 6))
					
					{ 
						ok=false;
					}
					else 
					{
						 if (version2==4) //segundo = 4
						{
						//	if (version3<1) ok=false;
						//	else
								numero_version = 4;
						}
						else
						 if (version2==5) //segundo = 5
						{
							//if (version3<1) ok=false;
							//else
								numero_version = 5;
						}					
						else
						 if (version2==6) //segundo = 5
						{
							//if (version3<1) ok=false;
							//else
								numero_version = 6;
						}									
					}
				}
	
				//VERIFICA QUE LA Virtual Machine SEA DE Sun
				if (Vendor.indexOf("Sun")==-1) ok=false;

				return numero_version
			
    	}  catch(e)
		{ 
		return 0;
		}
	}
	else 
  { 
    alert('No se ha instalado correctamente todos los componentes requeridos.');
    return 0;
  }
}

/****************************************
Funcion que valida si esta la VM de java
SLA
*****************************************/
function validarbrowser(pFormulario,pverifica){

if(typeof(pverifica) == "object" || (typeof(pverifica) == "function"))
{
  try {
    var version = 0;

    version=testVM(pverifica);

    if ( version < 3) 
		 {
      deshabilita_botones_Form(pFormulario);
      alert('No tiene instalada la versión de java requerida (superior a 1.3.1_x)');
      return version;
		 }
      return version;
		  
  }  catch(e)
  { 
    deshabilita_botones_Form(pFormulario);          
    alert('No tiene instalada la versión de java requerida (superior a 1.3.1_x)');
    return 0;
  }
}
else 
  { 
    deshabilita_botones_Form(pFormulario);          
    alert('No se ha instalado correctamente todos los componentes requeridos.');
    return 0;
  }

}

/****************************************
Muestra u oculta la capa indicada
SLA
*****************************************/
function maneja_capas(visible,capa){
if (visible == 'S')
  document.getElementById(capa).style.visibility="visible";
else
  document.getElementById(capa).style.visibility="hidden";
}

/****************************************
Muestra u oculta un boton 
SLA
*****************************************/
function maneja_boton(habilitado,boton){

	if (habilitado == 'S')
    document.getElementById(boton).disabled = false;
  else
    document.getElementById(boton).disabled = true;
}

/****************************************
Valida el formulario buscando los campos 
que estan vacios y tenian que tener valor
SLA
*****************************************/
function validarForm(pFormulario){
  
	var lObjElemento; // elemento del formulario
	var lColElementos; // colección de elementos de formulario
	var lnombre;
	lStrResult='CORRECTO';

  if (pFormulario != null)
  {
	lColElementos=pFormulario.elements;

	for(i=0;i<lColElementos.length;i++){

		if (lStrResult!='CORRECTO') {
			break;
		}
		lObjElemento=lColElementos[i];
			if ((lObjElemento.value.trim() == ''.trim()) && (lObjElemento.type!="hidden")&& (lObjElemento.type!="button") && (!lObjElemento.disabled)){
				//si no tiene valor avisamos que todos los campos son obligatorios
                                lStrResult='Debe rellenar el campo '+lObjElemento.id+'.';
				lObjElemento.focus();
			} //del if
	} // del for
  } 
	return lStrResult;
}

/****************************************
Deshabilita botones del formulario
SLA
*****************************************/
function deshabilita_botones_Form(pFormulario){
	var lObjElemento; // elemento del formulario
	var lColElementos; // colección de elementos de formulario
	lStrResult='CORRECTO';
	lColElementos=pFormulario.elements;

	for(i=0;i<lColElementos.length;i++){

		if (lStrResult!='CORRECTO') {
			break;
		}
		lObjElemento=lColElementos[i];
              
		if ((lObjElemento.type == "button") && (lObjElemento.type!="hidden") && (!lObjElemento.disabled)){
			lObjElemento.disabled = true;	
		} //del if
                
	} // del for
	return;
}
/****************************************
Funcion que quita los espacion en blanco
SLA
*****************************************/

String.prototype.trim = function()
{
  return( this.replace(/^\s*([\s\S]*\S+)\s*$|^\s*$/,'$1') );
}

String.prototype.padLeft = function(cChar, nLength)
{
    if( this.length < nLength )
    {
        var nExtraLen = nLength - this.length;
        var cTemp = "";
				
				for (var i = (nExtraLen-1);i >= 0; --i)
            cTemp += cChar;

        cTemp += this;
    }
    return cTemp;
}

/****************************************************************
Esta función se encarga de eliminar el efecto de la tecla 
enter para evitar que se realiza una acción (no deseada) al 
pulsar intro sobre algún campo delas páginas
****************************************************************/

function sinEnter(e)
{
  if (isIE()) 
  {
    if (window.event.keyCode == 13)
    { 
      window.event.keyCode = 0;
      return false;
    }
  }
  if (isNS()) 
  {
    if (e.which == 13) 
    {
      e.which = 0;
      return false;
    }
  }
  return false;
}

function submitenterD(pObjForm,accion,e,id)
{
  var keycode;
  if (window.event) keycode = window.event.keyCode;
  else if (e) keycode = e.which;
  else return true;
  
  if (keycode == 13)
     {
      EnviarFormulario(pObjForm,accion);
      return false;
     }
  else
     return onlyDigits(e,id);
}

function submitenter(accion,e,pObjForm)
{
   var keycode;
   if (window.event) keycode = window.event.keyCode;
   else if (e) keycode = e.which;
   else return true;     
   if (keycode == 13)
   {
     EnviarFormulario(pObjForm,accion);//actualizarListados(document.getElementById('TipoSubProyectoBean'),accion);
     return false;
   }
   else return true;
}

/**para los textAreas*/
function controlLongitud(id,longitud,mensaje)
{
  var valor = document.getElementById(id).value;
  if(valor.length>longitud)
  {
    var diferencia = valor.length - longitud;
    window.alert(mensaje+": "+diferencia);
    document.getElementById(id).focus();
  }
}

/****************************************
Funcion que lanza un mensaje de error y se
situa en el campo que lo hizo aparecer
*****************************************/

function error_Campo(id,mensaje)
{
  alert(mensaje);
  document.getElementById(id).select();
  document.getElementById(id).focus();
}

/****************************************
Funcion que evalua si el dato pasado
como parametro posee mas de un punto
*****************************************/

function mas_de_un_punto(dato)
{
  var pos = dato.indexOf('.');
  if (pos!=-1)
    {
      var parte = dato.substring(0,pos);
      if (parte.indexOf('.')!=-1)
        {
          return true;
        } else
          {
            return false;
          }
    } else
      {
        return false;
      }  
}

/****************************************
Funcion que evalua si el dato pasado
como parametro posee supera el max_length
impuesto.
*****************************************/
function max_length(max_length,dato)
{
  if (dato.length>max_length)
    {
      return true;
    } else
      {
        return false;
      }
}


/****************************************
Testea si el navegador tiene activadas
y soporta las cookies
JMM 15/04/03
*****************************************/
function testCookie()
{
// cookies - 990624 - abk 
// modified - 030226 - JMM
	document.cookie = "cookies=true";
	var is_cookie = (document.cookie) ? "true" : "false";
	var cookieName = 'testCookie' + (new Date().getTime());
	document.cookie = cookieName + '=cookieValue';
	is_cookie = is_cookie && document.cookie.indexOf(cookieName) != -1;
	return is_cookie;
}

/****************************************
Testea si la cadena de texti pasada como 
argumento es un número entero 
JMM 15/04/03
*****************************************/
function isInt (a_str)
{
	str=a_str;
	//se eliminan los ceros al comienzo de la cadena
	//para convertirla
	var j=0;
	while (str.charAt(j)=="0")
	{
		j++;
	}
	str=str.substring(j,str.length);
	
	var i = parseInt (str);
	//La cadena no puede convertirse a entero
	if (isNaN (i))
		return false;
	
	//Si puede convertirse pero no es un entero
	// únicamente sino q tiene tambien letras
	if (str.length==0 && i==0) return true;
	//se convierte el nº obtenido a cadena y se compara
	//con la cadena sin ceros a la izquierda
	i = i . toString ();
	if (i != str)
	{
		return false;
	}

	return true;
}



/****************************************
Abre la url pasada como argumento 
en una nueva ventana con titulo "Nueva"

JMM 15/02/03
*****************************************/

function fOpenWebInWindow(sWeb)
{
    var h=0;
    var w=0;
    var LeftPosition = 0;
    var TopPosition = 0;
    var settings = 'menubar=1,height='+h+',width='+w+',top='+TopPosition+',left='+LeftPosition+',scrollbars='+scroll+',';
    newWindow = window.open(sWeb,"Nueva",settings);
}

/****************************************
Captura el evento del ratón
tanto en Netscape como en IE
y muestra el mensaje en rightClickMessage

JMM 16/02/03
*****************************************/

var rightClickMessage="Función desactivada";


function click(e) {
	/*if (document.all) {
		if (event.button == 2) {
			alert(rightClickMessage);
			return true;
		}
	}
	if (document.layers) {
		if (e.which == 3) {
			alert(rightClickMessage);
			return false;
		}
	}*/
        return true;
}


if (document.layers) {
document.captureEvents(Event.MOUSEDOWN);
}
document.onmousedown=click;


// JavaScript Browser Sniffer
// Eric Krok, Andy King, Michel Plungjan 010329
// see
// http://www.webreference.com/ for more information
// http://www.webreference.com/tools/browser/javascript.html this particular doc
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
//  (at your option) any later version.
//
// please send any improvements to aking@internet.com and we'll
// roll the best ones in
//
// adapted from Netscape's Ultimate client-side JavaScript client sniff.
// and andy's sniffer
// Revised May 7 99 to add is.nav5up and is.ie5up (see below). (see below).
// Revised June 11 99 to add addit props, checks
// Revised June 23 99 added screen props - gecko m6 doesn't support yet - abk
//                    converted to var is_ from is object to work everywhere
// 990624 - added cookie forms links frames checks - abk
// 001031 - ie4 mod 5.0 -> 5. (ie5.5 mididentified - abk)
//          is_ie4 mod tp work with ie6+ - abk
// 001120 - ns6 released, document.layers false, put back in
//        - is_nav6 test added - abk
// 001121 - ns6+ added, used document.getElementById, better test, dom-compl
// 010117 - actual version for ie3-5.5 by Michel Plungjan
// 010118 - actual version for ns6 by Michel Plungjan
// 010217 - netscape 6/mz 6 ie5.5 onload defer bug docs - abk
//
//
// Everything you always wanted to know about your JavaScript client
// but were afraid to ask. Creates "is_" variables indicating:
// (1) browser vendor:
//     is_nav, is_ie, is_opera
// (2) browser version number:
//     is_major (integer indicating major version number: 2, 3, 4 ...)
//     is_minor (float   indicating full  version number: 2.02, 3.01, 4.04 ...)
// (3) browser vendor AND major version number
//     is_nav2, is_nav3, is_nav4, is_nav4up, is_nav5, is_nav5up, is_ie3, is_ie4, is_ie4up
// (4) JavaScript version number:
//     is_js (float indicating full JavaScript version number: 1, 1.1, 1.2 ...)
// (5) OS platform and version:
//     is_win, is_win16, is_win32, is_win31, is_win95, is_winnt, is_win98
//     is_os2
//     is_mac, is_mac68k, is_macppc
//     is_unix
//        is_sun, is_sun4, is_sun5, is_suni86
//        is_irix, is_irix5, is_irix6
//        is_hpux, is_hpux9, is_hpux10
//        is_aix, is_aix1, is_aix2, is_aix3, is_aix4
//        is_linux, is_sco, is_unixware, is_mpras, is_reliant
//        is_dec, is_sinix, is_freebsd, is_bsd
//     is_vms
//
// See http://www.it97.de/JavaScript/JS_tutorial/bstat/navobj.html and
// http://www.it97.de/JavaScript/JS_tutorial/bstat/Browseraol.html
// for detailed lists of userAgent strings.

//
// Note: you don't want your Nav4 or IE4 code to "turn off" or
// stop working when Nav5 and IE5 (or later) are released, so
// in conditional code forks, use is_nav4up ("Nav4 or greater")
// and is_ie4up ("IE4 or greater") instead of is_nav4 or is_ie4
// to check version in code which you want to work on future
// versions.
//

    // convert all characters to lowercase to simplify testing
    var agt=navigator.userAgent.toLowerCase();
    var appVer = navigator.appVersion.toLowerCase();

    // *** BROWSER VERSION ***

    var is_minor = parseFloat(appVer);
    var is_major = parseInt(is_minor);

    // Note: On IE, start of appVersion return 3 or 4
    // which supposedly is the version of Netscape it is compatible with.
    // So we look for the real version further on in the string

    var iePos  = appVer.indexOf('msie');
    if (iePos !=-1) {
       is_minor = parseFloat(appVer.substring(iePos+5,appVer.indexOf(';',iePos)))
       is_major = parseInt(is_minor);
    }

    // Netscape6 is mozilla/5 + Netscape6/6.0!!!
    // Mozilla/5.0 (Windows; U; Win98; en-US; m18) Gecko/20001108 Netscape6/6.0
    var nav6Pos = agt.indexOf('netscape6');
    if (nav6Pos !=-1) {
       is_minor = parseFloat(agt.substring(nav6Pos+10))
       is_major = parseInt(is_minor)
    }

    var is_getElementById   = (document.getElementById) ? "true" : "false"; // 001121-abk
    var is_getElementsByTagName = (document.getElementsByTagName) ? "true" : "false"; // 001127-abk
    var is_documentElement = (document.documentElement) ? "true" : "false"; // 001121-abk

    var is_nav  = ((agt.indexOf('mozilla')!=-1) && (agt.indexOf('spoofer')==-1)
                && (agt.indexOf('compatible') == -1) && (agt.indexOf('opera')==-1)
                && (agt.indexOf('webtv')==-1));
    var is_nav2 = (is_nav && (is_major == 2));
    var is_nav3 = (is_nav && (is_major == 3));
    var is_nav4 = (is_nav && (is_major == 4));
    var is_nav4up = (is_nav && (is_major >= 4));
    var is_navonly      = (is_nav && ((agt.indexOf(";nav") != -1) ||
                          (agt.indexOf("; nav") != -1)) );

/*	var is_nav6 = (is_nav && (agt.indexOf('netscape6') != -1)); // new 001120 - abk
	var is_nav6up = (is_nav && is_getElementById);              // new 001121 - abk
*/
	var is_nav6   = (is_nav && is_major==6);    // new 010118 mhp
	var is_nav6up = (is_nav && is_minor >= 6) // new 010118 mhp

    var is_nav5   = (is_nav && is_major == 5 && !is_nav6); // checked for ns6
    var is_nav5up = (is_nav && is_minor >= 5);

    var is_ie   = (iePos!=-1);
    var is_ie3  = (is_ie && (is_major < 4));

    var is_ie4   = (is_ie && is_major == 4);
    var is_ie4up = (is_ie && is_minor >= 4);
    var is_ie5   = (is_ie && is_major == 5);
    var is_ie5up = (is_ie && is_minor >= 5);
    var is_ie6 =( (is_ie) && (parseInt(navigator.appVersion) == 4) && (navigator.userAgent.indexOf("MSIE 6") != -1) );
    var is_ie7 =( (is_ie) && (parseInt(navigator.appVersion) == 4) && (navigator.userAgent.indexOf("MSIE 7") != -1) );

// KNOWN BUG: On AOL4, returns false if IE3 is embedded browser
    // or if this is the first browser window opened.  Thus the
    // variables is_aol, is_aol3, and is_aol4 aren't 100% reliable.

    var is_aol   = (agt.indexOf("aol") != -1);
    var is_aol3  = (is_aol && is_ie3);
    var is_aol4  = (is_aol && is_ie4);

    var is_opera = (agt.indexOf("opera") != -1);
    var is_webtv = (agt.indexOf("webtv") != -1);

    // *** JAVASCRIPT VERSION CHECK ***
    // Useful to workaround Nav3 bug in which Nav3
    // loads <SCRIPT LANGUAGE="JavaScript1.2">.
    var is_js;
    if (is_nav2 || is_ie3) is_js = 1.0
    else if (is_nav3 || is_opera) is_js = 1.1
    else if ((is_nav4 && (is_minor <= 4.05)) || is_ie4) is_js = 1.2
    else if ((is_nav4 && (is_minor > 4.05)) || is_ie5) is_js = 1.3
    else if (is_nav5 && !(is_nav6)) is_js = 1.4
    else if (is_nav6) is_js = 1.5

    // NOTE: In the future, update this code when newer versions of JS
    // are released. For now, we try to provide some upward compatibility
    // so that future versions of Nav and IE will show they are at
    // *least* JS 1.x capable. Always check for JS version compatibility
    // with > or >=.

    else if (is_nav && (is_major > 5)) is_js = 1.4
    else if (is_ie && (is_major > 5)) is_js = 1.3
    // HACK: no idea for other browsers; always check for JS version with > or >=
    else is_js = 0.0;

    // *** PLATFORM ***
    var is_win   = ( (agt.indexOf("win")!=-1) || (agt.indexOf("16bit")!=-1) );
    // NOTE: On Opera 3.0, the userAgent string includes "Windows 95/NT4" on all
    //        Win32, so you can't distinguish between Win95 and WinNT.
    var is_win95 = ((agt.indexOf("win95")!=-1) || (agt.indexOf("windows 95")!=-1));

    // is this a 16 bit compiled version?
    var is_win16 = ((agt.indexOf("win16")!=-1) ||
               (agt.indexOf("16bit")!=-1) || (agt.indexOf("windows 3.1")!=-1) ||
               (agt.indexOf("windows 16-bit")!=-1) );

    var is_win31 = ((agt.indexOf("windows 3.1")!=-1) || (agt.indexOf("win16")!=-1) ||
                    (agt.indexOf("windows 16-bit")!=-1));

    // NOTE: Reliable detection of Win98 may not be possible. It appears that:
    //       - On Nav 4.x and before you'll get plain "Windows" in userAgent.
    //       - On Mercury client, the 32-bit version will return "Win98", but
    //         the 16-bit version running on Win98 will still return "Win95".
    var is_win98 = ((agt.indexOf("win98")!=-1) || (agt.indexOf("windows 98")!=-1));
    var is_winnt = ((agt.indexOf("winnt")!=-1) || (agt.indexOf("windows nt")!=-1));
    var is_win32 = (is_win95 || is_winnt || is_win98 ||
                    ((is_major >= 4) && (navigator.platform == "Win32")) ||
                    (agt.indexOf("win32")!=-1) || (agt.indexOf("32bit")!=-1));

    var is_os2   = ((agt.indexOf("os/2")!=-1) ||
                    (navigator.appVersion.indexOf("OS/2")!=-1) ||
                    (agt.indexOf("ibm-webexplorer")!=-1));

    var is_mac    = (agt.indexOf("mac")!=-1);
    var is_mac68k = (is_mac && ((agt.indexOf("68k")!=-1) ||
                               (agt.indexOf("68000")!=-1)));
    var is_macppc = (is_mac && ((agt.indexOf("ppc")!=-1) ||
                                (agt.indexOf("powerpc")!=-1)));

    var is_sun   = (agt.indexOf("sunos")!=-1);
    var is_sun4  = (agt.indexOf("sunos 4")!=-1);
    var is_sun5  = (agt.indexOf("sunos 5")!=-1);
    var is_suni86= (is_sun && (agt.indexOf("i86")!=-1));
    var is_irix  = (agt.indexOf("irix") !=-1);    // SGI
    var is_irix5 = (agt.indexOf("irix 5") !=-1);
    var is_irix6 = ((agt.indexOf("irix 6") !=-1) || (agt.indexOf("irix6") !=-1));
    var is_hpux  = (agt.indexOf("hp-ux")!=-1);
    var is_hpux9 = (is_hpux && (agt.indexOf("09.")!=-1));
    var is_hpux10= (is_hpux && (agt.indexOf("10.")!=-1));
    var is_aix   = (agt.indexOf("aix") !=-1);      // IBM
    var is_aix1  = (agt.indexOf("aix 1") !=-1);
    var is_aix2  = (agt.indexOf("aix 2") !=-1);
    var is_aix3  = (agt.indexOf("aix 3") !=-1);
    var is_aix4  = (agt.indexOf("aix 4") !=-1);
    var is_linux = (agt.indexOf("inux")!=-1);
    var is_sco   = (agt.indexOf("sco")!=-1) || (agt.indexOf("unix_sv")!=-1);
    var is_unixware = (agt.indexOf("unix_system_v")!=-1);
    var is_mpras    = (agt.indexOf("ncr")!=-1);
    var is_reliant  = (agt.indexOf("reliantunix")!=-1);
    var is_dec   = ((agt.indexOf("dec")!=-1) || (agt.indexOf("osf1")!=-1) ||
           (agt.indexOf("dec_alpha")!=-1) || (agt.indexOf("alphaserver")!=-1) ||
           (agt.indexOf("ultrix")!=-1) || (agt.indexOf("alphastation")!=-1));
    var is_sinix = (agt.indexOf("sinix")!=-1);
    var is_freebsd = (agt.indexOf("freebsd")!=-1);
    var is_bsd = (agt.indexOf("bsd")!=-1);
    var is_unix  = ((agt.indexOf("x11")!=-1) || is_sun || is_irix || is_hpux ||
                 is_sco ||is_unixware || is_mpras || is_reliant ||
                 is_dec || is_sinix || is_aix || is_linux || is_bsd || is_freebsd);

    var is_vms   = ((agt.indexOf("vax")!=-1) || (agt.indexOf("openvms")!=-1));
// additional checks, abk
	var is_anchors = (document.anchors) ? "true":"false";
	var is_regexp = (window.RegExp) ? "true":"false";
	var is_option = (window.Option) ? "true":"false";
	var is_all = (document.all) ? "true":"false";
	
	var is_images = (document.images) ? "true":"false";
	var is_layers = (document.layers) ? "true":"false"; // gecko m7 bug?
// new doc obj tests 990624-abk
	var is_forms = (document.forms) ? "true" : "false";
	var is_links = (document.links) ? "true" : "false";
	var is_frames = (window.frames) ? "true" : "false";
	var is_screen = (window.screen) ? "true" : "false";

// java
	var is_java = (navigator.javaEnabled());
	

	
// hoja de estilos	
 if (is_nav)
	document.write('<link href="nn.css" rel="stylesheet" type="text/css">');
else
	document.write('<link href="ie.css" rel="stylesheet" type="text/css">');	

/********************************
Funcion para contar los caracteres 
del campo
********************************/
function cuenta(pobjTextArea, ancho) {
  if (!(ancho >= pobjTextArea.value.length)) {
    alert("El campo admite un máximo de " + ancho + " caracteres");
    pobjTextArea.value = pobjTextArea.value.substring(0, ancho - 1);
  }
}
/********************************
Funcion para valdiar que la cuenta
de correo tenga la forma correcta
********************************/
function esCorreo(pobjTextArea){
  pobjTextArea.value=trim(pobjTextArea.value);
  var direc=pobjTextArea.value;
  var posarroba;
  if(direc!=null && direc!=''){
    if(!((posarroba=direc.indexOf('@'))>0 && direc.indexOf('.')>0 && direc.indexOf('@',posarroba+1)==-1 && direc.charAt(posarroba+1)!='.' && direc.indexOf(' ')==-1 && (direc.charAt(direc.length-4)=='.' || direc.charAt(direc.length-3)=='.'))){
      alert('El campo no es una direccion de correo valida');
      pobjTextArea.focus();
      pobjTextArea.select();
      return false;
    }
  }
  else
    return false;
}


/********************************
Funcion para valdiar los DNI y
los Cif tanto españoles como 
extranjeros como especiales
********************************/
function validaDNI_NIF(pobjTextArea)
{
	var temp = pobjTextArea.value.toUpperCase(); // pasar a mayúsculas
	if(temp!='')
	{
		if (!/^[A-Za-z0-9]{9}$/.test(temp))// Son 9 dígitos?
		{
			alert('El campo no es un código de identificación valido')
			pobjTextArea.focus();
			pobjTextArea.select();
		}
		else
		{
      if (/^[0-9]{8}[A-Za-z]{1}$/.test(temp))//es un DNI
      {
        if(!validaDNI(temp))
        {
          alert('El valor ' + temp + ' no es un DNI valido.');
          pobjTextArea.focus();
          pobjTextArea.select();
        }
      }
      else
      {
        if (/^[ABCDEFGH]{1}[0-9]{8}$/.test(temp))//es un Cif
        {
          if(!validaCif(temp))
          {
            alert('El campo no es un Cif valido');
            pobjTextArea.focus();
            pobjTextArea.select();
          }
        }
        else
        {
          if (/^[XYZ]{1}[0-9]{7}[TRWAGMYFPDXBNZSQVHLCKEJ]{1}$/.test(temp))//es un DNI extranjero
                        {
                            if(!validaDNIe(temp))
                            {
                                //alert('El campo no es un NIE valido');
                                alert(obtenerTraduccion("nie_invalido", idiomaTradu));
                                pobjTextArea.focus();
                                pobjTextArea.select();
                            }
                        }
          else
          {
            if (/^[ABCDEFGHSPQN]{1}[A-Za-z0-9]{7}[ABCDEFGHIJ]{1}$/.test(temp))//es un Cif entidad
            {
              if(!validaCife(temp))
              {
                alert('El campo no es un Cod. Id valido');
                pobjTextArea.focus();
                pobjTextArea.select();
              }
            }
            else
            {
              alert('El campo no es un código de identificación valido');
              pobjTextArea.focus();
              pobjTextArea.select();
            }
          }
        }    
      }
		}
	}
}

/********************************
Validar un DNI
********************************/
function validaDNI(dni)
{
	var numeros=dni.substr(0,8);
	var letra=dni.substr(8,1);
	var validacion;
	cadena="TRWAGMYFPDXBNJZSQVHLCKET";
	//posicion = parseInt(numeros) % 23;
	posicion = new Number(numeros) % 23;
	validacion = cadena.substr(posicion,1);
	//validacion = cadena.substring(posicion,posicion+1);
	if(validacion==letra)
		return true;
	else
		return false;
}

/********************************
Validar un DNI extranjero
********************************/
function validaDNIe(dni)
{
    var numeros=dni.substr(1,7);
    var primera_letra=dni.substr(0,1);
    if(primera_letra=='Y' || primera_letra=='y')
        numeros='1'+numeros;
    var letra=dni.substr(8,9);
    var validacion;
    cadena="TRWAGMYFPDXBNJZSQVHLCKET";
    posicion = new Number(numeros) % 23;
    validacion = cadena.substring(posicion,posicion+1);
    if(validacion==letra)
        return true;
    else
        return false;
}
/*function validaDNIe(dni)
{
	var numeros=dni.substr(1,7);
	var letra=dni.substr(8,9);
	var validacion;
	cadena="TRWAGMYFPDXBNJZSQVHLCKET";
	posicion = new Number(numeros) % 23;
	validacion = cadena.substring(posicion,posicion+1);
	if(validacion==letra)
		return true;
	else
		return false;
}*/

/********************************
Validar un CIF
********************************/
function validaCif(cif)
{ 
	var control=cif.substring(8,9);
	var v1 = new Array(0,2,4,6,8,1,3,5,7,9); 
	var temp = 0; 
	for( i = 2; i <= 6; i += 2 ) 
	{
		temp = temp + v1[ new Number(cif.substr(i-1,1))];
		temp = temp + new Number(cif.substr(i,1));
	}
	//temp = temp + v1[ parseInt(cif.substr(7,1))];
	temp = temp + v1[ new Number(cif.substr(7,1))];
	temp = (10 - ( temp % 10));
	if( temp == 10 )
	{
		if(control=='0')
			return true;
		else
			return false;
	}
	else
	{
		if(temp==control)
			return true;
		else
			return false;
	}
}

/********************************
Validar un CIF especial
********************************/
function validaCife(cif)
{ 
	var control=cif.substring(8,9);
  var v1 =(parseInt(cif.substring(1,2)) * 2);
  var v2 = parseInt(cif.substring(2,3));
  var v3 =(parseInt(cif.substring(3,4)) * 2);
  var v4 = parseInt(cif.substring(4,5));
  var v5 =(parseInt(cif.substring(5,6)) * 2);
  var v6 = parseInt(cif.substring(6,7));
  var v7 =(parseInt(cif.substring(7,8)) * 2);
  var vv1;
  var vv3;
  var vv5;
  var vv7;
  var r1;
  var r2;
  var r;
  var res;
  var cc;
  var dc;
  
  if(v1>=10)
    vv1 = v1%10 + Math.floor(v1/10);
  else
    vv1 = v1;
  if(v3 >= 10)
    vv3 = v3%10 + Math.floor(v3/10);
  else
    vv3 = v3;
  if(v5 >= 10)
    vv5 = v5%10 + Math.floor(v5/10);
  else
    vv5 = v5;
  if(v7 >= 10)
    vv7 = v7%10 + Math.floor(v7/10);
  else
    vv7 = v7;
    
  r1 = v2+v4+v6;
  r2 = vv1+vv3+vv5+vv7;
  r = r1+r2;
  
  res = r%10;
  
  cc = 10 - res;
  
  if(cc == 10) 
    dc = 0;
  else
    dc = cc;
  
  var vdc = new Array('J','A','B','C','D','E','F','G','H','I'); 
  if(vdc[dc]==control)
  return true;
  else
  return false;
}

/********************************
Checkear
********************************/
function checkea(ckecbox, hidden)
{
	if(ckecbox.checked==true)
		hidden.value='S';
	else
		hidden.value='N';
}
/********************************
Pasa a mayusculas
********************************/
function Mayusculas(pobjTextArea){
	pobjTextArea.value=trim(pobjTextArea.value);
	pobjTextArea.value=pobjTextArea.value.toUpperCase();
}
/********************************
Validar que el contenido de un campo
es nmérico y si no lo es seleccionarlo
********************************/
function esNumero(pobjTextArea,enteros,decimales)
{
	var temp = pobjTextArea.value;
  var gram='';
  var gram2='';
  if(temp!=''){
    if(decimales!=null && enteros!=null)
    {
      if(decimales<=0)
      {
        gram=new RegExp("^[0-9]{1,"+enteros+"}$");
        if (!gram.test(temp))//todo dígitos
        {
          alert('- Solo se admiten valores numéricos. Separación decimal con punto (.)\n- Superada la longitud de la parte entera (max '+enteros+' dígitos).\n- Superada la longitud de la parte decimal (max '+decimales+' dígitos).');
          objetoJS=pobjTextArea;
          setTimeout("focusSelect();",10); 
          return false;
        } 
        else
        {
          return true;
        }
      }
      else
      { 
        gram = new RegExp('^[0-9]{1,'+enteros+'}$');
        gram2 = new RegExp('^[0-9]{1,'+enteros+'}[\.]{1}[0-9]{1,'+(decimales)+'}$');
        if (!gram.test(temp) && !gram2.test(temp))
        {
          alert('- Solo se admiten valores numéricos. Separación decimal con punto (.)\n- Superada la longitud de la parte entera (max '+enteros+' dígitos).\n- Superada la longitud de la parte decimal (max '+decimales+' dígitos).');
          objetoJS=pobjTextArea;
          setTimeout("focusSelect();",10); 
          return false;
        }    
        else
        {
          return true;
        }      
      }
    }
    else
      return false;
  }
  else
    return true;
}

/********************************
Validar el tamaño de un campo y
si sobrepasa el valor seleccionarlo
********************************/
function maxLongitud(pobjTextArea,longitud)
{
  //document.getElementById(pobjTextArea)
  var temp = pobjTextArea.value;
  if(temp!=''){
    if(temp.length>longitud)
    {
      alert('- Superada la longitud del campo. Máximo admitido '+longitud+'.');
      objetoJS=pobjTextArea;
      setTimeout("focusSelect();",10);      
      return false;
    }
    else
    {
      return true;
    }
  }
  else
    return true;
}

/***************************
Eliminar caracteres extraños de
los números de teléfono
****************************/
function validaTelefono(pobjTextArea)
{
	var temp = pobjTextArea.value;
  var gram='';

  if(temp!=''){
    temp=temp.replace(/\(/g,"");
    temp=temp.replace(/\)/g,"");
    temp=temp.replace(/\+/g,"");
    temp=temp.replace(/\-/g,"");
    temp=temp.replace(/\./g,"");
    
    pobjTextArea.value=temp;
  }
  else
    return true;
}

/*******************************
Varible js que se le asigna
el valor del objeto que qeuremos 
que la función de el foco y 
luego seleccione
********************************/
var objetoJS=null;
function focusSelect()
{
  if(objetoJS!=null)
  {
    objetoJS.focus();
    objetoJS.select();
  }
  objetoJS=null;
}

/******************************
Extrae el nombre de un fichero
a partir de su ruta
******************************/
function extrae_nombre(name)
{
	var ary=name.split("\\");
	return ary[ary.length-1];
}

/****************************************
Generar el XML que será guardado para
la proxima vez que se necesite recuperar
los datos de la solicitud
*****************************************/
function generaXMLAvance(pObjFormulario, tipo, idform)
{
  var xml='';
  var datosXML=generaXMLEnvio(pObjFormulario, tipo) ;
  
  xml=datosXML.substr(0,datosXML.indexOf("<XML>",0)+5);
  xml +='<'+'IDFORM>'+idform+'</'+'IDFORM>';
  xml +=datosXML.substr(datosXML.indexOf("<XML>",0)+5,datosXML.length);  
  
  return xml;
}

/****************************************
Cargar todo lo avanzado en una solicitud
que previamente ha sido guardado en un 
fichero XML que la propia pantalla generó
*****************************************/


function cargarXMLAvance(ficheroXML, idform){
  if(ficheroXML!='')
  {
    var xmlDoc = null;
    if (is_ie){
      try{
        xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async="false";
        xmlDoc.loadXML(ficheroXML);			
      } catch (e){ alert("Se produjo un error al crear un objeto para leer xml. \nError: " + e.message); return;  }
    }
    else{			
      try{
        parser=new DOMParser();
          xmlDoc=parser.parseFromString(ficheroXML,"text/xml");
      } catch (e){ alert("Se produjo un error al crear un objeto para leer xml. \nError: " + e.message); return;  }
    }
    
    var elementoXML;
    var elementoXMLaux;
    var elementosMismoId;
    var itemsListaDinamica;
    var k=0;
    var nombreBase="";
    var nombreBase2="";
    var htmlExtra="";
    var todosElementos=document.formulario.elements;
    var valido=false;
    
    try{
      elementoXML = xmlDoc.getElementsByTagName('XML');
      if(elementoXML[0].childNodes.length>1)
      {
        if(elementoXML[0].childNodes[0].nodeName!=null && elementoXML[0].childNodes[0].childNodes[0].nodeValue!=null)
        {
          if(elementoXML[0].childNodes[0].nodeName=='IDFORM' && elementoXML[0].childNodes[0].childNodes[0].nodeValue==idform)
            valido=true;
        }
      }
      if(valido)  
      {
        for( i = 1; i < elementoXML[0].childNodes.length; i++){
          if(elementoXML[0].childNodes[i].nodeName!=null)
          {          
            nombreBase=elementoXML[0].childNodes[i].nodeName;
            if(document.getElementById(nombreBase)!=null)
            {
              //if(elementoXML[0].childNodes[i].childNodes[0].nodeValue!=null)
              //{
                if(document.getElementById(nombreBase).type=='checkbox')
                {
                  if(elementoXML[0].childNodes[i].childNodes[0]==null)
                  {
                    document.getElementById(nombreBase+'_h').value='S';                                  
                    javascript:checkea(nombreBase,nombreBase+'_h');
                  }
                  else
                  {
                    if(elementoXML[0].childNodes[i].childNodes[0].nodeValue=='' || elementoXML[0].childNodes[i].childNodes[0].nodeValue=='Si')
                    {
                      document.getElementById(nombreBase+'_h').value='S';                                  
                      javascript:checkea(nombreBase,nombreBase+'_h');
                    }
                    else
                    {
                      document.getElementById(nombreBase+'_h').value='N';                                  
                      javascript:checkea(nombreBase,nombreBase+'_h');
                    }
                  }
                }
                else              
                {
                  if(document.getElementById(nombreBase).type=='radio')
                  {
                    if(elementoXML[0].childNodes[i].childNodes[0]!=null)
                    {
                      for(j=0; j<todosElementos.length; j++)
                      {
                        if(todosElementos[j].name==nombreBase && todosElementos[j].type=='radio')
                        {
                          if(todosElementos[j].value==elementoXML[0].childNodes[i].childNodes[0].nodeValue)
                          {
                            todosElementos[j].checked='checked';
                          }
                        }
                      }
                    }
                    else
                    {
                      for(j=0; j<todosElementos.length; j++)
                      {
                        if(todosElementos[j].name==nombreBase && todosElementos[j].type=='radio')
                        {
                          if(todosElementos[j].value==elementoXML[0].childNodes[i].childNodes[0])
                          {
                            todosElementos[j].checked='';
                          }
                        }
                      }
                    }
                  }
                  else
                  {
                    if(elementoXML[0].childNodes[i].childNodes[0]!=null)
                    {
                      document.getElementById(nombreBase).value=elementoXML[0].childNodes[i].childNodes[0].nodeValue;
                    }
                    else
                    {
                      document.getElementById(nombreBase).value='';
                    }
                  }
                }
              //}
              //else
                //document.getElementById(nombreBase).value='';
            }
            else
            {                    
              if(document.getElementById(nombreBase+'Clave')!=null)
              {
                if(elementoXML[0].childNodes[i].childNodes[0]!=null)
                {
                  document.getElementById(nombreBase+'Clave').value=elementoXML[0].childNodes[i].childNodes[0].nodeValue;  
                 
                  if(document.getElementById(nombreBase+'Secarga')!=null)
                    document.getElementById(nombreBase+'Secarga').value='SI';
                  if(document.getElementById(nombreBase+'pulsado'))
                    document.getElementById(nombreBase+'pulsado').value='SI';
                }
              }  
              else
              {
                if(document.getElementById('MuLtI0_'+nombreBase)!=null)
                {
                  elementoXMLaux=elementoXML[0].childNodes[i].getElementsByTagName('SELECCION');
                  k=0;
                  do{
                    document.getElementById('MuLtI'+k+'_'+nombreBase).checked='';
                    k++;
                  }while(document.getElementById('MuLtI'+k+'_'+nombreBase)!=null);
                  
                  k=0;              
                  do{
                    for( j = 0; j < elementoXMLaux.length; j++)
                    {
                      if(elementoXMLaux[j].childNodes[0]!=null)
                      {
                        if(document.getElementById('MuLtI'+k+'_'+nombreBase).value==elementoXMLaux[j].childNodes[0].nodeValue)                
                          document.getElementById('MuLtI'+k+'_'+nombreBase).checked='checked';
                      }
                    }
                    k++;
                  }while(document.getElementById('MuLtI'+k+'_'+nombreBase)!=null);
                }
                else
                {        
                  itemsListaDinamica=elementoXML[0].childNodes[i].getElementsByTagName('ITEM_'+nombreBase);                
                  if(itemsListaDinamica.length>0)
                  {
                    document.getElementById('LiStA_'+nombreBase+'filas').value=itemsListaDinamica.length;
                    
                    var field;
                    for(j=0; j<itemsListaDinamica.length; j++)                  
                    {
                      for(k=0; k<itemsListaDinamica[j].childNodes.length; k++)
                      {
                        nombreBase2=itemsListaDinamica[j].childNodes[k].nodeName;
                        field = document.createElement('LiStA_'+nombreBase+'_'+nombreBase2+'_'+(j+1));
                        
                        field.innerHTML = '<input '+'type="HIDDEN" id="LiStA_'+nombreBase+'_'+nombreBase2+'_'+(j+1)+'"'
                        + ' name="LiStA_'+nombreBase+'_'+nombreBase2+'_'+(j+1)+'"'
                        + ' value = "'+itemsListaDinamica[j].childNodes[k].childNodes[0].nodeValue+'" '+'/>';
                                              
                        document.formulario.appendChild(field);
                      }
                    }              
                  }
                }
              }
            }                     
          }
        }
        document.formulario.submit();   
        return true;
      }
      else
      {
        var mensaje = "El fichero seleccionado no tiene un formato correcto para";
        mensaje += "\nrecuperar los datos de la solicitud";
        alert(mensaje); 
      
        document.formulario.submit(); 
        return null;
      }
    }catch (e) { 
      var mensaje = "Se ha producido un error procesando el fichero. No se continua con la carga.";
      mensaje += "\nEs posible que el fichero no tenga un formato correcto";
      alert(mensaje + "\nError: " + e.message); 
      //document.formulario.submit(); 
      return null;
    }
  }
  return null;
}

/******************************
Función antigua
******************************/
function validaMestra(pObjFormulario, nombre, valor, id){
  document.forms[3].parametro.value = nombre + "~" + valor + "~" + id;
  pObjFormulario.submit();
}

/******************************
Función antigua
******************************/
function generaXML(pObjFormulario) {
var muestra = '';
var aux='';
var l;
var cont = '<?xml version="1.0" encoding="ISO-8859-1"?>\n'
cont += '<XML>\n';
for (var i = 0; i < document.formulario.length; i++) {
if (document.forms[0].elements[i].type != 'button') {
if (!(document.forms[0].elements[i].type == 'radio' && document.forms[0].elements[i].checked != true)) {
if (document.forms[0].elements[i].type == 'checkbox') {
if (document.forms[0].elements[i].checked == true) {
cont += '<' + document.forms[0].elements[i].name + '>S</' + document.forms[0].elements[i].name + '>\n';
} else {
cont += '<' + document.forms[0].elements[i].name + '>N</' + document.forms[0].elements[i].name + '>\n';
}
} else {
if(muestra=='' | (muestra.length>document.forms[0].elements[i].name.length | muestra!=document.forms[0].elements[i].name.substring(0,muestra.length))){
if (trim(document.forms[0].elements[i].value) == ""){
if (document.forms[0].elements[i].lang == "S") {
l=document.forms[0].elements[i].name.length;
if(l>5){
aux=document.forms[0].elements[i].name.substring(l-5,l);
if(aux=='Clave'){
muestra=document.forms[0].elements[i].name.substring(0,l-5);
cont += '<' + muestra + '>' + trim(document.forms[0].elements[i].value) + '</' + muestra + '>';

}
else{
muestra='';
cont += '<' + document.forms[0].elements[i].name + '>' + trim(document.forms[0].elements[i].value) + '</' + document.forms[0].elements[i].name + '>';

}
}
else{
muestra='';
cont += '<' + document.forms[0].elements[i].name + '>' + trim(document.forms[0].elements[i].value) + '</' + document.forms[0].elements[i].name + '>';

}
}
}
else {
l=document.forms[0].elements[i].name.length;
if(l>5){
aux=document.forms[0].elements[i].name.substring(l-5,l);
if(aux=='Clave'){
muestra=document.forms[0].elements[i].name.substring(0,l-5);
cont += '<' + muestra + '>' + trim(document.forms[0].elements[i].value) + '</' + muestra + '>';

}
else{
muestra='';
cont += '<' + document.forms[0].elements[i].name + '>' + trim(document.forms[0].elements[i].value) + '</' + document.forms[0].elements[i].name + '>';

}
}
else{
muestra='';
cont += '<' + document.forms[0].elements[i].name + '>' + trim(document.forms[0].elements[i].value) + '</' + document.forms[0].elements[i].name + '>';

}
}
}
}
}
}
}
cont = cont + '</' + 'XML>';
document.forms[1].xml.value = cont;
pObjFormulario.submit();
}


/******************************
Función antigua
******************************/
function trim(sString) {
  while (sString.substring(0, 1) == ' ') {
    sString = sString.substring(1, sString.length);
  }
  while (sString.substring(sString.length - 1, sString.length) == ' ') {
    sString = sString.substring(0, sString.length - 1);
  }
  return sString;
}

/******************************
Función que Valida el contenido
y formato de los campos del 
formulario de datos del envío
******************************/
function validaCamposForm(pObjFormulario, tipo) {
	var muestra = '';
	var aux='';
	var l;
	var anterior = "";
	var titAnterior = "";
	var radio = "N";
	var chequeado = "N";
	var obligatorio = "N";
	var noml = '';
	var gnoml = '';
	var iteml = '';
	var gniteml = '';
	var niteml = '';
	var gnom_m = '';
  var tienePago = false;
  
  /**Indica el codigo de retorno correcto de la pasarela de pago**/
	var PAGO_CORRECTO = '1';
	
	//comprobamos si el formulario tiene un bloque de pago y si este es obligatorio de que este en
	//un estado correcto
	try{
		if (document.getElementById('hayBloquePago') != undefined) tienePago = true;		
	}	catch (e){tienePago=false;}
	if (tienePago){
		var obligatorio = document.getElementById('bloquePagoObligatorio').value;
		if (obligatorio == 'S'){
			var codRespuesta = document.getElementById('PAGO00000000006').value;	
			if(codRespuesta == ''){
				alert("Se debe realizar el pago antes de enviar los datos");	
				return false;
			}
			else{
				if ( codRespuesta != PAGO_CORRECTO ){
					alert("El c\u00F3digo devuelto en la operaci\u00F3n de pago no es correcto o se ha denegado la operaci\u00F3n");	
					return false;
				}
			}
		}
		//recuperamos los valores enviados a la pasarela de pagos		
		document.getElementById('PAGO00000000000').value = document.getElementById('PAGO00000000000_Ant').value;
		document.getElementById('PAGO00000000001').value = document.getElementById('PAGO00000000001_Ant').value;
		document.getElementById('PAGO00000000002').value = document.getElementById('PAGO00000000002_Ant').value;
		var dinero = document.getElementById('PAGO00000000003_Ant').value;
		if (dinero.length > 2){
			if(dinero.substr(dinero.length-2) == '00'){
				
				dinero = dinero.substr(0, dinero.length-2);
			}
			else{
				dinero = dinero.substr(0, dinero.length-2) + "," + dinero.substr(dinero.length-2, dinero.length);
			}
		}
		
		document.getElementById('PAGO00000000003').value = dinero;
		document.getElementById('PAGO00000000004').value = document.PAGO_FORMULARIO.CENTRO.value;
		document.getElementById('PAGO00000000005').value = document.PAGO_FORMULARIO.TPV.value;
		if (document.PAGO_FORMULARIO.IDIOMA.value == 'C'){
			document.getElementById('PAGO00000000008_CASTELLANO').checked = true;
			document.getElementById('PAGO00000000008_VALENCIANO').checked = false;
		}
		else{
			document.getElementById('PAGO00000000008_CASTELLANO').checked = false;
			document.getElementById('PAGO00000000008_VALENCIANO').checked = true;			
		}
	}
  
	for (var i = 0; i < document.formulario.length; i++) {
		if (document.forms[0].elements[i].name != 'trama' && document.forms[0].elements[i].name.substring(0,4) != 'ldap') {
			if (document.forms[0].elements[i].type != 'button') {
				if (document.forms[0].elements[i].type != 'radio') {
					if (radio == "S") {
						if (obligatorio == "S") {
							if (chequeado == "N") {
								alert("El campo " + titAnterior + " es obligatorio")
								return false;
							}
						}
					}
					radio = "N";
					chequeado = "N";
					obligatorio = "N";
					if((document.forms[0].elements[i].name.substring(0,6)=="LiStA_") & (document.forms[0].elements[i].name.indexOf("_",0)==document.forms[0].elements[i].name.lastIndexOf("_")))
					{
						if(document.forms[0].elements[i].lang == "S" && document.forms[0].elements[i].value=='0')
						{
							alert("La lista " + document.forms[0].elements[i].title + " es obligatoria");
							return false;
						}
					} else{  
						if (trim(document.forms[0].elements[i].value).length < 1) {
							if (document.forms[0].elements[i].lang == "S") {
								alert("El campo " + document.forms[0].elements[i].title + " es obligatorio");
								return false;
						}
						}
					}
					anterior = document.forms[0].elements[i].name;
					titAnterior = document.forms[0].elements[i].title;
				} else {
					if (radio == "S") {            
						if (anterior == document.forms[0].elements[i].name) {
							if (document.forms[0].elements[i].lang == "S") {
								obligatorio = "S";
								if (!document.forms[0].elements[i-1].checked) {
									if (document.forms[0].elements[i].checked) {
									chequeado = "S";
									}
								} else {
									chequeado = "S";
								}
							} else {
								obligatorio = "N";
							}
						} else {   
							if (obligatorio == "S") {
								if (chequeado == "N") {

									alert("El campo " + titAnterior + " es obligatorio");
									return false;
								}
							}
              //abrimos un nuevo campo de radio buttons
              radio = "S";
              chequeado = "N";
              obligatorio = "N";
              anterior = document.forms[0].elements[i].name;
              titAnterior = document.forms[0].elements[i].title;
						}                        
					} else {
						if (document.forms[0].elements[i].lang == "S") {
							obligatorio = "S";
							if (document.forms[0].elements[i].checked) {
								chequeado = "S";
							}
						} else {
							obligatorio = "N";
						}
					}
					radio = "S";
					anterior = document.forms[0].elements[i].name;
					titAnterior = document.forms[0].elements[i].title;
				}
			}
		}
	}
  generaXMLEnvio(pObjFormulario, tipo);
  
  return true;
}  

/******************************
Función que genera el XML de
datos del formulario de datos
******************************/
function generaXMLEnvio(pObjFormulario, tipo) {  
  var muestra = '';
	var aux='';
	var l;
	var anterior = "";
	var titAnterior = "";
	var radio = "N";
	var chequeado = "N";
	var obligatorio = "N";
	var noml = '';
	var gnoml = '';
	var iteml = '';
	var gniteml = '';
	var niteml = '';
	var gnom_m = ''; 

	var cont = '<?xml version="1.0" encoding="ISO-8859-1"?>\n'
	cont += '<XML>\n';
	for (var i = 0; i < document.formulario.length; i++) {    
		if (document.forms[0].elements[i].name != 'trama' && document.forms[0].elements[i].name.substring(0,4) != 'ldap' 
      && document.forms[0].elements[i].name != 'PAGO_DESCRIPCION' && document.forms[0].elements[i].name != 'PAGO_INFORMACION') {
			if (document.forms[0].elements[i].type != 'button') {
				if (document.forms[0].elements[i].type != 'hidden') {
					if (!(document.forms[0].elements[i].type == 'radio' && document.forms[0].elements[i].checked != true)) {
						if (document.forms[0].elements[i].type == 'checkbox') {
							if(gnoml!='')
							{
								cont += '</'+'ITEM_' + gnoml + '>'; 
								cont += '</' + gnoml + '>'; 
								gnoml='';
								gniteml='';
							}
							if(document.forms[0].elements[i].name.substr(0,5)=='MuLtI')
							{
								if(gnom_m!='')
								{
									if(document.forms[0].elements[i].name.substr(document.forms[0].elements[i].name.indexOf("_",0)+1,15)!=gnom_m)
									{
										cont += '</' + gnom_m + '>'; 
										gnom_m='';
									}
								}
								if (document.forms[0].elements[i].checked == true)
								{
									if(gnom_m=='')
									{
										gnom_m=document.forms[0].elements[i].name.substr(document.forms[0].elements[i].name.indexOf("_",0)+1,15);
										cont += '<'+gnom_m + '>'; 
									}
									else
									{
										if(document.forms[0].elements[i].name.substr(document.forms[0].elements[i].name.indexOf("_",0)+1,15)!=gnom_m)
										{
											cont += '</' + gnom_m + '>'; 
											gnom_m=document.forms[0].elements[i].name.substr(document.forms[0].elements[i].name.indexOf("_",0)+1,15);
											cont += '<'+gnom_m + '>';
										}
									}
									cont += '<SELECCION>' + trim(document.forms[0].elements[i].value.replace('&', '&amp;').replace('<', '&lt;')) + '</'+'SELECCION>';
								}
							} else { 
								if(gnom_m!='')
								{
									cont += '</' + gnom_m + '>'; 
									gnom_m='';
								}
								if (document.forms[0].elements[i].checked == true) {
									cont += '<' + document.forms[0].elements[i].name + '>Si</' + document.forms[0].elements[i].name + '>\n';
								} else {
									cont += '<' + document.forms[0].elements[i].name + '>No</' + document.forms[0].elements[i].name + '>\n';
								}
							}
						} else {
							if(gnom_m!='')
							{
								cont += '</' + gnom_m + '>';
								gnom_m='';
							}
							if(document.forms[0].elements[i].name.substring(0,6)=="LiStA_"){
								if(document.forms[0].elements[i].name.indexOf("_",0)!=document.forms[0].elements[i].name.lastIndexOf("_"))
								{
									aux=document.forms[0].elements[i].name.substring(6,document.forms[0].elements[i].name.length);
									noml=aux.substring(0,(aux.indexOf("_",0)));
									aux=aux.substring(aux.indexOf("_",0)+1,aux.length);
									iteml=aux.substring(0,aux.indexOf("_",0));
									aux=aux.substring(aux.indexOf("_",0)+1,aux.length);
									niteml=aux.substring(0,aux.length);
									if(gnoml!=noml){
										if(gnoml!='')
										{
											cont += '</'+'ITEM_' + gnoml + '>';
											cont += '</' + gnoml + '>';
										}
										cont += '<' + noml + '>';
										cont += '<ITEM_' + noml + '>';
										cont += '<' + iteml + '>' + trim(document.forms[0].elements[i].value.replace('&', '&amp;').replace('<', '&lt;')) + '</' + iteml + '>';
										gnoml=noml;
										gniteml=niteml;
									} else {
										if(gniteml!=niteml)
										{
											if(gniteml!='')
												cont += '</'+'ITEM_' + noml + '>';
											cont += '<ITEM_' + noml + '>';
											cont += '<' + iteml + '>' + trim(document.forms[0].elements[i].value.replace('&', '&amp;').replace('<', '&lt;')) + '</' + iteml + '>';  
											gniteml=niteml;
										} else {
											cont += '<' + iteml + '>' + trim(document.forms[0].elements[i].value.replace('&', '&amp;').replace('<', '&lt;')) + '</' + iteml + '>';                  
										}
									}
								}
							} else { 
								if(gnoml!='')
								{
									cont += '</'+'ITEM_' + gnoml + '>'; 
									cont += '</' + gnoml + '>'; 
									gnoml='';
									gniteml='';
								}
								if (document.forms[0].elements[i].name != '')
								{
        								if(muestra=='' | (muestra.length>document.forms[0].elements[i].name.length | muestra!=document.forms[0].elements[i].name.substring(0,muestra.length))){
        									if (trim(document.forms[0].elements[i].value) == ""){
        										if (document.forms[0].elements[i].lang == "S") {
        											l=document.forms[0].elements[i].name.length;
        											if(l>5){
        												aux=document.forms[0].elements[i].name.substring(l-5,l);
        												if(aux=='Clave'){
        													muestra=document.forms[0].elements[i].name.substring(0,l-5);
        													cont += '<' + muestra + '>' + trim(document.forms[0].elements[i].value.replace('&', '&amp;').replace('<', '&lt;')) + '</' + muestra + '>';
        												} else{
        													muestra='';
        													cont += '<' + document.forms[0].elements[i].name + '>' + trim(document.forms[0].elements[i].value.replace('&', '&amp;').replace('<', '&lt;')) + '</' + document.forms[0].elements[i].name + '>';  
        												}
        											} else {
        												muestra='';
        												cont += '<' + document.forms[0].elements[i].name + '>' + trim(document.forms[0].elements[i].value.replace('&', '&amp;').replace('<', '&lt;')) + '</' + document.forms[0].elements[i].name + '>';
        											}
        										}
        									} else {
        										l=document.forms[0].elements[i].name.length;
        										if(l>5){
        											aux=document.forms[0].elements[i].name.substring(l-5,l);
        											if(aux=='Clave'){
        												muestra=document.forms[0].elements[i].name.substring(0,l-5);
        												cont += '<' + muestra + '>' + trim(document.forms[0].elements[i].value.replace('&', '&amp;').replace('<', '&lt;')) + '</' + muestra + '>';  
        											} else{
        												muestra='';
        												cont += '<' + document.forms[0].elements[i].name + '>' + trim(document.forms[0].elements[i].value.replace('&', '&amp;').replace('<', '&lt;')) + '</' + document.forms[0].elements[i].name + '>';
        											}
        										} else{
        											muestra='';
        											cont += '<' + document.forms[0].elements[i].name + '>' + trim(document.forms[0].elements[i].value.replace('&', '&amp;').replace('<', '&lt;')) + '</' + document.forms[0].elements[i].name + '>';
        										}
        									}
        								}
							      }
								/*if(muestra=='' | (muestra.length>document.forms[0].elements[i].name.length | muestra!=document.forms[0].elements[i].name.substring(0,muestra.length))){
									if (trim(document.forms[0].elements[i].value) == ""){
										if (document.forms[0].elements[i].lang == "S") {
											l=document.forms[0].elements[i].name.length;
											if(l>5){
												aux=document.forms[0].elements[i].name.substring(l-5,l);
												if(aux=='Clave'){
													muestra=document.forms[0].elements[i].name.substring(0,l-5);
													cont += '<' + muestra + '>' + trim(document.forms[0].elements[i].value.replace('&', '&amp;').replace('<', '&lt;')) + '</' + muestra + '>';
												} else{
													muestra='';
													cont += '<' + document.forms[0].elements[i].name + '>' + trim(document.forms[0].elements[i].value.replace('&', '&amp;').replace('<', '&lt;')) + '</' + document.forms[0].elements[i].name + '>';  
												}
											} else {
												muestra='';
												cont += '<' + document.forms[0].elements[i].name + '>' + trim(document.forms[0].elements[i].value.replace('&', '&amp;').replace('<', '&lt;')) + '</' + document.forms[0].elements[i].name + '>';
											}
										}
									} else {
										l=document.forms[0].elements[i].name.length;
										if(l>5){
											aux=document.forms[0].elements[i].name.substring(l-5,l);
											if(aux=='Clave'){
												muestra=document.forms[0].elements[i].name.substring(0,l-5);
												cont += '<' + muestra + '>' + trim(document.forms[0].elements[i].value.replace('&', '&amp;').replace('<', '&lt;')) + '</' + muestra + '>';  
											} else{
												muestra='';
												cont += '<' + document.forms[0].elements[i].name + '>' + trim(document.forms[0].elements[i].value.replace('&', '&amp;').replace('<', '&lt;')) + '</' + document.forms[0].elements[i].name + '>';
											}
										} else{
											muestra='';
											cont += '<' + document.forms[0].elements[i].name + '>' + trim(document.forms[0].elements[i].value.replace('&', '&amp;').replace('<', '&lt;')) + '</' + document.forms[0].elements[i].name + '>';
										}
									}
								}*/
							}
						}
					}
				}
				else
				{
					if(document.forms[0].elements[i].name.substring(0,8)=="InTeRnO_"){
						if(gnom_m!='')
						{
							cont += '</' + gnom_m + '>';
							gnom_m='';
						}
						if(gnoml!='')
						{
							cont += '</'+'ITEM_' + gnoml + '>'; 
							cont += '</' + gnoml + '>'; 
							gnoml='';
							gniteml='';
						}
						noml=document.forms[0].elements[i].name.substring(8,document.forms[0].elements[i].name.length);
						muestra='';
						cont += '<INTERNO_' + noml + '>' + trim(document.forms[0].elements[i].value.replace('&', '&amp;').replace('<', '&lt;')) + '</'+'INTERNO_' + noml + '>';
					}
				}
			}
		}
	}
	if(gnoml!='')
	{
		cont += '</'+'ITEM_' + gnoml + '>'; 
		cont += '</' + gnoml + '>'; 
		gnoml='';
		gniteml='';
	}
	if(gnom_m!='')
	{
		cont += '</' + gnom_m + '>'; 
		gnom_m='';
	}
	cont = cont + '</' + 'XML>';
	if (tipo == "V") {
		document.forms[2].xmlv.value = cont;
	} else {
		document.forms[1].xml.value = cont;
	}

	return cont;
}

/***********************
Devuelve un xml a partir 
de una cadena
************************/
function loadXMLString(txt)
{
	try //Internet Explorer
	{
		xmlDoc=new ActiveXObject('Microsoft.XMLDOM');
		xmlDoc.async='false';
		xmlDoc.loadXML(txt);
		return(xmlDoc);
	}
	catch(e)
	{
	try //Firefox, Mozilla, Opera, etc.
	{
		parser=new DOMParser();
		xmlDoc=parser.parseFromString(txt,'text/xml');
		return(xmlDoc);
	}
	catch(e) {alert(e.message)}
	}
	return(null);
}

/*****************************  
Guarda en el XML el contenido 
de los ficheros, y elimina la 
ruta dejando solo el nombre de 
archivo
*****************************/
function carga_contenido_ficheros()
{
	var xml = document.getElementById('xml').value;
	var xml_ficheros = document.getElementById('XMLFicheros').value;
	var inicioBusqueda = 0;
	var rutas = new Array();
	var i = 0;
	// Obtenemos las rutas del xml de ficheros
	while (true)
	{
		var campo = '<RUTA>';
		var inicioRuta = xml_ficheros.indexOf(campo, inicioBusqueda) + campo.length;
		if (inicioRuta <= campo.length)
			break;
		var campo = '<\/RUTA>';
		var finRuta = xml_ficheros.indexOf(campo, inicioBusqueda);
		var ruta = xml_ficheros.substring(inicioRuta, finRuta);
		if (ruta != '')
		{
			rutas[i] = ruta;
			i += 1;
		}
		inicioBusqueda = finRuta + campo.length;
	}
	// Añadimos el contenido de los ficheros al xml
	xmlDoc = loadXMLString(xml);
	x=xmlDoc.getElementsByTagName("*");
	for (i = 0; i < rutas.length; i+=1)
	{
		var ruta = rutas[i];
		var campo = '';
    
		// Busco el nombre del campo correspondiente a la ruta
    var inicioCampo = xml.indexOf(ruta) + ruta.length + 2;
    var finCampo = xml.indexOf('>', inicioCampo);
    campo = xml.substring(inicioCampo, finCampo);

		/*for (j = 0; j < x.length; j+=1)
		{
			valor = x[j].childNodes[0].nodeValue;
			if (valor == ruta)
			{
				campo = x[j].tagName;
				break;
			}
		}*/
		// Obtengo el contenido del fichero en base64
		var contenidoFichero = document.Obtenerfirma.leefichero(ruta);
		var campoContenido = '<' + campo + '_CONTENIDO>' + contenidoFichero + '</' + campo + '_CONTENIDO>';
		// Sustituyo la ruta local por el nombre de archivo
		var inicioRuta = xml.indexOf(ruta);
		var finRuta = xml.indexOf(ruta) + ruta.length;
		var ultimaBarra = xml.substring(inicioRuta, finRuta).lastIndexOf('\\') + inicioRuta + 1;
		xml = xml.substring(0, inicioRuta) + xml.substring(ultimaBarra, xml.length);
		// Meto el contenido del fichero en el xml
		var inicioCampo = xml.indexOf('<' + campo + '>');
		xml = xml.substring(0, inicioCampo) + campoContenido + xml.substring(inicioCampo, xml.length);
	}
  
	document.forms['formEnvio'].xml.value = xml;
}
  
/******************************
Función para generar el XML del
envio con ficheros adjuntos
******************************/
function generaXMLFicheros(pObjFormulario, tipo) {
	var cont = '<'+'?xml version="1.0" encoding="ISO-8859-1"?>\n'
	cont += '<'+'XML>\n';
	cont += '<'+'TIPO_FICHEROS>PI00028'+'</'+'TIPO_FICHEROS>';
	
	for (var i = 0; i < document.formulario.length; i++) {
		if (document.forms[0].elements[i].type == 'file') {
			cont += '<'+'FICHERO>';
			cont += '<'+'CAMPO>';
			cont += document.forms[0].elements[i].name;
			cont += '</'+'CAMPO>';
			cont += '<'+'RUTA>';
			try {
				netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
			} catch (e) {
			}
			cont += document.forms[0].elements[i].value;
			cont += '</'+'RUTA>';
			cont += '</'+'FICHERO>';
		}
	}
	cont += '</'+'XML>';
	if (tipo == "V") {
		document.forms[2].XMLFicheros.value = cont;
	} else {
		document.forms[1].XMLFicheros.value = cont;
	}
  document.getElementById('XMLFicheros').value = cont;

  return cont;
}

/*****************************
Regenerar la trama
******************************/
function regenerar()
{
  document.getElementById('accionOculta').value = 'regenerar';
  document.formulario.submit();
}

/***************************
Función para llamar al enviar
normal(Sin Ficheros adjuntos)
****************************/
function validaCampos(pObjFormulario, tipo)
{
  if(validaCamposForm(pObjFormulario, tipo))
  {
    pObjFormulario.submit();
    return true;
  }
  else
  {
    return false;
  }  
}

/***************************
Función para llamar al enviar
con Ficheros adjuntos
****************************/
function validaCamposFicheros(pObjFormulario, tipo)
{
  if(validaCamposForm(pObjFormulario, tipo))
  {
    generaXMLFicheros(pObjFormulario, tipo);      
    carga_contenido_ficheros();
    //pObjFormulario.submit();
    return true;
  }
  else
  {
    return false;
  }  
}

/***************************
Función para llamar al enviar
con Firma adjuntos
****************************/
function validaCamposFirma(pObjFormulario, tipo)
{
  if(validaCamposForm(pObjFormulario, tipo))
  {
    generaXMLFicheros(pObjFormulario, tipo);      
    carga_contenido_ficheros();
    //pObjFormulario.submit();
    return true;
  }
  else
  {
    return false;
  }  
}

/***************************
Función para seleccionar las
funciones para enviar según
el tipo de firma.
****************************/
function seleccionarEnvioFirma()
{
  if (document.getElementById('tarjeta').checked)
    maneja_envios_ficheros(document.form_datos_cauce,document.form_pkcs,document.formEnvio);
  if (document.getElementById('fichero').checked)
    maneja_envios_ficheros(document.form_datos_cauce,document.form_pkcs,document.formEnvio);
  if (document.getElementById('navegador').checked)
    enviarCapicom(document.formEnvio);
}

/***************************
Función para validar que el
contenido de la trama sea el
mismo que la imágen. Hace submit
con la acción espeaciál para 
validar en código java
****************************/
function validaTrama(pObjFormulario, tipo)
{
  if(validaCamposForm(pObjFormulario, tipo))
  {
    //guardamos todo el XMl de datos
    pObjFormulario.xml_aux.value = generaXMLEnvio(pObjFormulario, tipo);
    //ponemos la acción correcta para que haga el submit
    document.getElementById('accionOculta').value = 'validar';
    document.formulario.submit();
    return true;
  }
  else
  {
    return false;
  }  
}

/***************************
Función para llamar al enviar
validando con TRAMA y con 
ficheros o firma
****************************/
function validaTramaFicherosFirma(pObjFormulario, tipo)
{
  if(validaCamposForm(pObjFormulario, tipo))
  {
    //guardamos todo el XMl de datos
    pObjFormulario.xml_aux.value = generaXMLEnvio(pObjFormulario, tipo);
    pObjFormulario.xml_ficheros_aux.value = generaXMLFicheros(pObjFormulario, tipo);
    //ponemos la acción correcta para que haga el submit
    document.getElementById('accionOculta').value = 'validar';  
    pObjFormulario.submit();
    return true;
  }
  else
  {
    return false;
  }  
}

/**********************************
Funciones para hacer submit cuando
tenga TRAMA(Llamar a enviar)
Dependen de si teine ficheros o firma
***********************************/
/**Normal**/
function submitEnvio(pObjFormulario, tipo) {
  if (tipo == "V") {  
    document.forms[2].xmlv.value = pObjFormulario.xml_aux.value; 
  } else {
    document.forms[1].xml.value = pObjFormulario.xml_aux.value; 
  }
  document.formEnvio.submit();
}
/**Ficheros**/
function submitEnvioFicheros(pObjFormulario, tipo) {
  if (tipo == "V") {
    document.forms[2].xmlv.value = pObjFormulario.xml_aux.value;
  } else {
    document.forms[1].xml.value = pObjFormulario.xml_aux.value;
    document.forms[1].XMLFicheros.value = pObjFormulario.xml_ficheros_aux.value;
  }
  
  carga_contenido_ficheros();
  document.formEnvio.submit();  
}
/**Firma**/
function submitEnvioFirma(pObjFormulario, tipo) {
  if (tipo == "V") {
    document.forms[2].xmlv.value = pObjFormulario.xml_aux.value;
  } else {
    document.forms[1].xml.value = pObjFormulario.xml_aux.value;
    document.forms[1].XMLFicheros.value = pObjFormulario.xml_ficheros_aux.value;
  }
  
  carga_contenido_ficheros();
  javascript:maneja_envios_ficheros(document.form_datos_cauce,document.form_pkcs,document.formEnvio);
}
/**Ficheros y Firma**/
function submitEnvioFicherosFirma(pObjFormulario, tipo) {
  
  if (tipo == "V") {
    document.formValidacion.xmlv.value = pObjFormulario.xml_aux;
  } else {
    document.formEnvio.xml.value = pObjFormulario.xml_aux;
    document.formEnvio.XMLFicheros.value = pObjFormulario.xml_ficheros_aux;
  }
  
  carga_contenido_ficheros();
  javascript:maneja_envios_ficheros(document.form_datos_cauce,document.form_pkcs,document.formEnvio);
}

/**********************************
Función de utilidad para ocultar el
div para fiormar con capicom si el
navegador no es IE
**********************************/
  function muestraTarjeta()
  {
    if (isIE()) 
    {
      document.getElementById('labelNavegador').style.display = 'block';
      document.getElementById('navegador').checked = true;
      document.getElementById('tarjeta').checked = false;
    }
    else 
    {      
      document.getElementById('navegador').checked = false;
      document.getElementById('tarjeta').checked = true;
    }
  }



function cargarXMLAvanceAVAPCSJ(ficheroXML, idform){
  if(ficheroXML!='')
  {
    var xmlDoc = null;
    if (is_ie){
      try{
        xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async="false";
        xmlDoc.loadXML(ficheroXML);			
      } catch (e){ alert("Se produjo un error al crear un objeto para leer xml. \nError: " + e.message); return;  }
    }
    else{			
      try{
        parser=new DOMParser();
          xmlDoc=parser.parseFromString(ficheroXML,"text/xml");
      } catch (e){ alert("Se produjo un error al crear un objeto para leer xml. \nError: " + e.message); return;  }
    }
    
    var elementoXML;
    var elementoXMLaux;
    var elementosMismoId;
    var itemsListaDinamica;
    var k=0;
    var nombreBase="";
    var nombreBase2="";
    var htmlExtra="";
    var todosElementos=document.formulario.elements;
    var valido=false;
    
    try{
      elementoXML = xmlDoc.getElementsByTagName('XML');
      if(elementoXML[0].childNodes.length>1)
      {
        if(elementoXML[0].childNodes[0].nodeName!=null && elementoXML[0].childNodes[0].childNodes[0].nodeValue!=null)
        {
          if(elementoXML[0].childNodes[0].nodeName=='IDFORM' && elementoXML[0].childNodes[0].childNodes[0].nodeValue==idform)
            valido=true;
        }
      }
      if(valido)  
      {
        for( i = 1; i < elementoXML[0].childNodes.length; i++){
          if(elementoXML[0].childNodes[i].nodeName!=null)
          {          
            nombreBase=elementoXML[0].childNodes[i].nodeName;
            if(document.getElementById(nombreBase)!=null)
            {
              //if(elementoXML[0].childNodes[i].childNodes[0].nodeValue!=null)
              //{
                if(document.getElementById(nombreBase).type=='checkbox')
                {
                  if(elementoXML[0].childNodes[i].childNodes[0]==null)
                  {
                    document.getElementById(nombreBase+'_h').value='S';                                  
                    javascript:checkea(nombreBase,nombreBase+'_h');
                  }
                  else
                  {
                    if(elementoXML[0].childNodes[i].childNodes[0].nodeValue=='' || elementoXML[0].childNodes[i].childNodes[0].nodeValue=='Si')
                    {
                      document.getElementById(nombreBase+'_h').value='S';                                  
                      javascript:checkea(nombreBase,nombreBase+'_h');
                    }
                    else
                    {
                      document.getElementById(nombreBase+'_h').value='N';                                  
                      javascript:checkea(nombreBase,nombreBase+'_h');
                    }
                  }
                }
                else              
                {
                  if(document.getElementById(nombreBase).type=='radio')
                  {
                    if(elementoXML[0].childNodes[i].childNodes[0]!=null)
                    {
                      for(j=0; j<todosElementos.length; j++)
                      {
                        if(todosElementos[j].name==nombreBase && todosElementos[j].type=='radio')
                        {
                          if(todosElementos[j].value==elementoXML[0].childNodes[i].childNodes[0].nodeValue)
                          {
                            todosElementos[j].checked='checked';
                          }
                        }
                      }
                    }
                    else
                    {
                      for(j=0; j<todosElementos.length; j++)
                      {
                        if(todosElementos[j].name==nombreBase && todosElementos[j].type=='radio')
                        {
                          if(todosElementos[j].value==elementoXML[0].childNodes[i].childNodes[0])
                          {
                            todosElementos[j].checked='';
                          }
                        }
                      }
                    }
                  }
                  else
                  {
                    if(elementoXML[0].childNodes[i].childNodes[0]!=null)
                    {
                      document.getElementById(nombreBase).value=elementoXML[0].childNodes[i].childNodes[0].nodeValue;
                    }
                    else
                    {
                      document.getElementById(nombreBase).value='';
                    }
                  }
                }
              //}
              //else
                //document.getElementById(nombreBase).value='';
            }
            else
            {                    
              if(document.getElementById(nombreBase+'Clave')!=null)
              {
                if(elementoXML[0].childNodes[i].childNodes[0]!=null)
                {
                  document.getElementById(nombreBase+'Clave').value=elementoXML[0].childNodes[i].childNodes[0].nodeValue;  
                 
                  if(document.getElementById(nombreBase+'Secarga')!=null)
                    document.getElementById(nombreBase+'Secarga').value='SI';
                  if(document.getElementById(nombreBase+'pulsado'))
                    document.getElementById(nombreBase+'pulsado').value='SI';
                }
              }  
              else
              {
                if(document.getElementById('MuLtI0_'+nombreBase)!=null)
                {
                  elementoXMLaux=elementoXML[0].childNodes[i].getElementsByTagName('SELECCION');
                  k=0;
                  do{
                    document.getElementById('MuLtI'+k+'_'+nombreBase).checked='';
                    k++;
                  }while(document.getElementById('MuLtI'+k+'_'+nombreBase)!=null);
                  
                  k=0;              
                  do{
                    for( j = 0; j < elementoXMLaux.length; j++)
                    {
                      if(elementoXMLaux[j].childNodes[0]!=null)
                      {
                        if(document.getElementById('MuLtI'+k+'_'+nombreBase).value==elementoXMLaux[j].childNodes[0].nodeValue)                
                          document.getElementById('MuLtI'+k+'_'+nombreBase).checked='checked';
                      }
                    }
                    k++;
                  }while(document.getElementById('MuLtI'+k+'_'+nombreBase)!=null);
                }
                else
                {        
                  itemsListaDinamica=elementoXML[0].childNodes[i].getElementsByTagName('ITEM_'+nombreBase);                
                  if(itemsListaDinamica.length>0)
                  {
                    document.getElementById('LiStA_'+nombreBase+'filas').value=itemsListaDinamica.length;
                    
                    var field;
                    for(j=0; j<itemsListaDinamica.length; j++)                  
                    {
                      for(k=0; k<itemsListaDinamica[j].childNodes.length; k++)
                      {
                        nombreBase2=itemsListaDinamica[j].childNodes[k].nodeName;
                        field = document.createElement('LiStA_'+nombreBase+'_'+nombreBase2+'_'+(j+1));
                        
                        field.innerHTML = '<input '+'type="HIDDEN" id="LiStA_'+nombreBase+'_'+nombreBase2+'_'+(j+1)+'"'
                        + ' name="LiStA_'+nombreBase+'_'+nombreBase2+'_'+(j+1)+'"'
                        + ' value = "'+itemsListaDinamica[j].childNodes[k].childNodes[0].nodeValue+'" '+'/>';
                                              
                        document.formulario.appendChild(field);
                      }
                    }              
                  }
                  else
                  {
                    if(document.getElementById('ldap'+nombreBase+'Clave')!=null)
                    {
                      if(elementoXML[0].childNodes[i].childNodes[0]!=null)
                      {
                        document.getElementById('ldap'+nombreBase+'Clave').value=elementoXML[0].childNodes[i].childNodes[0].nodeValue;  
                        if(document.getElementById(nombreBase+'Clave')!=null)
                        {
                          document.getElementById(nombreBase+'Clave').value=elementoXML[0].childNodes[i+1].childNodes[0].nodeValue;  
                          i++;
                        }                       
                        if(document.getElementById(nombreBase+'Secarga')!=null)
                          document.getElementById(nombreBase+'Secarga').value='SI';
                        if(document.getElementById(nombreBase+'pulsado'))
                          document.getElementById(nombreBase+'pulsado').value='SI';
                      }
                    } 
                  }
                }
              }
            }                     
          }
        }
        document.formulario.submit();   
        return true;
      }
      else
      {
        var mensaje = "El fichero seleccionado no tiene un formato correcto para";
        mensaje += "\nrecuperar los datos de la solicitud";
        alert(mensaje); 
      
        document.formulario.submit(); 
        return null;
      }
    }catch (e) { 
      var mensaje = "Se ha producido un error procesando el fichero. No se continua con la carga.";
      mensaje += "\nEs posible que el fichero no tenga un formato correcto";
      alert(mensaje + "\nError: " + e.message); 
      //document.formulario.submit(); 
      return null;
    }
  }
  return null;
}

function generaXMLEnvioAVAPCSJ(pObjFormulario, tipo) {  
  var muestra = '';
	var aux='';
	var l;
	var anterior = "";
	var titAnterior = "";
	var radio = "N";
	var chequeado = "N";
	var obligatorio = "N";
	var noml = '';
	var gnoml = '';
	var iteml = '';
	var gniteml = '';
	var niteml = '';
	var gnom_m = ''; 
  
  var valido=false;

	var cont = '<?xml version="1.0" encoding="ISO-8859-1"?>\n'
	cont += '<XML>\n';
	for (var i = 0; i < document.formulario.length; i++) {
    valido=true;
    if(document.forms[0].elements[i].name != 'trama')
    {
			if (document.forms[0].elements[i].type != 'button') {
				if (document.forms[0].elements[i].type != 'hidden') {
        if (document.forms[0].elements[i].name.substring(0,4) == 'ldap') {    
          if(document.forms[0].elements[i].name.length>=21)
          {
            if(document.forms[0].elements[i].name.substring(19,document.forms[0].elements[i].name.length)=='Clave')
            {
              valido=true;
            }
            else
            {
              valido=false;
            }
          }
          else
          {
            valido=false;
          }
        }           
        else
        {
          valido=true;
        }
        if(valido)
        {          
					if (!(document.forms[0].elements[i].type == 'radio' && document.forms[0].elements[i].checked != true)) {
						if (document.forms[0].elements[i].type == 'checkbox') {
							if(gnoml!='')
							{
								cont += '</'+'ITEM_' + gnoml + '>'; 
								cont += '</' + gnoml + '>'; 
								gnoml='';
								gniteml='';
							}
							if(document.forms[0].elements[i].name.substr(0,5)=='MuLtI')
							{
								if(gnom_m!='')
								{
									if(document.forms[0].elements[i].name.substr(document.forms[0].elements[i].name.indexOf("_",0)+1,15)!=gnom_m)
									{
										cont += '</' + gnom_m + '>'; 
										gnom_m='';
									}
								}
								if (document.forms[0].elements[i].checked == true)
								{
									if(gnom_m=='')
									{
										gnom_m=document.forms[0].elements[i].name.substr(document.forms[0].elements[i].name.indexOf("_",0)+1,15);
										cont += '<'+gnom_m + '>'; 
									}
									else
									{
										if(document.forms[0].elements[i].name.substr(document.forms[0].elements[i].name.indexOf("_",0)+1,15)!=gnom_m)
										{
											cont += '</' + gnom_m + '>'; 
											gnom_m=document.forms[0].elements[i].name.substr(document.forms[0].elements[i].name.indexOf("_",0)+1,15);
											cont += '<'+gnom_m + '>';
										}
									}
									cont += '<SELECCION>' + trim(document.forms[0].elements[i].value.replace('&', '&amp;').replace('<', '&lt;')) + '</'+'SELECCION>';
								}
							} else { 
								if(gnom_m!='')
								{
									cont += '</' + gnom_m + '>'; 
									gnom_m='';
								}
								if (document.forms[0].elements[i].checked == true) {
									cont += '<' + document.forms[0].elements[i].name + '>Si</' + document.forms[0].elements[i].name + '>\n';
								} else {
									cont += '<' + document.forms[0].elements[i].name + '>No</' + document.forms[0].elements[i].name + '>\n';
								}
							}
						} else {
							if(gnom_m!='')
							{
								cont += '</' + gnom_m + '>';
								gnom_m='';
							}
							if(document.forms[0].elements[i].name.substring(0,6)=="LiStA_"){
								if(document.forms[0].elements[i].name.indexOf("_",0)!=document.forms[0].elements[i].name.lastIndexOf("_"))
								{
									aux=document.forms[0].elements[i].name.substring(6,document.forms[0].elements[i].name.length);
									noml=aux.substring(0,(aux.indexOf("_",0)));
									aux=aux.substring(aux.indexOf("_",0)+1,aux.length);
									iteml=aux.substring(0,aux.indexOf("_",0));
									aux=aux.substring(aux.indexOf("_",0)+1,aux.length);
									niteml=aux.substring(0,aux.length);
									if(gnoml!=noml){
										if(gnoml!='')
										{
											cont += '</'+'ITEM_' + gnoml + '>';
											cont += '</' + gnoml + '>';
										}
										cont += '<' + noml + '>';
										cont += '<ITEM_' + noml + '>';
										cont += '<' + iteml + '>' + trim(document.forms[0].elements[i].value.replace('&', '&amp;').replace('<', '&lt;')) + '</' + iteml + '>';
										gnoml=noml;
										gniteml=niteml;
									} else {
										if(gniteml!=niteml)
										{
											if(gniteml!='')
												cont += '</'+'ITEM_' + noml + '>';
											cont += '<ITEM_' + noml + '>';
											cont += '<' + iteml + '>' + trim(document.forms[0].elements[i].value.replace('&', '&amp;').replace('<', '&lt;')) + '</' + iteml + '>';  
											gniteml=niteml;
										} else {
											cont += '<' + iteml + '>' + trim(document.forms[0].elements[i].value.replace('&', '&amp;').replace('<', '&lt;')) + '</' + iteml + '>';                  
										}
									}
								}
							} else { 
								if(gnoml!='')
								{
									cont += '</'+'ITEM_' + gnoml + '>'; 
									cont += '</' + gnoml + '>'; 
									gnoml='';
									gniteml='';
								}
								if(muestra=='' | (muestra.length>document.forms[0].elements[i].name.length | muestra!=document.forms[0].elements[i].name.substring(0,muestra.length))){
									if (trim(document.forms[0].elements[i].value) == ""){
										if (document.forms[0].elements[i].lang == "S") {
											l=document.forms[0].elements[i].name.length;
											if(l>5){
												aux=document.forms[0].elements[i].name.substring(l-5,l);
												if(aux=='Clave'){
                          if(document.forms[0].elements[i].name.substring(0,4)!='ldap')
                          {
                            muestra=document.forms[0].elements[i].name.substring(0,l-5);
                            cont += '<' + muestra + '>' + trim(document.forms[0].elements[i].value.replace('&', '&amp;').replace('<', '&lt;')) + '</' + muestra + '>';
                          } else{
                            muestra='';
                            cont += '<' + document.forms[0].elements[i].name + '>' + trim(document.forms[0].elements[i].value.replace('&', '&amp;').replace('<', '&lt;')) + '</' + document.forms[0].elements[i].name + '>';  
                          }                          
												} else{
													muestra='';
													cont += '<' + document.forms[0].elements[i].name + '>' + trim(document.forms[0].elements[i].value.replace('&', '&amp;').replace('<', '&lt;')) + '</' + document.forms[0].elements[i].name + '>';  
												}
											} else {
												muestra='';
												cont += '<' + document.forms[0].elements[i].name + '>' + trim(document.forms[0].elements[i].value.replace('&', '&amp;').replace('<', '&lt;')) + '</' + document.forms[0].elements[i].name + '>';
											}
										}
									} else {
										l=document.forms[0].elements[i].name.length;
										if(l>5){
											aux=document.forms[0].elements[i].name.substring(l-5,l);
											if(aux=='Clave'){
												if(document.forms[0].elements[i].name.substring(0,4)!='ldap')
                        {
                          muestra=document.forms[0].elements[i].name.substring(0,l-5);
                          cont += '<' + muestra + '>' + trim(document.forms[0].elements[i].value.replace('&', '&amp;').replace('<', '&lt;')) + '</' + muestra + '>';
                        } else{
                          muestra='';
                          cont += '<' + document.forms[0].elements[i].name + '>' + trim(document.forms[0].elements[i].value.replace('&', '&amp;').replace('<', '&lt;')) + '</' + document.forms[0].elements[i].name + '>';  
                        }  
											} else{
												muestra='';
												cont += '<' + document.forms[0].elements[i].name + '>' + trim(document.forms[0].elements[i].value.replace('&', '&amp;').replace('<', '&lt;')) + '</' + document.forms[0].elements[i].name + '>';
											}
										} else{
											muestra='';
											cont += '<' + document.forms[0].elements[i].name + '>' + trim(document.forms[0].elements[i].value.replace('&', '&amp;').replace('<', '&lt;')) + '</' + document.forms[0].elements[i].name + '>';
										}
									}
								}
							}
						}
					}
        }        
				else
				{
					if(document.forms[0].elements[i].name.substring(0,8)=="InTeRnO_"){
						if(gnom_m!='')
						{
							cont += '</' + gnom_m + '>';
							gnom_m='';
						}
						if(gnoml!='')
						{
							cont += '</'+'ITEM_' + gnoml + '>'; 
							cont += '</' + gnoml + '>'; 
							gnoml='';
							gniteml='';
						}
						noml=document.forms[0].elements[i].name.substring(8,document.forms[0].elements[i].name.length);
						muestra='';
						cont += '<INTERNO_' + noml + '>' + trim(document.forms[0].elements[i].value.replace('&', '&amp;').replace('<', '&lt;')) + '</'+'INTERNO_' + noml + '>';
					}
				}
        }
			}
		}
	}
	if(gnoml!='')
	{
		cont += '</'+'ITEM_' + gnoml + '>'; 
		cont += '</' + gnoml + '>'; 
		gnoml='';
		gniteml='';
	}
	if(gnom_m!='')
	{
		cont += '</' + gnom_m + '>'; 
		gnom_m='';
	}
	cont = cont + '</' + 'XML>';
	if (tipo == "V") {
		document.forms[2].xmlv.value = cont;
	} else {
		document.forms[1].xml.value = cont;
	}

	return cont;
}

function generaXMLAvanceAVAPCSJ(pObjFormulario, tipo, idform)
{
  var xml='';
  var datosXML=generaXMLEnvioAVAPCSJ(pObjFormulario, tipo) ;
  
  xml=datosXML.substr(0,datosXML.indexOf("<XML>",0)+5);
  xml +='<'+'IDFORM>'+idform+'</'+'IDFORM>';
  xml +=datosXML.substr(datosXML.indexOf("<XML>",0)+5,datosXML.length);  
  
  return xml;
}



/****************************************************
Funcion que averigua si el navegador es un IE

return true si el navegador es InternetExplorer
			 false si el navegador no es InternetExplorer 

FGI
*****************************************************/
function isIE() { return document.all ? true:false; }
	
/****************************************************
Funcion que averigua si el navegador es un NS

return true si el navegador es Netscape 
			 false si el navegador no es Netscape 

FGI
*****************************************************/
function isNS() { return document.layers ? true:false }


/****************************************
Funcion que solo permite la introduccion
de numeros decimales siendo el separador
el "."
*****************************************/

function onlyDigits3(e,id) {
  
  var _ret = true;
  if (id==null)
    {
      alert('El id no puede ser nulo');      
      return _ret;
    }
  if (e==null)
    {    
      alert('El evento de teclado no puede ser nulo');
      return _ret;
    }
    
  var tecla;
  
  if (isIE())
  {    
    tecla = e.keyCode;
  }
  else
  {
    if(isNS())    
    {      
      tecla = e.which;
    }
    else
    {      
      tecla = e.which;
    }
  }   
    
  if (tecla == 44) 
  {
    var completo = document.getElementById(id).value;
    if (completo.indexOf(',')!=-1)
    {
      anular_tecla(e)
      _ret = false;
    }
    else
    {            
      return true;
    }
  }
  if (tecla < 48 || tecla > 57 ) 
  {                   
    anular_tecla(e);
     _ret = false;          
  }  
  return (_ret);    	
    
}

/**
	Cambia el icono actual por una mano
**/
function ponerMano(obj){
	obj.style.cursor = 'hand';
}

function aumentarFontSize(frame) {
   var p = frame.document.getElementsByTagName('*');
   for(i=0;i<p.length;i++) {
      if(p[i].style.fontSize) {
         var s = parseInt(p[i].style.fontSize.replace("px",""));
      } else {
         var s = 12;
      }
      s += 1;
      p[i].style.fontSize = s+"px"
   }
}
function disminuirFontSize(frame) {
   var p = frame.document.getElementsByTagName('*');
   for(i=0;i<p.length;i++) {
      if(p[i].style.fontSize) {
         var s = parseInt(p[i].style.fontSize.replace("px",""));
      } else {
         var s = 12;
      }
      s -= 1;
      p[i].style.fontSize = s+"px"
   }   
}

//APELLIDOS,NOMBRE, NIF, IMPORTE, CENTRO, TPV, COD_RESULTADO, DESC_RESULTADO, IDIOMA, FECHA_RESULTADO, OP_RESULTADO
function realizarPagoTelematico(apellidosId,nombreId, nifId, importeId, centroId, tpvId, codResultadoId, descResultadoId, idiomaId, fechaResultadoId, opResultadoId, objForm){ 
	var importe = document.getElementById(importeId).value.trim();	
	var cif 	= document.getElementById(nifId).value.trim();	
	var nombre 	= document.getElementById(nombreId).value.trim();	
	var apellidos= document.getElementById(apellidosId).value.trim();	
	var cmd 	= '0008';	
	var centro 	= document.getElementById(centroId).value.trim();	
	var tpv 	= document.getElementById(tpvId).value.trim();
	var desc 	= document.getElementById("PAGO_DESCRIPCION").value.trim();
	var info 	= document.getElementById("PAGO_INFORMACION").value.trim();
	var errores = '';
	var idioma  = '';
	
	if ( cmd == ''){
		errores = "Falta el c\u00F3digo de operaci\u00F3n. Contacte con el administrador";	
	}
	if ( centro == ''){
		errores += "\nFalta el c\u00F3digo del centro. Contacte con el administrador";	
	} 
	if ( tpv == ''){
		errores += "\nFalta el c\u00F3digo del tpv. Contacte con el administrador";	
	} 
	if ( importe == ''){
		errores += "\nFalta el importe.";	
	} 
	if ( cif == ''){
		errores += "\nFalta el CIF del usuario.";	
	} 
	if ( nombre == ''){
		errores += "\nFalta el nombre del usuario.";	
	} 
	if ( apellidos == ''){
		errores += "\nFaltan los apellidos del usuario.";	
	} 
	if ( desc == ''){
		errores += "\nFalta la descripci\u00f3n. Contacte con el administrador";
	}
	
	if ( errores != ''){
		alert(errores);
		return null;
	}
	
	//la aplicacion de pagos espera que el importe no tenga punto de decimales
	//1 euro 	=> 100
	//1,50		=> 150
	var indice = importe.indexOf('.');
	if (indice < 0) importe = importe + "00";
	else{
		alert(importe.substring(indice+1, importe.length));
		if ( importe.substring(indice+1, importe.length).length == 1){
			importe = importe + "0";	
		}
		else if ( importe.substring(indice+1, importe.length).length > 2){
			alert("El importe s\u00F3lo puede tener dos decimales " );
			document.getElementById(importeId).focus();	
			return null;
		}
		importe = importe.replace(".", "");
	}
	if (importe.length > 10){
		alert("El importe es demasiado grande para la aplicación de pagos");
		document.getElementById(importeId).focus();	
		return null;
	}	
	//comprobamos que el importe sea numerico.
	importe = parseInt(importe);
	if (isNaN(importe)){
		alert("Se ha producido un error al convertir el importe a un num\u00E9rico, compruebe el valor del mismo");
		document.getElementById(importeId).focus();	
		return null;
	}
	
	var idiomaTodos = document.getElementsByName(idiomaId);
	for (i = 0; i < idiomaTodos.length; i++){
		if (idiomaTodos[i].checked){
			if (idiomaTodos[i].id == idiomaId + "_CASTELLANO"){
				idioma = 'C';	
			}
			else if (idiomaTodos[i].id == idiomaId + "_VALENCIANO"){
				idioma = 'V';
			}
		}
	}
	
	if (idioma == ''){
		alert("Se debe seleccionar un idioma");		
		return null;
	}
	
	document.getElementById('PAGO00000000000_Ant').value = apellidos;
	document.getElementById('PAGO00000000001_Ant').value = nombre;
	document.getElementById('PAGO00000000002_Ant').value = cif;
	document.getElementById('PAGO00000000002_Ant').value = importe;
	
	var nomForm = objForm.name;
	document.getElementById(nomForm).action = 'https://webges3.uv.es/uvPagoWeb/ExtPago?';	
	document.getElementById(nomForm + "_CMD").value = cmd;
	document.getElementById(nomForm + "_CENTRO").value = centro;
	document.getElementById(nomForm + "_TPV").value = tpv;
	document.getElementById(nomForm + "_NOMBRE").value = nombre;
	document.getElementById(nomForm + "_APELLIDOS").value = apellidos;
	document.getElementById(nomForm + "_IMPORTE").value = importe;
	document.getElementById(nomForm + "_IDIOMA").value = idioma;
	document.getElementById(nomForm + "_DESCRIPCION").value = desc;
	document.getElementById(nomForm + "_INFORMACION").value = info;
	document.getElementById(nomForm + "_NIF").value = cif;
	document.getElementById("TPV_FORMULARIO").value = 'formulario';
	document.getElementById("TPV_IDOPERACION").value = opResultadoId;
	document.getElementById("TPV_FECHAOPERACION").value = fechaResultadoId;
	document.getElementById("TPV_CODRESPUESTA").value = codResultadoId;
	document.getElementById("TPV_DESCRESPUESTA").value = descResultadoId;
	document.getElementById(nomForm).target="WPRINCIPAL";
	
	ventana = window.open("","WPRINCIPAL","");
	document.getElementById(nomForm).submit();

}

function validaCamposR(pObjFormulario, tipo) {
  var muestra = '';
  var aux='';
  var l;
  var anterior = "";
  var titAnterior = "";
  var radio = "N";
  var chequeado = "N";
  var obligatorio = "N";
  var noml = '';
  var gnoml = '';
  var iteml = '';
  var gniteml = '';
  var niteml = '';
  for (var i = 0; i < document.formulario.length; i++) {
    if((document.forms[0].elements[i].name!='') && (document.forms[0].elements[i].name.substring(0,2)!='VI') && (document.forms[0].elements[i].name.substring(0,1)!='V')){
    if (document.forms[0].elements[i].type != 'button') {
      if (document.forms[0].elements[i].type != 'radio') {
        if (radio == "S") {
          if (obligatorio == "S") {
            if (chequeado == "N") {
              alert("El campo " + titAnterior + " es obligatorio")
              return false;
            }
          }
        }
        radio = "N";
        chequeado = "N";
        obligatorio = "N";
        if((document.forms[0].elements[i].name.substring(0,6)=="LiStA_") & (document.forms[0].elements[i].name.indexOf("_",0)==document.forms[0].elements[i].name.lastIndexOf("_")))
        {
           if(document.forms[0].elements[i].lang == "S" && document.forms[0].elements[i].value=='0')
           {
             alert("La lista " + document.forms[0].elements[i].title + " es obligatoria");
             return false;
           }
         }
         else{  
           if (trim(document.forms[0].elements[i].value).length < 1) {
             if (document.forms[0].elements[i].lang == "S") {
               alert("El campo " + document.forms[0].elements[i].title + " es obligatorio");
               return false;
             }
           }
         }
         anterior = document.forms[0].elements[i].name;
         titAnterior = document.forms[0].elements[i].title;
      } else {
        if (radio == "S") {
          if (anterior == document.forms[0].elements[i].name) {
            if (document.forms[0].elements[i].lang == "S") {
              obligatorio = "S";
              if (!document.forms[0].elements[i-1].checked) {
                if (document.forms[0].elements[i].checked) {
                  chequeado = "S";
                }
              } else {
                chequeado = "S";
              }
            } else {
              obligatorio = "N";
            }
          } else {
            if (obligatorio == "S") {
              if (chequeado == "N") {
                alert("El campo " + titAnterior + " es obligatorio");
                return false;
              }
            }
            if (document.forms[0].elements[i].lang == "S") {
              obligatorio = "S";
              if (document.forms[0].elements[i].checked) {
                chequeado = "S";
              }
            } else {
              obligatorio = "N";
            }
          }
        } else {
          if (document.forms[0].elements[i].lang == "S") {
            obligatorio = "S";
            if (document.forms[0].elements[i].checked) {
              chequeado = "S";
            }
          } else {
            obligatorio = "N";
          }
        }
        radio = "S";
        anterior = document.forms[0].elements[i].name;
        titAnterior = document.forms[0].elements[i].title;
      }
    }
    }
  }
  var cont = '<?xml version="1.0" encoding="ISO-8859-1"?>\n'
  cont += '<XML>\n';
  for (var i = 0; i < document.formulario.length; i++) {
    if((document.forms[0].elements[i].name!='') && (document.forms[0].elements[i].name.substring(0,2)!='VI') && (document.forms[0].elements[i].name.substring(0,1)!='V')){
    if (document.forms[0].elements[i].type != 'button') {
      if (!(document.forms[0].elements[i].type == 'radio' && document.forms[0].elements[i].checked != true)) {
        if (document.forms[0].elements[i].type == 'checkbox') {
          if(gnoml!='')
          {
            cont += '</'+'ITEM_' + gnoml + '>'; 
            cont += '</' + gnoml + '>'; 
            gnoml='';
            gniteml='';
          }
          if (document.forms[0].elements[i].checked == true) {
            cont += '<' + document.forms[0].elements[i].name + '>Si</' + document.forms[0].elements[i].name + '>\n';
          } else {
            cont += '<' + document.forms[0].elements[i].name + '>No</' + document.forms[0].elements[i].name + '>\n';
          }
        } else {
          if(document.forms[0].elements[i].name.substring(0,6)=="LiStA_"){
            if(document.forms[0].elements[i].name.indexOf("_",0)!=document.forms[0].elements[i].name.lastIndexOf("_"))
            {
              aux=document.forms[0].elements[i].name.substring(6,document.forms[0].elements[i].name.length);
              noml=aux.substring(0,(aux.indexOf("_",0)));
              aux=aux.substring(aux.indexOf("_",0)+1,aux.length);
              iteml=aux.substring(0,aux.indexOf("_",0));
              aux=aux.substring(aux.indexOf("_",0)+1,aux.length);
              niteml=aux.substring(0,aux.length);
              if(gnoml!=noml){
                if(gnoml!='')
                {
                  cont += '</'+'ITEM_' + gnoml + '>';
                  cont += '</' + gnoml + '>';
                }
                cont += '<' + noml + '>';
                cont += '<ITEM_' + noml + '>';
                cont += '<' + iteml + '>' + trim(document.forms[0].elements[i].value.replace('&', '&amp;').replace('<', '&lt;')) + '</' + iteml + '>';
                gnoml=noml;
                gniteml=niteml;
              }
              else
              {
                if(gniteml!=niteml)
                {
                  if(gniteml!='')
                    cont += '</'+'ITEM_' + noml + '>';
                  cont += '<ITEM_' + noml + '>';
                  cont += '<' + iteml + '>' + trim(document.forms[0].elements[i].value.replace('&', '&amp;').replace('<', '&lt;')) + '</' + iteml + '>';  
                  gniteml=niteml;
                }
                else
                  cont += '<' + iteml + '>' + trim(document.forms[0].elements[i].value.replace('&', '&amp;').replace('<', '&lt;')) + '</' + iteml + '>';                  
              }
            }
          }
          else{
            if(gnoml!='')
            {
              cont += '</'+'ITEM_' + gnoml + '>'; 
              cont += '</' + gnoml + '>'; 
              gnoml='';
              gniteml='';
            }
            if(muestra=='' | (muestra.length>document.forms[0].elements[i].name.length | muestra!=document.forms[0].elements[i].name.substring(0,muestra.length))){
              if (trim(document.forms[0].elements[i].value) == ""){
                if (document.forms[0].elements[i].lang == "S") {
                  l=document.forms[0].elements[i].name.length;
                  if(l>5){
                    aux=document.forms[0].elements[i].name.substring(l-5,l);
                    if(aux=='Clave'){
                      muestra=document.forms[0].elements[i].name.substring(0,l-5);
                      cont += '<' + muestra + '>' + trim(document.forms[0].elements[i].value.replace('&', '&amp;').replace('<', '&lt;')) + '</' + muestra + '>';
                    }
                    else{
                      muestra='';
                      cont += '<' + document.forms[0].elements[i].name + '>' + trim(document.forms[0].elements[i].value.replace('&', '&amp;').replace('<', '&lt;')) + '</' + document.forms[0].elements[i].name + '>';  
                    }
                  }
                else{
                  muestra='';
                  cont += '<' + document.forms[0].elements[i].name + '>' + trim(document.forms[0].elements[i].value.replace('&', '&amp;').replace('<', '&lt;')) + '</' + document.forms[0].elements[i].name + '>';
                }
              }
              else // no obligatorio
              {
                if (document.forms[0].elements[i].type == 'textarea') // Si es de tipo textarea
                {
                  cont += '<' + document.forms[0].elements[i].name + '>' + trim(document.forms[0].elements[i].value.replace('&', '&amp;').replace('<', '&lt;')) + '</' + document.forms[0].elements[i].name + '>';
                }
              }
            }
            else {
              l=document.forms[0].elements[i].name.length;
                if(l>5){
                  aux=document.forms[0].elements[i].name.substring(l-5,l);
                  if(aux=='Clave'){
                    muestra=document.forms[0].elements[i].name.substring(0,l-5);
                    cont += '<' + muestra + '>' + trim(document.forms[0].elements[i].value.replace('&', '&amp;').replace('<', '&lt;')) + '</' + muestra + '>';  
                  }
                  else{
                    muestra='';
                    cont += '<' + document.forms[0].elements[i].name + '>' + trim(document.forms[0].elements[i].value.replace('&', '&amp;').replace('<', '&lt;')) + '</' + document.forms[0].elements[i].name + '>';
                  }
                }
                else{
                  muestra='';
                  cont += '<' + document.forms[0].elements[i].name + '>' + trim(document.forms[0].elements[i].value.replace('&', '&amp;').replace('<', '&lt;')) + '</' + document.forms[0].elements[i].name + '>';
                }
              }
            }
          }
        }
      }
    } 
    } 
  }
  if(gnoml!='')
  {
    cont += '</'+'ITEM_' + gnoml + '>'; 
    cont += '</' + gnoml + '>'; 
    gnoml='';
    gniteml='';
  }
  cont = cont + '</' + 'XML>';
  if (tipo == "V") {
    document.forms[2].xmlv.value = cont;
  } else {
    document.forms[1].xml.value = cont;
  }
  //alert(cont);
  pObjFormulario.submit();
}
