/**********************************************************************************/
/******************  Función que cambia el color de una caja de texto ******************/
/******************  cuando le pasamos el foco                              ************/
/***************************************************************************************/
function fijarAtencion(campo){
	campo.focus();
	campo.style.backgroundColor = 'lightsteelblue';
	                        
}
 function ponBlanco(campo){
	campo.style.backgroundColor = '';
}
/*********************************************************************************************/
/******************  Función que me limpia los espacios                               ********/
/******************  en blanco del comienzo y fin de la cadena y me devuelve la cadena********/
/*********************************************************************************************/

function quitaBlancos(theForm) {
    if(theForm.value)
	{
		var x = theForm.value;
		theForm = (x.replace(/^\s+/,'')).replace(/\s+$/,'');
		return(theForm);
	}
}

/**********************************************************************************/
/******************  Función que me comprueba la longitud de un    ******************/
/******************  campo (si pasa de 300 no deja escibir)  ************/
/**********************************************************************************/

function compLongitud(campo)
{
var texto;
var long_texto = 240;	
texto = campo.value;
if(texto.length>long_texto)
{
		longitud = long_texto;
		alert('Introduzca como mucho ' + longitud + ' caracteres en el campo BENEFICIARIOS.');
		campo.value = campo.value.substr(0,longitud);
		campo.blur();
		return(false);
}
return(true);
}
/*******************************************************************************/
/******************  Función que me valida si hay algun     ********************/
/******************  caracter nulo o no.                    ********************/
/*******************************************************************************/
	function validaNoNulo(theFormtxtNombre){
		if (theFormtxtNombre.value == "") {
			return (false);
		}//fin del if
	 	else{
			return(true);
		}
	}//fin del validaNoNulo
/**********************************************************************************/
/******************  Función que me valida si el              ********************/
/******************  valor de un campo de texto es numerico   *******************/
/**********************************************************************************/

function validaNumero(theFormtxtNombre)
{
  var checkOK = "0123456789 \t\r\n\f";
  var checkStr = theFormtxtNombre.value;
  var allValid = true;
  for (i = 0;  i < checkStr.length;  i++)
  {
    ch = checkStr.charAt(i);
    for (j = 0;  j < checkOK.length;  j++)
      if (ch == checkOK.charAt(j))
        break;
    if (j == checkOK.length)
    {
      allValid = false;
      break;
    }
  }
  if (!allValid)
  {
    return (false);
  }
  return (true);
}

/**********************************************************************************/
/******************  Función que me valida si el              ********************/
/******************  valor de un campo de texto es numerico   *******************/
/**********************************************************************************/

function validaNumeroValor(valor)
{
  var checkOK = "0123456789";
  var checkStr = valor;
  var allValid = false;
  for (i = 0;  i < checkStr.length;  i++)
  {
    ch = checkStr.charAt(i);
    for (j = 0;  j < checkOK.length;  j++){
      if (ch == checkOK.charAt(j)){
        allValid=true;
        break;
      }
   }
 }
  if (!allValid)
  {
    return (false);
  }
  return (true);
}

/**********************************************************************************/
/******************  Función que me valida el campo teléfono  ********************/
/******************  valor de un campo de texto es numerico   *******************/
/**********************************************************************************/

function validaTelefono(valor)
{
  var checkOK = "0123456789";
  var checkStr = valor.value;
  var allValid = true;
  for (i = 0;  i < checkStr.length;  i++)
  {
    ch = checkStr.charAt(i);
    for (j = 0;  j < checkOK.length;  j++)
      if (ch == checkOK.charAt(j))
        break;
    if (j == checkOK.length)
    {
      allValid = false;
      break;
    }
  }
  if (!allValid)
  {
    return (false);
  }
  return (true);
}

/**************************************************************************/
/******************  Función que me valida los dígitos de          ******************/
/******************  control de una cuenta bancaria 	 ******************/
/**************************************************************************/

function validaDG(entidad,sucursal,DG,cuenta)
{
	banco=entidad+sucursal;

 	pesos1= new Object(8);
 	pesos1[0]='6';
 	pesos1[1]='3';
 	pesos1[2]='7';
 	pesos1[3]='9';
 	pesos1[4]='10';
 	pesos1[5]='5';
 	pesos1[6]='8';
 	pesos1[7]='4';

 	pesos2= new Object(10);  
 	pesos2[0]='6';
 	pesos2[1]='3';
 	pesos2[2]='7';
 	pesos2[3]='9';
 	pesos2[4]='10';
 	pesos2[5]='5';
 	pesos2[6]='8';
 	pesos2[7]='4';
 	pesos2[8]='2';
 	pesos2[9]='1';

 	result=0;
 	cont=0;
 
 	for (i=7;i>=0;i--)  
  	{
   		result=result+banco.charAt(i)*pesos1[cont];
   		cont++;
  	}             

 	resta=11-(result%11);
 	digito='';
	if (resta==11)
     		digito=digito+0;
	else if (resta==10)
        	digito=digito+1;
    	else 
          	digito=digito+resta;

 	corriente=cuenta;
 	cont2=0;
 	result2=0;

 	for (j=9;j>=0;j--)
  	{
   		result2=result2+corriente.charAt(j)*pesos2[cont2];
   		cont2++;
  	}

 	resta2=11-(result2%11);

	if (resta2==11)
     		digito=digito+0;

	else if (resta2==10)
        	digito=digito+1;
     	else 
          	digito=digito+resta2;

	if (digito==DG)
    		return(true);
	else
    		return(false);

}  
/**************************************************************************/
/********************      Funciones que pintan las páginas     ********************/
/*************************************************************************/
var pulsar=0;
function MM_goToURL() { //v3.0
  var i, args=MM_goToURL.arguments; document.MM_returnValue = false;
  for (i=0; i<(args.length-1); i+=2) eval(args[i]+".location='"+args[i+1]+"'");
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document); 
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_showHideLayers() { //v3.0
  var i,p,v,obj,args=MM_showHideLayers.arguments;
  for (i=0; i<(args.length-2); i+=3) if ((obj=MM_findObj(args[i]))!=null) { v=args[i+2];
    if (obj.style) { obj=obj.style; v=(v=='show')?'visible':(v='hide')?'hidden':v; }
    obj.visibility=v; }
}


function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

/*******************************************************************************/
/********************** ESTE GRUPO DE FUNCIONES SE ************************/
/********************** ENCARGA DE HACER PARPADEAR *********************/
/********************** UN LITERAL EN LA PARTE DE  *************************/
/********************** ABAJO DEL NAVEGADOR ******************************/
/*******************************************************************************/
function pintaAbajo(arg1,arg2,arg3,tipo){
	startclock(tipo,0);
	MM_preloadImages(arg1,arg2,arg3);
}
var timerRunning = false;
var timerID = null;
function stopclock(){  
	 if(timerRunning)      
		clearTimeout(timerID);
	timerRunning = false;
}

function startclock(tip,i){   
	// Nos aseguramos de que el reloj está parado   
	stopclock();  
	showtime(tip,i);
}
/******************************************************************************/
/**********************  Funcion que se encarga de sacar    *************************/
/**********************  un mensaje en la parte de abajo del *************************/
/**********************  browser desplanzando el mensaje    *************************/
/******************************************************************************/
function showtime2(tip,i){
	i++;   
	if (i==tip.length) i=0;
	window.defaultStatus=tip.substring(i);
	timerID = setTimeout("showtime('"+tip+"','"+i+"')",150);   
	timerRunning = true;
}
/******************************************************************************/
/**********************  Funcion que se encarga de sacar    *************************/
/**********************  un mensaje en la parte de abajo del *************************/
/**********************  browser haciendo un parpadeo        *************************/
/******************************************************************************/
function showtime(tip,i){
	i++;   
	if(i%10==1){
		window.defaultStatus="                                                                                                                         ";
	}else{
		window.defaultStatus=tip;
	}
	timerID = setTimeout("showtime('"+tip+"','"+i+"')",75);   
	timerRunning = true;
}
function pintura(tip){
	window.defaultStatus=tip;
	window.clearTimeout
}

/********************************************************************************/
/*****************  OBTENER VALOR DE UN RADIO BUTTON   ******************/
/********************************************************************************/
function GetRadioValue( radioObject ) { 
	var value = null;

	// Validate parameter value
	if (radioObject+"" == "undefined" || radioObject == null)
		return null;

	for (var i=0; i < radioObject.length; i++) { 
		if (radioObject[i].checked) { 
			value = radioObject[i].value;
			break;
		} 
	} // end for loop 
	
	return value;
}
/********************************************************************************/
/*******************     OBTENER VALOR DE UNA SELECT      ********************/
/********************************************************************************/
function GetSelectValue( selectObject ) {
	// Validate parameter value
	if (selectObject == null)
		return null;
	
	if (selectObject.selectedIndex+"" == "undefined" || 
				selectObject.selectedIndex == null ||
				selectObject.selectedIndex < 0)
		return null;

	return selectObject.options[selectObject.selectedIndex].value;
} 
/*********************************************************************************/
/**********************  Funcion que se encarga de validar      **************************/
/**********************  que la suma de una serie de campos   **************************/
/**********************  sea igual al 100%, o suma el importe   **************************/
/**********************  de todos los campos comprobando que**************************/
/**********************  sea igual que el tamaño de total           **************************/
/*********************************************************************************/
function validaTotal(arrayFondos,total) {
	var totFondos=0;
	var correcto=true;
	var ev="";
	var tota="";
	var conta=0;
	var auxev="";
	var auxev2="";
	var evaux="";
	for (i=0;i<total.length;i++){
		if (total[i]==","){
			tota=tota+".";
		}else{
			tota=tota+total[i];
		}
	}
	if (tota.length>total.length){
		tota="";
		for (i=0;i<total.length;i++){
			if (total.charAt(i)==","){
				tota=tota+".";
			}else{
				tota=tota+total.charAt(i);
			}
		}
	}
	total = tota;
	for (y=0;(y<arrayFondos.length);y++){
		ev  = eval('document.forms[0].'+arrayFondos[y]+'.value');
		auxev="";
		auxev2="";
		for (x=0;x<ev.length;x++){
			evaux="";
			if (ev.charAt(x)==","){
				auxev=auxev+".";
				auxev2=auxev2+",";
			}else{
				evaux=evaux+ev.charAt(x);
				if (validaNumeroValor(evaux)){
					auxev=auxev+evaux;
					auxev2=auxev2+evaux;
				}
			}
		}
		if (auxev!=""){
			totFondos=parseFloat(totFondos)+parseFloat(auxev);
			ev  = eval('document.forms[0].'+arrayFondos[y]+'.value="'+auxev2+'"');
		}
		else	{
			conta = conta+1;
		}
	}
	var t="",auxTF="",auxT="";
	auxTF = auxTF + totFondos;
	auxT = auxT + total;
	if (auxTF.length > auxT.length){
		totFondos = parseFloat(totFondos)*100000;
		t=t+totFondos;
		totFondos = parseFloat(t.split(".",1));
		totFondos = parseFloat(totFondos)/100000;
	}
	if( conta==arrayFondos.length  ){
		alert("Por favor, indique el importe que desea invertir en los fondos que conformarán su cartera");	
		correcto=false;
	}	
	else if (parseFloat(totFondos)!=parseFloat(total)){
		alert("La suma de las cantidades de todos los fondos debe ser igual al total especificado("+total+").");		
		correcto=false;
	}
	return correcto;
}

/**************************************************************************/
/*******                 VALIDACIÓN ALFANUMÉRICOS                    ******/
/**************************************************************************/

function isan(string) {
     if (string.length == 0)
         return false;
     for (var i=0;i < string.length;i++)

         if ((string.substring(i,i+1) < '0') || (string.substring(i,i+1) > '9'))
             return false;
     
     return true;
 }


function validaAlfanumerico(theFormtxtNombre)
{
  var checkOK = "ABCDEFGHIJKLMNÑOPQRSTUVWXYZÁÉÍÓÚabcdefghijklmnñopqrstuvwxyzáéíóúüÜºª-. \t\r\n\f,.1234567890";
  var checkStr = theFormtxtNombre.value;
  var allValid = true;
  for (i = 0;  i < checkStr.length;  i++)
  {
    ch = checkStr.charAt(i);

    for (j = 0;  j < checkOK.length;  j++) if (ch == checkOK.charAt(j)) break;
    if (j == checkOK.length)
    {
      allValid = false;

      break;
    }
  }
  if (!allValid)
  {
    theFormtxtNombre.focus();
    return (false);
  }
  return (true);
}
function validaAlfanumerico2(theFormtxtNombre)
{
  var checkOK = "ABCDEFGHIJKLMNÑOPQRSTUVWXYZÁÉÍÓÚabcdefghijklmnñopqrstuvwxyzáéíóúüÜºª-. \t\r\n\f";
  var checkStr = theFormtxtNombre.value;
  var allValid = true;

  for (i = 0;  i < checkStr.length;  i++)
  {
    ch = checkStr.charAt(i);

    for (j = 0;  j < checkOK.length;  j++) if (ch == checkOK.charAt(j)) break;
    if (j == checkOK.length)
    {
      allValid = false;

      break;
    }
  }
  if (!allValid)
  {
    theFormtxtNombre.focus();
    return (false);
  }
  return (true);
}
      
        
/**************************************************************************/
/*******                 VALIDACIÓN DE FECHAS                        ******/
/**************************************************************************/

//Función que me dice si el formato de una fecha es correcto ó no 

function y2k(number) { return (number < 1000) ? number + 1900 : number; }

function isDate (fecha) {


			var cadena = fecha.value.split("/",3);
			
			
			if ( (cadena[1]== null) && (cadena[2]== null)  ) {
					 cadena = fecha.value.split("-",3);
			}
			
			if ( (cadena[1]== null) || (cadena[2]== null)  ||  (cadena[1]=="")   ||  (cadena[2]=="")   ||  (cadena[2].length<4)   ||  (cadena[0].length<1)  ||  (cadena[1].length<1)   ) {
   				//alert("Por favor, debe introducir una fecha correcta");   				
					return(false);
			}
			
			var day = cadena[0].replace(/\s/g,'');
			var month = cadena[1].replace(/\s/g,'');
			var year = cadena[2].replace(/\s/g,'');


			
			if (day.length<2){
				day="0"+day;
			}
			if (month.length<2){
				month="0"+month;
			}
			
			var day2 =  day;
			var month2 = month;
			var year2 = year;		


// comprueba que la fecha pasada es valida
// El mes pasado debe estar entre 1 y 12 y el 
// año en el formato aaaa

   	if (month==0)
		return false;
    	var today = new Date();
    	year = ((!year) ? y2k(today.getYear()):year);
    	month = ((!month) ? today.getMonth():month-1);
    	if (!day) 
    		return false;
    	var test = new Date(year,month,day);
    	if ( (y2k(test.getYear()) == year) && (month == test.getMonth()) && (day == test.getDate()) ) {        
    	    fecha.value=day2+"/"+month2+"/"+year2;		 	
        	return true;}
    	else
        	return false;        	
	}

/*
Nos devuelve la edad actuarial de una persona.
Si entre el dia actual y el dia actual más 6 meses está la fecha de nacimiento de una persona entonces su edad actuarial será los
años que tiene ahora +1.
*/
function getEdadActuarial(dateString,dateType) {
 /*
    function getEdadActuarial
    parameters: dateString dateType
    returns: boolean

    dateString is a date passed as a string in the following
    formats:

    type 1 : 19970529
    type 2 : 970529
    type 3 : 29/05/1997
    type 4 : 29/05/97

    dateType is a numeric integer from 1 to 4, representing
    the type of dateString passed, as defined above.

    Returns string containing the age in years, months and days
    in the format yyy years mm months dd days.
    Returns empty string if dateType is not one of the expected
    values.
 */

     var now = new Date();
     var today = new Date(now.getYear(),now.getMonth(),now.getDate());

     var yearNow = now.getYear();

     if (yearNow.toString().length==4){
	yearNow=yearNow-1900;
     }

     var monthNow = now.getMonth();

     var dateNow = now.getDate();


     if (dateType == 1)
         var dob = new Date(dateString.substring(0,4),
                             dateString.substring(4,6)-1,
                             dateString.substring(6,8));
     else if (dateType == 2)
         var dob = new Date(dateString.substring(0,2),
                             dateString.substring(2,4)-1,
                             dateString.substring(4,6));
     else if (dateType == 3)
         var dob = new Date(dateString.substring(6,10),
                             dateString.substring(3,5)-1,
                             dateString.substring(0,2));
     else if (dateType == 4)
         var dob = new Date(dateString.substring(6,8),
                             dateString.substring(3,5)-1,
                             dateString.substring(0,2));
     else
         return '';

     var yearDob = dob.getYear();

     var monthDob = dob.getMonth();

     var dateDob = dob.getDate();
    
     yearAge = yearNow - yearDob;


     if (monthNow >= monthDob)
         var monthAge = monthNow - monthDob;
     else {
         yearAge--;
         var monthAge = 12 + monthNow -monthDob;
     }

     if (dateNow >= dateDob)
         var dateAge = dateNow - dateDob;
     else {
         monthAge--;
         var dateAge = 31 + dateNow - dateDob;

         if (monthAge < 0) {
             monthAge = 11;

             yearAge--; 
         }
     }
//      alert(yearAge + ' years ' + monthAge + ' months ' + dateAge + ' days');
//      return yearAge + ' years ' + monthAge + ' months ' + dateAge + ' days';
        if (monthAge>=6)
	yearAge++;
        return yearAge;
}

function getAge(dateString,dateType) {
 /*
    function getAge
    parameters: dateString dateType
    returns: boolean

    dateString is a date passed as a string in the following
    formats:

    type 1 : 19970529
    type 2 : 970529
    type 3 : 29/05/1997
    type 4 : 29/05/97

    dateType is a numeric integer from 1 to 4, representing
    the type of dateString passed, as defined above.

    Returns string containing the age in years, months and days
    in the format yyy years mm months dd days.
    Returns empty string if dateType is not one of the expected
    values.
 */

     var now = new Date();
     var today = new Date(now.getYear(),now.getMonth(),now.getDate());

     var yearNow = now.getYear();

     if (yearNow.toString().length==4){
	yearNow=yearNow-1900;
     }

     var monthNow = now.getMonth();

     var dateNow = now.getDate();


     if (dateType == 1)
         var dob = new Date(dateString.substring(0,4),
                             dateString.substring(4,6)-1,
                             dateString.substring(6,8));
     else if (dateType == 2)
         var dob = new Date(dateString.substring(0,2),
                             dateString.substring(2,4)-1,
                             dateString.substring(4,6));
     else if (dateType == 3)
         var dob = new Date(dateString.substring(6,10),
                             dateString.substring(3,5)-1,
                             dateString.substring(0,2));
     else if (dateType == 4)
         var dob = new Date(dateString.substring(6,8),
                             dateString.substring(3,5)-1,
                             dateString.substring(0,2));
     else
         return '';

     var yearDob = dob.getYear();

     var monthDob = dob.getMonth();

     var dateDob = dob.getDate();


     yearAge = yearNow - yearDob;

     if (monthNow >= monthDob)
         var monthAge = monthNow - monthDob;
     else {
         yearAge--;
         var monthAge = 12 + monthNow -monthDob;
     }

     if (dateNow >= dateDob)
         var dateAge = dateNow - dateDob;
     else {
         monthAge--;
         var dateAge = 31 + dateNow - dateDob;

         if (monthAge < 0) {
             monthAge = 11;

             yearAge--; 
         }
     }
//      alert(yearAge + ' years ' + monthAge + ' months ' + dateAge + ' days');
//      return yearAge + ' years ' + monthAge + ' months ' + dateAge + ' days';
        return yearAge;
}

function validaFechaNac(fechaIni)
{       
   var dia1  = fechaIni.substring(0,2);

   var mes1 = fechaIni.substring(3,5);

   var anio1 = fechaIni.substring(6);

   var fx_ini= dia1+ mes1+ anio1;
                                
	var today = new Date();		
	var dia2  = today.getDate();
   	var mes2 =  today.getMonth()+1;
   	var anio2 = (y2k(today.getYear()) );		
	
	var anioIni=1881;

                                
if(dia1 && anio1 && mes1 && mes2 && dia2 && anio2)
{
        if(parseInt(anio1)>parseInt(anio2))
                {
                alert('La FECHA DE NACIMIENTO no es correcta. Modifique la fecha.');
                return(false);
                }               
        else if(parseInt(anio1,10)==parseInt(anio2,10))
                {

                if (parseInt(mes1,10)>parseInt(mes2,10))
                        {
                        alert('La FECHA DE NACIMIENTO no es correcta. Modifique la fecha.');
                        return(false);
                        }
                else if(parseInt(mes1,10)==parseInt(mes2,10))
                        {
                        if(parseInt(dia1,10)>parseInt(dia2,10))
                                {
                                alert('La FECHA DE NACIMIENTO no es correcta. Modifique la fecha.');
                                return(false);
                                }
                        else if(parseInt(dia1,10)==parseInt(dia2,10))
                                {
                                return(true);
                                }
                        }
                }//fin  del if inicial 
 }//fin del if que me dice que existen esos campos de txt
 
 	if(parseInt(anio1)<parseInt(anioIni)) 
	{
		alert('La fecha de nacimiento no es correcta. Modifique la fecha.');
		return(false);
	}

return(true);
        }//fin de la funcion validaFechaIniFin


function validaFechaNacAutos(fechaIni,dia2,mes2,anio2)
{       
        var dia1  = fechaIni.substring(0,2);

   var mes1 = fechaIni.substring(3,5);

   var anio1 = fechaIni.substring(6);

        var fx_ini= dia1+ mes1+ anio1;
                                
    var dia2  = dia2;

  var mes2 = mes2;

  var anio2 = anio2;

        var fx_fin= dia2+ mes2+ anio2;
                                
if(dia1 && anio1 && mes1 && mes2 && dia2 && anio2)
{
        if(parseInt(anio1)>parseInt(anio2) || parseInt(anio1)<1900)
                {
                alert('La fecha introducida no es correcta. Por favor modifíquela.');
                return(false);
                }               
        else if(parseInt(anio1,10)==parseInt(anio2,10))
                {

                if (parseInt(mes1,10)>parseInt(mes2,10))
                        {
                        alert('La fecha introducida no es correcta. Por favor modifíquela.');
                        return(false);
                        }
                else if(parseInt(mes1,10)==parseInt(mes2,10))
                        {
                        if(parseInt(dia1,10)>parseInt(dia2,10))
                                {
                                alert('La fecha introducida no es correcta. Por favor modifíquela.');
                                return(false);
                                }
                        else if(parseInt(dia1,10)==parseInt(dia2,10))
                                {
                                return(true);
                                }
                        }
                }//fin  del if inicial 
 }//fin del if que me dice que existen esos campos de txt
return(true);
        }//fin de la funcion validaFechaIniFin


		
		
function ValidDate(y, m, d) // m = 0..11
 { with (new Date(y, m, d)) return ((getDate()==d) && (getMonth()==m)) }

function ReadISO8601date(Q) { var T // adaptable for other layouts
	if ((T = /^(\d+)([-\/])(\d\d)(\2)(\d\d)$/.exec(Q)) == null)
	{ return -2 } // bad format
	for (var j=1; j<=5; j+=2) 
	{ T[j] = parseInt(T[j], 10) } // wanted ?
	if (!ValidDate(T[1], T[3]-1, T[5])) 
	{ return -1 } // bad value
	return [ T[1], T[3], T[5] ] 
}
 
function DiferenciaAnios(F2, F1, dateType) { 
/*
    function DiferenciaAnios
    parameters: F2(la mayor), F1(la menor) dateType
    returns: String

    F1 & F2 son dos fechas pasadas como string con los 
	siguientes formatos:
    type 1 : 19970529
    type 2 : 970529
    type 3 : 29/05/1997
    type 4 : 29/05/97

    dateType es un número entero de 1 a 4, que representa
    el tipo de fecha que se ha pasado por parámetro, 
	tal como se define mas arriba.

    Devuelve un String que contiene la diferencia de años en el formato YYYY.
    Devuelve una cadena vacia si uan de las fechas no tiene el formato indicado.
 */

	if (dateType == 1){
		var S1 = F1.substring(0,4) + "/" +
                F1.substring(4,6) + "/" +
				F1.substring(6,8);
		var S2 = F2.substring(0,4) + "/" +
                F2.substring(4,6) + "/" +
				F2.substring(6,8);		
	}else if (dateType == 2){
		var S1 = F1.substring(0,2) + "/" +
                 F1.substring(2,4) + "/" +
                 F1.substring(4,6);
		var S2 = F2.substring(0,2) + "/" +
                 F2.substring(2,4) + "/" +
                 F2.substring(4,6);
	}else if (dateType == 3){
		var S1 = F1.substring(6,10) + "/" +
                 F1.substring(3,5) + "/" +
                 F1.substring(0,2);
		var S2 = F2.substring(6,10) + "/" +
                 F2.substring(3,5) + "/" +
                 F2.substring(0,2);
				

	}else if (dateType == 4){
		var S1 = F1.substring(6,8) + "/" +
				 F1.substring(3,5) + "/" +
                 F1.substring(0,2);
		var S2 = F2.substring(6,8) + "/" +
				 F2.substring(3,5) + "/" +
                 F2.substring(0,2);
   	}else
		return '';
		
 var D2 = ReadISO8601date(S2) ; if (D2<0) return ""
 var D1 = ReadISO8601date(S1) ; if (D1<0) return ""
 D1 = new Date(D1[0], D1[1], D1[2])
 D2 = new Date(D2[0], D2[1], D2[2])

 var age = D2.getFullYear() - D1.getFullYear()
 D1.setFullYear(D2.getFullYear())
 if (D1>D2) age--
 return age  
}

function getFechaHoy(){
	var now = new Date();
	var fechaHoy = "";
	if (now.getDate() < 10)
    	fechaHoy = fechaHoy + 0 + now.getDate();
	else 
		fechaHoy = fechaHoy + now.getDate();
	var mes = now.getMonth()+1;
	if ( mes<10)
		fechaHoy = fechaHoy + "/0" + mes;
	else
		fechaHoy = fechaHoy + "/" + mes;

	fechaHoy = fechaHoy + "/" + now.getFullYear();
	return fechaHoy;	
}

function dameEdad (F1, dataType){
	var now = new Date();
	var fechaHoy = "";
    fechaHoy = getFechaHoy();
	
	var edadActual = DiferenciaAnios(fechaHoy,F1, 3);
	return edadActual;
}
		
/*****************************************************/
/*****        FUNCION VALIDAR DNI               ******/
/*****************************************************/

function validarDNI(theFormtxtNombre)
{

	var Numeros = '0123456789';
	var Letras = 'ABCDEFGHIJKLMNÑOPQRSTUVWXYZabcdefghijklmnñopqrstuvwxyz';
	var Letras_Posibles = 'TRWAGMYFPDXBNJZSQVHLCKE';
	var Alfabeticos = 'ABCDEFGHKLMNPQSXabcdefghklmnpqsx';
	var Alfajur ='ABCEFGHSabcefghs';
	var Alfafis ='KLMXklmx';
	var Alfaposicion = 'ABDCEFGHNPQSabcdefghnpqs';
	var digito ="0";
	var cuarta ="3";

  //Obligatorio al menos un caracter

  	if (theFormtxtNombre.length < 1)
		return (-1);
    //Máximo nueve caracteres
	if (theFormtxtNombre.length < 2)
		return (-1);

  	if (theFormtxtNombre.length > 10)
		return (-2);

 	//Primer digito de los 10 siempre 0
	if ( ( theFormtxtNombre.charAt(0) != '0' ) && ( theFormtxtNombre.length == 10) )
	return(-3);


//Segundor caracter numérico o letra


	var cadena = theFormtxtNombre.toString();
	var digito1="0";
	var ch1 = cadena.charAt(0);
  
    		for (j = 0;  j < Alfabeticos.length;  j++)
      		{
			if (ch1 == Alfabeticos.charAt(j))
        			break;//es una letra
      		} 
		if (j==Alfabeticos.length){ 
			for (k = 0; k < Numeros.length; k++)
			{
      				if (ch1 == Numeros.charAt(k))
        				break;		//es un número
			}
			if (k == Numeros.length){
				return (-4);
			}else{
				digito1="11";
			}
		}
		else{
				digito1="10";
		}
		var re="";
		if ( digito1=="10" ) {
		   	if (cadena.length<10){
					for(i=0;i<10-cadena.length;i++){
						re="0"+re;
					}
					cadena=re+cadena;				
				}
		}

  		var ch = cadena.charAt(1);

    		for (j = 0;  j < Alfabeticos.length;  j++)
      		{
			if (ch == Alfabeticos.charAt(j))
        			break;
      		} 
		if (j==Alfabeticos.length){ 
			for (k = 0; k < Numeros.length; k++)
			{
      				if (ch == Numeros.charAt(k))
        				break;		
			}
			if (k == Numeros.length){
				return (-4);
			}else{
				digito="11";
			}
		}else{
			// miramos si el digito es A,B,S,E,F,G,H lo cual nos indicaria
			// que en la 10ª posicion habra un numero.
			for (c = 0; c < Alfajur.length; c++){
				if (ch==Alfajur.charAt(c)){
					digito="10";
					break;
				}
			}
			for (d = 0; d < Alfafis.length; d++){
				if (ch==Alfafis.charAt(d)){
					digito="99";
					break;
				}
			}
			if( ( c==Alfajur.length ) && (d ==  Alfafis.length) ) digito="14";
			for (e = 0; e < Alfaposicion.length; e++){
				if (ch==Alfaposicion.charAt(e)){
				   if ( (cadena.charAt(2)==8)||(cadena.charAt(2)==6) ){
						cuarta="1";
						break;
					}
					if (cadena.charAt(2)==9){
						cuarta="0";
						break;
					}
				}
			}
		}
  //Todos números excepto el último que es número o letra
	//var cadena = theFormtxtNombre.toString();
	
	var error = "0";
  	for (i=2; i< cadena.length; i++)
  	{
  		ch = cadena.charAt(i);
    		if (i < cadena.length-1)
    		{
	      		for (j = 0;  j < Numeros.length;  j++)
        			{
        				if (ch == Numeros.charAt(j)){
					if ( (i==3) && (cuarta=="0") && (ch=="0") ){
							error="1";
							break;
					}
					if ( (i==3) && (cuarta=="1") && ( (ch=="5") || (ch=="6") || (ch=="7") || (ch=="8") || (ch=="9") ) ){
							error="1";
							break;
					}
					break;					
				}
		     	}  
	
    			if (j == Numeros.length){
          				return (-5);
			}else{
				if (error=="1"){
					return(-6);
				}
			}
  		}  
   		else
    		{
      			for (j = 0; j < Letras.length; j++)
			{
        				if (ch == Letras.charAt(j))
          					break;
	        		}
     
      			if (j != Letras.length)
	//Si ha llegado hasta aquí, el último caracter es una letra del conjunto 'Letras'//
			{
				if (digito=="11"){
	         			return (1);
				}else if (digito=="99"){
	         			return (9);
				}else if (digito=="14"){
	         			return (2);
				//}else if (digito=="10"){
	         	//		return (2);
				}else{	return (-10);}
			}

      			else
	        		{
          				for (n = 0;  n < Numeros.length;  n++)
            				{
            					if (ch == Numeros.charAt(n))
               					{              
                					if (cadena.length < 9)
						//Si ha llegado hasta aquí, el último caracter es un número y hay menos de 9 caracteres//
		  				{
		  					return (-1);
		  				}
						else
							//Si ha llegado hasta aquí hay diez dígitos//
		  				{
							if (digito=="10"){
								return(2);
							}else{
			  					return (-5);
							}
		  				}

 	       				}
	            			}  

	          			if (n == Numeros.length)
					//Si ha llegado hasta aquí el último no es ni número ni letra
              					return (-4);
		        	}
    		}    
  	}  
	return(0);

}//End validarDNI 


//FUNCION COMPROBACION FORMATO DNI

function compruebaFormatoDNI(dni)
{

	var Numeros = '0123456789';
	var Letras = 'ABCDEFGHIJKLMNÑOPQRSTUVWXYZabcdefghijklmnñopqrstuvwxyz';
	var Letras_Posibles = 'TRWAGMYFPDXBNJZSQVHLCKE';

  //Obligatorio al menos un caracter

  	if (dni.length < 1)
		return (-1);
  
  //Primer caracter numérico

	var cadena = dni.toString();

  	for (i = 0; i < cadena.length; i++)
  	{
  		ch = cadena.charAt(0);

    		for (j = 0;  j < 10;  j++)
      		{
      			if (ch == Numeros.charAt(j))
        			break;
      		}  

    		if (j == 10)
      			return (-2);
  	}    

  //Máximo nueve caracteres

  	if (dni.length > 9)
		return (-3);

  //Todos números excepto el último que es número o letra

  	for (i=0; i< cadena.length; i++)
  	{
  		ch = cadena.charAt(i);
  
    		if (i != cadena.length-1)
    		{
      			for (j = 0;  j < Numeros.length;  j++)
        		{
        			if (ch == Numeros.charAt(j))
          				break;
        		}  

      			if (j == Numeros.length)
          			return (-4);
    		}  
    		else
    		{
      			for (j = 0; j < Letras.length; j++)
			{
        			if (ch == Letras.charAt(j))
          				break;
        		}
      
      			if (j != Letras.length)
	//Si ha llegado hasta aquí, el último caracter es una letra del conjunto 'Letras'//
			{
         			return (0);
			}

      			else
        		{
          			for (n = 0;  n < Numeros.length;  n++)
            			{
            				if (ch == Numeros.charAt(n))
               				{              
                				if (cadena.length < 9)
	//Si ha llegado hasta aquí, el último caracter es un número y hay menos de 9 caracteres//
		  				{
		  					return (1);
		  				}
						else
	//Si ha llegado hasta aquí hay nueve dígitos//
		  				{
		  					return (-5);
		  				}

 	       				}
            			}  

          			if (n == Numeros.length)
	//Si ha llegado hasta aquí el último no es ni número ni letra
              				return (-4);
        		}
    		}    
  	}  
	return(0);

}//End compruebaFormatoDNI 
/*****************************************************/
/***** FUNCION COMPROBACIÓN DE LA LETRA DEL NIF ******/
/*****************************************************/


function compruebaLetraDNI(theForm)
{
	var nif = theForm.DNI.value.toUpperCase();
	//var nif = theForm.value.toUpperCase();
	//var nif = theForm.value;
	var Letras_Posibles = 'TRWAGMYFPDXBNJZSQVHLCKE';

  //Caso en que se ha introducido una letra: se comprueba si es correcta

  	if (compruebaFormatoDNI(nif) == 0)
  	{
  //separo la letra del nif 
    		letra_documento = nif.charAt(nif.length-1);

  //separo el número del nif
    		numero_documento = '';
  
      		for (i=0; i < nif.length-1; i++)
      		{
        		numero_documento = numero_documento + nif.charAt(i);
      		}
  //calculo la letra que le correspondería a ese número
    		pos_corr = (numero_documento%23);
    		letra_correcta = Letras_Posibles.charAt(pos_corr);

  //compruebo que sean iguales
      		if (letra_documento != letra_correcta)
        	{       
        		NIF = numero_documento + letra_correcta;        	
        		alert('La letra del NIF no es correcta. Va a ser reemplazada por la correspondiente al DNI informado');
			return (0);    
        	}
      		else
        		return (1);
  	}//end if
  	
  //Caso en que todo sean números: Calculo la letra correspondiente a ese número

  	if (compruebaFormatoDNI(nif) == 1)
  	{
  		var pos = (nif%23);
  		letra = Letras_Posibles.charAt(pos);
  		NIF = nif.toString() + letra;
  		alert('La letra del NIF no es correcta. Va a ser reemplazada por la correspondiente al DNI informado');
  		return (2);
  	}  

}//END compruebaLetraDNI



// FUNCIÓN QUE COMPRUEBA LA LETRA DEL DNI (BIS)

function compruebaLetraDNI2(nif){
	
	//var nif = theForm.txtNIF.value.toUpperCase(); CAMBIO RESPECTO A VALIDARLETRADNI
	nif=nif.toUpperCase();
	//var nif = theForm.value.toUpperCase();
	//var nif = theForm.value;
	var Letras_Posibles = 'TRWAGMYFPDXBNJZSQVHLCKE';
  //Caso en que se ha introducido una letra: se comprueba si es correcta
  	if (compruebaFormatoDNI(nif) == 0)
  	{
  //separo la letra del nif 
    		letra_documento = nif.charAt(nif.length-1);

  //separo el número del nif
    		numero_documento = '';
  
      		for (i=0; i < nif.length-1; i++)
      		{
        		numero_documento = numero_documento + nif.charAt(i);
      		}
  //calculo la letra que le correspondería a ese número
    		pos_corr = (numero_documento%23);
    		letra_correcta = Letras_Posibles.charAt(pos_corr);

  //compruebo que sean iguales
      		if (letra_documento != letra_correcta)
        	{       
        		NIF = numero_documento + letra_correcta;        	
        		alert('La letra del NIF no es correcta.');
			return (-1);    
        	}
      		else
        		return (1);
  	}//end if
  	
  //Caso en que todo sean números: Calculo la letra correspondiente a ese número

  	if (compruebaFormatoDNI(nif) == 1)
  	{
  		var pos = (nif%23);
  		letra = Letras_Posibles.charAt(pos);
  		NIF = nif.toString() + letra;
  		alert('La letra del NIF no es correcta. ');
  		return (-1);
  	}  

}//END compruebaLetraDNI2

/*******************************************************************/
/***** FUNCION CONFIRMACION DE DATOS INTRODUCIDOS ******/
/******************************************************************/
function confirmacion(){
	if (!confirm("¿Esta seguro que los datos introducidos son correctos?")) {
                	return(false);
	}else return(true);
}


/********************************************************************************/
/**********FUNCION QUE QUITA LOS PUNTOS DE UN STRING ******************************/
/*********************************************************************************/

function quitaPuntos(cadena){

	var straux="";
	
 for (var i = 0;  i < cadena.length;  i++)
  {
    ch = cadena.charAt(i);
    
      if (ch != '.'){straux=straux+cadena.charAt(i);}
  }
  return(straux);   
}
/********************************************************************/
/*********** FUNCION QUE VALIDA EL CODIGO POSTAL         ************/
/********************************************************************/
function validaCodigoPostal(txtForm){
	var nombreProvincia;
	var correcto=false;
	if (!validaNoNulo(txtForm)){
		alert("El campo código postal debe estar rellenado");
		txtForm.focus();
	}else{
		if (!validaNumero(txtForm)){
			alert("El campo código postal debe ser un número");
			txtForm.focus();
		}else{
			if ( (txtForm.value.length>5)  ||  (txtForm.value.length<5)   ){			
				alert("El código postal debe tener un tamaño de 5 dígitos.");
				txtForm.focus();
			}else{
				if ( (parseInt(txtForm.value.substring(0,2)) >0 )  &&  (parseInt(txtForm.value.substring(0,2)) < 53) ){
				correcto=true;
				}else{
					if (  (parseInt(txtForm.value.substring(0,2))>52)  || (parseInt(txtForm.value.substring(0,2))<1)  ){
						alert("Los códigos postales sólo pueden empezar por 01 hasta 52.");
						txtForm.focus();			
					}
				}
			}
		}
	}
	return correcto;
}

/********************************************************************/
/***********    FUNCION QUE PASA DE CAMPO A CAMPO        ************/
/********************************************************************/
/*Esta función se encarga de pasar de un campo a otro, cuando llega al límite del tamaño del primero*/

function chkCampo(rCampoA, rCampoS, maxLon) {
    if (rCampoA.value.length == maxLon) rCampoS.focus();
    else rCampoA.focus();
}

/***************************************************************************/
/*********** FUNCION QUE PASA CORRECTAMENTE UNA URL  ************/
/***************************************************************************/
/*
Esta función se encarga de pasar una URL en JS en la que desaparecen los simbolos raros.
Que pueden perjudicar en que la URL sea correcta.
*/
function URLEncode(strIn) {

	var len = strIn.length;
	var i,ch;
	
	var strOut = "";
	for (i=0; i<len; i++) {
		ch = strIn.charAt(i);
		
		if (ch == " ") {
			ch = '+';
		} else if (ch == "&") {
			ch = "%26";
		} else if (ch == "á") {
			ch = "%E1";
		} else if (ch == "é") {
			ch = "%E9";
		} else if (ch == "í") {
			ch = "%ED";
		} else if (ch == "ó") {
			ch = "%F3";
		} else if (ch == "ú") {
			ch = "%FA";
		} else if (ch == "Á") {
			ch = "%C1";
		} else if (ch == "É") {
			ch = "%C9";
		} else if (ch == "Í") {
				ch = "%CD";
		} else if (ch == "Ó") {
			ch = "%D3";
		} else if (ch == "Ú") {
			ch = "%DA";
		} else if (ch == "ñ") {
			ch = "%F1";
		} else if (ch == "Ñ") {
			ch = "%D1";
		} else if (ch == "/") {
			ch = "%2F";
		} else if (ch == "\\") {
			ch = "";
		} else if (ch == "=") {
			ch = "%3D";
		} else if (ch == ":") {
			ch = "%3A";
		} else if (ch == ";") {
			ch = "%3B";
		} else if (ch == "'") {
			ch = "%27";
		} else if (ch == "\"") {
			ch = "%22";
		}
		
		strOut += ch;
	}
	
	return strOut;

}

/********************************************************************************************/
/*****  FUNCION QUE VALIDA SI UN CAMPO NUMÉRICO ES CORRECTO DEPENDIENDO DE LA MONEDA  *******/
/********************************************************************************************/

function validaCantidad2(moneda,_campo,numEnteros,numDecimales,nombreCampo){

var s1="",p1="",p2="",p3="",p1_tmp="",p2_tmp="";
  s1=_campo.value.replace(/\s/g,'');
  if(s1==""){//_campo.value="0"; 
  				 return(true);
  	}
  for(var i=0;i<s1.length;i++){
    if(s1.charAt(i)!=',') p1+=s1.charAt(i);//parte entera del campo
    else{
      p2=s1.substr(i+1,s1.length); //parte decimal del campo
      i=s1.length;
    }
  }
  
  for(i=0;i<p1.length;i++) if(!isNaN(p1.charAt(i))) p1_tmp+=p1.charAt(i);
		//Eliminamos los caracteres que no sean numericos
  for(i=0;i<p2.length;i++) if(!isNaN(p2.charAt(i))) p2_tmp+=p2.charAt(i);
		//Eliminamos los caracteres que no sean numericos
  p1=p1_tmp;
  p2=p2_tmp;

  
  if ( p1.length>numEnteros ) { //comprobamos el número de enteros q puede tener el campo 		
  		alert("El campo "+nombreCampo+" solo puede tener "+numEnteros+ " enteros");
  		_campo.focus();		
  		return(false);
	}
	
if ( (moneda!="P") && (p2.length>numDecimales) ) { //comprobamos el número de decimales q puede tener el campo 		
  		alert("El campo "+nombreCampo+" solo puede tener "+numDecimales+ " decimales");
  		_campo.focus();		
  		return(false);
	}
  
  if ( p2!=0  &&  moneda=="P") {  //Si la moneda es peseta no permitimos importes con decimales
  		   alert("No se admiten decimales en el campo "+nombreCampo);
  		   p2="";
  }
  else if ( moneda=="P" ) {
   		 p2="";
  }  
  
  //En la parte entera del número colocaremos colocaremos los puntos de los millares 
  j=0;
  for(i=0;i<=p1.length;i++){
    if(p1.charAt(i)!='.') p3+=p1.charAt(i);
  }
  for(i=0;p3.charAt(i)=='0';i++);
  if(p3.length==i) p3="0";
  else p3=p3.substr(i,p3.length);
  j=0;
  p1="";
  for(i=p3.length;i>=0;i--){
    p1=p3.charAt(i)+p1;
    if((j++==3)&&(i!=0)){
      j=1;
      p1='.'+p1;
    }
  } 
  if((p1!="")&&(p2!="")) p4=p1+","+p2
  else p4=p1+p2;
  if(p4=="") p4="0";
  _campo.value=p4; //
  return(true);
}


function validaTotal2(arrayFondos,total,moneda) {
        var totFondos=0;
        var correcto=true;
        var ev;
        var tota="";
        var conta=0;
        var j=0;                
        for (i=0;i<total.length;i++){

                if (total[i]==","){

                        tota=tota+".";

                }else{
                        tota=tota+total[i];

                }
        }
        
                for (j=0;(j<arrayFondos.length);j++){           
	                ev  = eval('document.forms[0].'+arrayFondos[j]);                       
		if (!validaCantidad2(moneda,ev,9, 2,"IMPORTE")){
			alert( "return");
			return;
		}                    					    
		ev=enviarDato(ev);        
	     	if (ev!=""){
      	                	totFondos =parseFloat(ev)+parseFloat(totFondos);         
                	}else{
	            	            conta = conta+1;
	              	}
	}
        
        if( conta==arrayFondos.length  ){
                alert("Por favor, indique el importe que desea invertir en los fondos que conformarán su cartera");             
                correcto=false;
        }       
        else if (parseFloat(totFondos)!=parseFloat(total)){
                alert("La suma de las cantidades de todos los fondos debe ser igual al total especificado("+total+").");                
                correcto=false;

        }       
        return correcto;
}
function validaCantidad3(moneda,_campo,numEnteros,numDecimales,nombreCampo){

var s1="",p1="",p2="",p3="",p1_tmp="",p2_tmp="";
  s1=_campo.value.replace(/\s/g,'');
  if(s1==""){//_campo.value="0"; 
  				 return(true);
  	}
  for(var i=0;i<s1.length;i++){
    if(s1.charAt(i)!=',') p1+=s1.charAt(i);//parte entera del campo
    else{
      p2=s1.substr(i+1,s1.length); //parte decimal del campo
      i=s1.length;
    }
  }
  
  for(i=0;i<p1.length;i++) if(!isNaN(p1.charAt(i))) p1_tmp+=p1.charAt(i);
		//Eliminamos los caracteres que no sean numericos
  for(i=0;i<p2.length;i++) if(!isNaN(p2.charAt(i))) p2_tmp+=p2.charAt(i);
		//Eliminamos los caracteres que no sean numericos
  p1=p1_tmp;
  p2=p2_tmp;

  
  if ( p1.length>numEnteros ) { //comprobamos el número de enteros q puede tener el campo 		
  		alert("El campo "+nombreCampo+" solo puede tener "+numEnteros+ " enteros");
  		_campo.focus();		
  		return(false);
	}
	
if ( (moneda!="P") && (p2.length>numDecimales) ) { //comprobamos el número de decimales q puede tener el campo 		
  		alert("El campo "+nombreCampo+" solo puede tener "+numDecimales+ " decimales");
  		_campo.focus();		
  		return(false);
	}
  
  if ( p2!=0  &&  moneda=="P") {  //Si la moneda es peseta no permitimos importes con decimales
  		   alert("No se admiten decimales en el campo "+nombreCampo);
  		   p2="";
  }
  else if ( moneda=="P" ) {
   		 p2="";
  }  
  
  //En la parte entera del número colocaremos colocaremos los puntos de los millares 
  j=0;
  for(i=0;i<=p1.length;i++){
    if(p1.charAt(i)!='.') p3+=p1.charAt(i);
  }
  for(i=0;p3.charAt(i)=='0';i++);
  if(p3.length==i) p3="0";
  else p3=p3.substr(i,p3.length);
  j=0;
  p1="";
  for(i=p3.length;i>=0;i--){
    p1=p3.charAt(i)+p1;
    if((j++==3)&&(i!=0)){
      j=1;
      p1=p1;
    }
  } 
  if((p1!="")&&(p2!="")) p4=p1+","+p2
  else p4=p1+p2;
  if(p4=="") p4="0";
  _campo.value=p4; //
  return(true);
}


//Antes de enviar los datos, debemos eliminar los millares de la parte entera de la cantidad,
//y sustituiremos la coma decimal por un punto.

function enviarDato(_campo){
var s1="",s2="";
  //eval("s1=document."+this.form+"."+_campo+".value.replace(/\s/g,'')");  
  s1=_campo.value.replace(/\s/g,'');

  
  //if(s1=="") return 0;
  
  for(var i=0;i<s1.length;i++){
    if(s1.charAt(i)!='.')
      if(s1.charAt(i)==',') s2+='.';
      else s2+=s1.charAt(i);
  }
  //if(s2=="") s2="0";
  
  return(s2);
  
}

/********************************************************************************/
/*****************  OBTENER VALOR DE UN RADIO BUTTON   ******************/
/********************************************************************************/
function GetRadioIndex( radioObject ) { 
	for (var i=0; i < radioObject.length; i++) { 
		if (radioObject[i].checked) { 
			break;
		} 
	}
	return i;
}

/**********************************************************************************/
/******************  Función que me limpia los espacios          ******************/
/******************  en blanco del comienzo y fin de la cadena.	 ******************/
/**********************************************************************************/

// función que me limpia los espacios en blanco del comienzo y fin de la cadena.

function trim(theFormtxtDsNombre) {
    if(theFormtxtDsNombre.value)
	{
		var x = theFormtxtDsNombre.value;
		theFormtxtDsNombre.value = (x.replace(/^\s+/,'')).replace(/\s+$/,'');
	}
}

/**********************************************************************************/
/******************                      Función que me valida si un              ********************/
/******************                           valor es numerico                        ********************/
/**********************************************************************************/

function validaNumero2(theFormtxtNombre)
{
  var checkOK = "0123456789 \t\r\n\f";
  var checkStr = theFormtxtNombre;
  var allValid = true;
  for (i = 0;  i < checkStr.length;  i++)
  {
    ch = checkStr.charAt(i);
    for (j = 0;  j < checkOK.length;  j++)
      if (ch == checkOK.charAt(j))
        break;
    if (j == checkOK.length)
    {
      allValid = false;
      break;
    }
  }
  if (!allValid)
  {
    return (false);
  }
  return (true);
}

/*********************************************************************************/
/******************             Función que me valida si la  letra              ********************/
/******************           de una matricula nueva es correcta             ********************/
/*********************************************************************************/

function validaLetraNueva(letras)
{
  var checkOK = "BCDFGHJKLMNPRSTVWXYZbcdfghjklmnprstvwxyz";
  var checkStr = letras;
  var allValid = true;
  for (i = 0;  i < checkStr.length;  i++)
  {
    ch = checkStr.charAt(i);
    for (j = 0;  j < checkOK.length;  j++)
      if (ch == checkOK.charAt(j))
        break;
    if (j == checkOK.length)
    {
      allValid = false;
      break;
    }
  }
  if (!allValid)
  {
    return (false);
  }
  return (true);
}

/*********************************************************************************/
/******************                Función que me valida que el                 ********************/
/******************                      dato sea sólo letras                          ********************/
/*********************************************************************************/
function validaLetras(theFormtxtNombre)
{
  var checkOK = "ABCDEFGHIJKLMNÑOPQRSTUVWXYZabcdefghijklmnñopqrstuvwxyz";
  var checkStr = theFormtxtNombre;

  var allValid = true;

  for (i = 0;  i < checkStr.length;  i++)
  {
    ch = checkStr.charAt(i);

    for (j = 0;  j < checkOK.length;  j++) if (ch == checkOK.charAt(j)) break;
    if (j == checkOK.length)
    {
      allValid = false;

      break;
    }
  }
  if (!allValid)
  {
    return (false);
  }
  return (true);
}
        
/***********************************************************************************/
/******************             Función que me valida si la/s  letra/s             ********************/
/******************      del principio una matricula nueva es correcta        ********************/
/***********************************************************************************/

function validaLetrasIniMat(letras)
{
  var inicialProv = new Array("A","AB","AL","AV","B","BA","BI","BU","C","CA","CC","CE","CO","CR","CS","CU","GC","GI","GE","GR","GU","H","HU","J","L","LE","LO","LU","M","MA","ML","MU","NA","O","OU","OR","P","IB","PM","PO","S","SA","SE","SG","SO","SS","T","TE","TF","TO","V","VA","VI","Z","ZA");
  var checkStr = letras;
  var allValid = true;
  for (y = 0;  y < inicialProv.length;  y++){
  	if (checkStr == inicialProv[y]) break;
  }
  if (y == inicialProv.length){
      allValid = false;
  }
  if (!allValid)
  {
    return (false);
  }
  return (true);
}
/************************************************************************************/
/******************             Función que me valida si la matrícula             ********************/
/********************      es un vehículo especial tipo E o R  o TE      ***********************/
/***********************************************************************************/

function vehiculoEspecial(matr)
{
	if (matr.length==4){
		// vehiculos del tipo E
 		if (validaNumero2(matr.substring(0,2))){
			if(matr.substring(2)=="VE"){
				return(true);
			}else{
				return(false);
			}
		}else{
			return(false);
		}
	}else{
		if (matr.length==3){
			// vehiculos del tipo R
 			if (validaNumero2(matr.substring(0,2))){
				if(matr.substring(2)=="R"){
					return(true);
				}else{
					return(false);
				}
			}else{
				if ( ( matr.substring(0,1) == "T" ) || ( matr.substring(0,1) == "R" ) ){
					if ( validaNumero2(matr.substring(1,3)) ){
						return(true);
					}else{
						return(false);
					}
				}else{
					return(false);
				}
			}
		}else{
			return(false);
		}
	}
}
/************************************************************************************/
/******************             Función que me valida si la matrícula             ********************/
/******************      es un vehículo especial tipo E1 o R1 o C o T1          ******************/
/***********************************************************************************/

function vehiculoEspecial2(matr)
{
	if (matr.length==8){
		if ( (matr.substring(0,1)=="E") ||  (matr.substring(0,1)=="R")  ||  (matr.substring(0,1)=="C")  ||  (matr.substring(0,1)=="T")  ||  (matr.substring(0,1)=="H")  ||  (matr.substring(0,1)=="P") ||  (matr.substring(0,1)=="V") ||  (matr.substring(0,1)=="S") ) {
			if (validaNumero2(matr.substring(1,5))){
				if ( validaLetraNueva(matr.substring(5)) ){			
					return(true);
				}else{
					return(false);
				}
			}else{
				return(false);
			}
		}else{
			return(false);
		}
	}else{
		return(false);
	}
}
/************************************************************************************/
/******************             Función que me valida si la matrícula             ********************/
/******************      es un vehículo del estado (tipo M o M1)         ******************/
/***********************************************************************************/

function vehiculoEstado(matr)
{
	var matEstado = new Array("A","DGP","EA","ET","FN","MF","MMA","MOP","PGC","PME","PMM");	
	var mat1 = matr.substring(0,1);
	var mat2 = matr.substring(0,2);
	var mat3 = matr.substring(0,3);
	var rest = "";
	for (var q = 0;  q <matEstado.length;  q++){
		if (mat1 == matEstado[q]) break;
	}
	for (var y = 0;  y <matEstado.length;  y++){
		if (mat2 == matEstado[y]) break;
	}
	for (var t = 0;  t <matEstado.length;  t++){
		if (mat3 == matEstado[t]) break;
	}
	if (q != matEstado.length){
		rest = matr.substring(1);
	}else{
		if (y != matEstado.length){
			rest = matr.substring(2);
		}else{
			if (t != matEstado.length){
				rest = matr.substring(3);
			}else{
				return(false);
			}
		}
	}
	if (validaNumero2(rest.substring(0,4))){
		if (rest.substring(4).length==2){
			if (validaNumero2(rest.substring(4,6))){
				return(true);
			}
			if (validaLetras(rest.substring(4,6))){
				return(true);
			}
			return(false);
		}else{
			return(false);
		}
	}else{
		if (rest.substring(0,2) == "VE"){
			if (rest.substring(2).length==6){	
				if (validaNumero2(rest.substring(2,8))){
					return(true);
				}else{
					return(false);
				}
			}else{
				return(false);
			}
		}else{
			return(false);
		}
	}
}
/************************************************************************************/
/******************             Función que me valida si la matrícula             ********************/
/**************      es un vehículo de pruebas (tipo P) o de la ITV (tipo I)          ***************/
/***********************************************************************************/

function vehiculoPruebasITV(matr)
{
	if ( validaNumero2(matr.substring(0,2))){
		if ( (matr.substring(2,3) == "P") || (matr.substring(2,3) == "T")){
			if ( validaNumero2(matr.substring(3,7)) ){
				if ( (matr.substring(7,8) =="1") || (matr.substring(7,8) =="2") ){
					if ( (matr.substring(8).length == "0") || (matr.substring(8).length == "2") ){
						if (matr.substring(8).length =="2") {
							if ( validaNumero2(matr.substring(8,10)) ){
								return(true);
							}else{
								return(false);
							}
						}else{
							return(true);
						}
					}else{
						return(false);
					}
				}else{
					return(false);
				}
			}else{
				return(false);
			}
		}else{
			return(false);
		}
	}else{
		if (matr.substring(0,3) == "ITV"){
			if (matr.substring(3).length == 4){
				if ( validaNumero2(matr.substring(3,7)) ){
					return(true);
				}else{
					return(false);
				}
			}else{
				return(false);
			}
		}else{
			return(false);
		}
	}
}
/************************************************************************************/
/******************             Función que me valida si la matrícula             ********************/
/***********************      es una matrícula de tipo turística T         ***********************/
/***********************************************************************************/

function vehiculoTuristico(matr)
{
  var mesRomano= new Array("I","II","III","IV","V","VI","VII","VIII","IX","X","XI","XII");
	if (matr.length>=7){
		if ( validaNumero2(matr.substring(0,2)) ){
			if ( validaLetras(matr.substring(2,3)) ){
				if ( validaLetras(matr.substring(3,4)) ){
					//es una posible provincia de 2 letras
					if (validaLetrasIniMat(matr.substring(2,4))){
						if (validaNumero2(matr.substring(4,8))){
							if ( (matr.substring(8).length == 4) || (matr.substring(8).length==0) ){
								if ( matr.substring(8).length==4){
									for (var y = 0;  y <mesRomano.length;  y++){
  										if (matr.substring(8,10) == mesRomano[y]) break;
									}
									if (y == mesRomano.length){
										return(false);
									}
									if (validaNumero2(matr.substring(10,12))){
										return(true);
									}else{
										return(false);
									}
								}
							}
						}
					}else{
						return(false);
					}
				}else{
					//es una posible provincia de 1 letra
					if (validaLetrasIniMat(matr.substring(2,3))){
						if (validaNumero2(matr.substring(3,7))){
							if ( (matr.substring(7).length==4) || (matr.substring(7).length==0) ){
								if ( matr.substring(7).length==4){
									for (y = 0;  y <mesRomano.length;  y++){
  										if (matr.substring(7,9) == mesRomano[y]) break;
									}
									if (y == mesRomano.length){
										return(false);
									}
									if (validaNumero2(matr.substring(9,11))){
										return(true);
									}else{
										return(false);
									}
								}							
							}
						}						
					}else{
						return(false);
					}
				}
			}else{
				return(false);
			}
		}else{
			return(false);
		}
	}else{
		return(false);
	}
}
/************************************************************************************/
/******************             Función que me valida si la matrícula             ********************/
/************************      es un vehículo de regimen diplomático           ************************/
/***********************************************************************************/

function regimenDiplomatico(matr)
{
	if ( (matr.substring(0,2)=="CD") ||  (matr.substring(0,2)=="OI")  ||  (matr.substring(0,2)=="TA") ||  (matr.substring(0,2)=="CC") ) {
		if (matr.length==8){
			if (validaNumero2(matr.substring(2,8))){
				return(1);
			}else{
				return(0);
			}
		}else{
			return(0);
		}
	}else{
		return(2);
	}
}
/*******************************************************************************/
/**********************        Función que me valida si la          ************************/
/**********************  	  matrícula es correcta                ************************/
/*******************************************************************************/
function validaMatricula(txtMatricula){
 	txtMatricula.value = txtMatricula.value.toUpperCase();
	trim(txtMatricula);
	var valor = txtMatricula.value;
	var auxMat = "";
	
	//No se debe introducir una E al principio. DMFVIRE 24/08/2004.
	if (valor.substring(0, 1) =="E"){
		alert("La matricula introducida no es correcta");
		return(false);
	}
	
	
	axMod = valor.split("-");
	if (axMod.length > 1){
		alert("La matrícula debe ser introducida sin guiones.");
		return(false);
//		valor="";
//		for (var x=0; x < axMod.length;x++) {
//			auxMat = axMod[x];
//			axMod[x] = (auxMat.replace(/^\s+/,'')).replace(/\s+$/,'');
//			valor = valor + axMod[x];
//		}//end del for
	}
	auxMat = "";
	for (x=0; x< valor.length;x++){
		if (valor.charAt(x) != " ") auxMat += valor.charAt(x);
	}
	valor = auxMat;
	txtMatricula.value = valor;
	if ( validaNumero2(valor.substring(0,4)) ){
		if (valor.substring(4).length ==3){
			if ( !validaLetraNueva(valor.substring(4)) ){
				alert("La matrícula introducida no es correcta.");
				return(false);
			}
		}else{
			alert("La matrícula introducida no es correcta.");
			return(false);
		}
	}else{
		if ( vehiculoTuristico(valor)){
			return(true);
		}
		if ( validaLetras(valor.substring(0,1)) ){
			if ( validaLetras(valor.substring(1,2)) ){
				if (vehiculoEstado(valor)) {
					return(true);
				}
				var auxRD="";
				auxRD = auxRD+regimenDiplomatico(valor);
				//se valida que la matricula sea del tipo D (regimen diplomático)
				if (auxRD == 1){
					return(true);
				}else{
					if(auxRD == 0){
						if (valor.substring(0,2)!= "CC"){
							alert("El formato de una matrícula en Régimen Diplomático debe tener el formato: "+valor.substring(0,2)+"-000000. Completando con ceros cada bloque de tres cifras.");	
							return(false);
						}
					}
				}	
				//las dos primeras posiciones son letras	
				if (!validaLetrasIniMat(valor.substring(0,2))){
					//Se comprueba si seguido de la 1ª letra esta el literal ITV
					if (valor.substring(1,4) == "ITV"){
						if (vehiculoPruebasITV(valor.substring(1))){
							return(true);
						}
					}
					alert("La matrícula introducida no es correcta, la provincia no es correcta.");
					return(false);
				}else{
					if (valor.substring(2,5) == "ITV"){
						if (vehiculoPruebasITV(valor.substring(2))){
							return(true);
						}
					}
					if (validaLetrasIniMat(valor.substring(0,1))){
						if (vehiculoPruebasITV(valor.substring(1))){
							return(true);
						}
					}
				}	
				if ( validaNumero2(valor.substring(2,6))){
					if (valor.substring(6).length > 2){
						// a las 2 primeras posiciones, que son letras, les siguen 4 números, 
						//pero hay más de 2 posiciones despues, es decir, ni tiene 6 números
						//despues de las 2 letras, ni tiene 4 numeros y como máximo 2 letras.
						if (vehiculoEspecial(valor.substring(6))){
							return(true);
						}
						alert("La matrícula introducida no es correcta.");
						return(false);
					}else{
						//se compruba el valor de las 2 últimas posiciones
						if (!validaNumero2(valor.substring(6)) ){
							//si estas 2 ultimas no son números.
							if (!validaLetras(valor.substring(6))){
								alert("La matrícula introducida no es correcta.");
								return(false);							
							}
						}else{
							//si estas 2 ultimas son números.
							if (valor.substring(6).length != 2){
								alert("La matrícula introducida no es correcta.");
								return(false);
							}
						}
					}
				}else{
					// a las 2 primeras posiciones, que son letras, no les siguen 4 números.
					alert("La matrícula introducida no es correcta.");
					return(false);
				}
			}else{
				//la primera posicion es una letra
				if (!validaLetrasIniMat(valor.substring(0,1))){
					if (vehiculoEspecial2(valor)){
						return(true);
					}
					alert("La matrícula introducida no es correcta, la provincia no es correcta.");
					return(false);
				}	
				if ( validaNumero2(valor.substring(1,5))){
					if (valor.substring(5).length > 2){
						// a la primera posicion, que es una letra, le sigue 4 números, 
						//pero hay más de 2 posiciones despues, es decir, ni tiene 6 números
						//despues de la letra, ni tiene 4 numeros y como máximo 2 letras.
						if (vehiculoEspecial(valor.substring(5))){
							return(true);
						}
						if (vehiculoEspecial2(valor)){
							//se valida que la matricula sea del tipo E1 ó R1 ó C (ciclomotores) ó T1 (turística) ó TT .
							return(true);
						}
						alert("La matrícula introducida no es correcta.");
						return(false);
					}else{
						//se comprueba el valor de las 2 últimas posiciones
						if (!validaNumero2(valor.substring(5)) ){
							//si estas 2 ultimas no son números.
							if (!validaLetras(valor.substring(5))){
								alert("La matrícula introducida no es correcta.");
								return(false);							
							}
						}else{
							if (valor.substring(5).length != 2){
								alert("La matrícula introducida no es correcta.");
								return(false);
							}
						}
					}
				}else{
					// a la primera posicion, que es una letra, no le sigue 4 números.
					alert("La matrícula introducida no es correcta.");
					return(false);
				}
			}		
		}else{
			alert("La matrícula introducida no es correcta.");
			return(false);
		}
	}
	return(true);
}//fin del validaMatricula

/**********************************************************************************************/
/**********************        Función que  valida si                  ************************/
/**********************  	  el e-mail es correcto                ************************/
/**********************************************************************************************/
function checkEmail(checkString1){
	var newstr = "";
	var at = false;
	var dot = false;
	checkString = checkString1.value;
    // Vemos si tiene '@'
    if (checkString.indexOf("@") != -1) {
		at = true;
    // Vemos si tiene '.'
	}
    else if (checkString.indexOf(".") != -1) {
		dot = true;
	}
    //
    for (var i = 0; i < checkString.length; i++) {
		ch = checkString.substring(i, i + 1)
		if ((ch >= "A" && ch <= "Z") || (ch >= "a" && ch <= "z")
			|| (ch == "@") || (ch == ".") || (ch == "_")
            || (ch == "-") || (ch >= "0" && ch <= "9")) {
            newstr += ch;
            if (ch == "@") {
				at=true;
			}
			if (ch == ".") {
                dot=true;
			}
		}
	}
	if ((at == true) && (dot == true)) {
        return newstr;
    }
    else {
       // Error
       alert ("La direccion de correo no tiene el formato adecuado.");
       //checkString1.focus();
       //return checkString;
       return false;
    }
}

///////////////////////////********************************
/**********************************************************************************************/
/**********************        Función que  valida si                  ************************/
/**********************  	  el e-mail es correcto                ************************/
/**********************************************************************************************/
function validEmail(email) {
//        return ( !(email.indexOf("@") == -1) )

	var newstr = "";
	var at = false;
	var dot = false;
	var checkString = email;
    // Vemos si tiene '@'
    if (checkString.indexOf("@") != -1) {
		at = true;
    // Vemos si tiene '.'
	}
    else if (checkString.indexOf(".") != -1) {
		dot = true;
	}
    //
    for (var i = 0; i < checkString.length; i++) {
		ch = checkString.substring(i, i + 1)
		if ((ch >= "A" && ch <= "Z") || (ch >= "a" && ch <= "z")
			|| (ch == "@") || (ch == ".") || (ch == "_")
            || (ch == "-") || (ch >= "0" && ch <= "9")) {
            newstr += ch;
            if (ch == "@") {
				at=true;
			}
			if (ch == ".") {
                dot=true;
			}
		}
	}
	if ((at == true) && (dot == true)) {
        return newstr;
    }
    else {
       //alert ("La direccion de correo no tiene el formato adecuado.");
       //checkString1.focus();
       //return checkString;
       return false;
    }
}


function validaFechaPost(fechaIni,dia2,mes2,anio2)
{       
        var dia1  = fechaIni.substring(0,2);

   var mes1 = fechaIni.substring(3,5);

   var anio1 = fechaIni.substring(6);

        var fx_ini= dia1+ mes1+ anio1;
                                
    var dia2  = dia2;

  var mes2 = mes2;

  var anio2 = anio2;

        var fx_fin= dia2+ mes2+ anio2;
                                
if(dia1 && anio1 && mes1 && mes2 && dia2 && anio2)
{
        if(parseInt(anio2)>parseInt(anio1))
                {
                return(false);
                }               
        else if(parseInt(anio1,10)==parseInt(anio2,10))
                {

                if (parseInt(mes2,10)>parseInt(mes1,10))
                        {
                        return(false);
                        }
                else if(parseInt(mes2,10)==parseInt(mes1,10))
                        {
                        if(parseInt(dia2,10)>parseInt(dia1,10))
                                {
                                return(false);
                                }
                        else if(parseInt(dia2,10)==parseInt(dia1,10))
                                {
                                return(true);
                                }
                        }
                }//fin  del if inicial 
 }//fin del if que me dice que existen esos campos de txt
return(true);
}//fin de la funcion validaFechaPost

function GetSelectText( selectObject ) {
        // Validate parameter value
        if (selectObject == null)
                return null;
        
        if (selectObject.selectedIndex+"" == "undefined" || 
                                selectObject.selectedIndex == null ||
                                selectObject.selectedIndex < 0)
                return null;

        return selectObject.options[selectObject.selectedIndex].text;
}

function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}
function getEdadAport(dateString) {

     var now = new Date();
     var today = new Date(now.getYear(),now.getMonth(),now.getDate());

     var yearNow = now.getYear();

     if (yearNow.toString().length==4){
	yearNow=yearNow-1900;
     }

     var monthNow = now.getMonth();

     var dateNow = now.getDate();


     var dob = new Date(dateString.substring(6,10),
                             dateString.substring(3,5)-1,
                             dateString.substring(0,2));

     var yearDob = dob.getYear();

     yearAge = yearNow - yearDob;


     return yearAge;
}


/*******************************************************************************/
// FUNCIÓN PARA VALIDAR UN CIF QUE SE LLAMA DESDE LA VALIDACIÓN DEL NIF 
/*******************************************************************************/


function validaCIF(F) 
{
  
  var v1 = new Array(0,2,4,6,8,1,3,5,7,9);
  var v2 = new Array('j','a','b','c','d','e','f','g','h','i'); 
  var v3 = new Array('J','A','B','C','D','E','F','G','H','I'); 
  var temp = 0; 
  var temp1;

  
  for( i = 2; i <= 6; i += 2 ) 
    {
      temp = temp + v1[ parseInt(F.substr(i-1,1)) ];
      temp = temp + parseInt(F.substr(i,1));
    };

  temp = temp + v1[ parseInt(F.substr(7,1)) ];

  temp = (10 - ( temp % 10));

  	//El último dígito ha de ser igual al dígito de control calculado (temp) o su análogo en letra (a=1, b=2,..,j=0 ó 10)
	if (temp == 10) temp = 0;
	if (temp != F.charAt(8) && F.charAt(8) != v2[temp] && F.charAt(8) != v3[temp] ){
	alert( "El cif no es válido");
	return(-55);
	}			 	
}

//fin validaCIF
function validaId(txtCodId){
	if(txtCodId.value == ""){
				return false;}else {
				  if (txtCodId.value.length==10){
					if(txtCodId.value.substring(0,1)=="0"){
						txtCodId.value=txtCodId.value.substring(1);
					}else{
					return false;}
				 }				
				 var re="";
				 var resultado=validarDNI(txtCodId.value.toUpperCase());
				 var resultado2="";
				 
					 if (parseInt(resultado)>=0){ 
							if (parseInt(resultado)==1){					
									resultado2=compruebaLetraDNI2(txtCodId.value.toUpperCase());		
							   	if (parseInt(resultado2)=="1"){	
							   		if (txtCodId.value.length<10){
											for(i=0;i<10-txtCodId.value.length;i++){
												re="0"+re;
											}
											txtCodId.value=re+txtCodId.value.toUpperCase();		
										}
									}	
									else if(parseInt(resultado2)=="0"){	
						   			txtCodId.value = NIF;
										if (txtCodId.value.length<10){
											for(i=0;i<10-txtCodId.value.length;i++){
												re="0"+re;
											}
											txtCodId.value=re+txtCodId.value.toUpperCase();		
										}
									}						
									else if(parseInt(resultado2)=="2"){	
						   			txtCodId.value = NIF;
										if (txtCodId.value.length<10){
											for(i=0;i<10-txtCodId.value.length;i++){
												re="0"+re;
											}
											txtCodId.value=re+txtCodId.value.toUpperCase();		
										}
									}else if(parseInt(resultado2) ==-1){
													fijarAtencion(txtCodId);
													return false;}						
							}else if (parseInt(resultado)==2){													
									if(!compruebaCIF(txtCodId.value)) return false;if (txtCodId.value.length<10){
										//Componemos el CIF correctamente para poder enviarlo al host de vida.
										var cadena =  txtCodId.value.toUpperCase();
										var cadena2 = cadena.substr(1,cadena.length-1);
										var cadena1="0"+cadena.substr(0,1);
										for(i=0;i<8-cadena2.length;i++){
											cadena2 = "0"+cadena2;
										}
										cadena = cadena1 + cadena2;	
										txtCodId.value=cadena;							
									}	
						}else if(parseInt(resultado)==9){
						
						var cadena = txtCodId.value.toUpperCase();
						cadena = cadena.substr(1,9);
						resultado2=compruebaLetraDNI2(cadena);		
							   	if (parseInt(resultado2)=="1"){	
							   		if (txtCodId.value.length<10){
											for(i=0;i<10-txtCodId.value.length;i++){
												re="0"+re;
											}
											txtCodId.value=re+txtCodId.value.toUpperCase();		
										}
									}	
									else if(parseInt(resultado2)=="0"){
						   			//txtCodId.value = NIF;
										if (txtCodId.value.length<10){
											for(i=0;i<10-txtCodId.value.length;i++){
												re="0"+re;
											}
											txtCodId.value=re+txtCodId.value.toUpperCase();
										}
									}						
									else if(parseInt(resultado2)=="2"){	
						   			txtCodId.value = NIF;
										if (txtCodId.value.length<10){
											for(i=0;i<10-txtCodId.value.length;i++){
												re="0"+re;
											}
											txtCodId.value=re+txtCodId.value.toUpperCase();		
										}
									}else if(parseInt(resultado2) == "-1"){
									txtCodId.focus();	
									return false;}																							
						}else{
									return false;}						
					}else{
						return false;}				
				}
		return true;
	}
function validaIdFisica(txtCodId){
	if(txtCodId.value == ""){
				alert("Por favor, rellene el código de identificación.");
				fijarAtencion(txtCodId);
				return false;}else {
				  if (txtCodId.value.length==10){
					if(txtCodId.value.substring(0,1)=="0"){
						txtCodId.value=txtCodId.value.substring(1);
					}else{
						alert("Por favor introduzca un DNI correcto" );
						fijarAtencion(txtCodId);
					return false;}
				 }				
				 var re="";
				 var resultado=validarDNI(txtCodId.value.toUpperCase());
				 var resultado2="";
				 
					 if (parseInt(resultado)>=0){ 
							if (parseInt(resultado)==1){					
									resultado2=compruebaLetraDNI2(txtCodId.value.toUpperCase());		
							   	if (parseInt(resultado2)=="1"){	
							   		if (txtCodId.value.length<10){
											for(i=0;i<10-txtCodId.value.length;i++){
												re="0"+re;
											}
											txtCodId.value=re+txtCodId.value.toUpperCase();		
										}
									}	
									else if(parseInt(resultado2)=="0"){	
						   			txtCodId.value = NIF;
										if (txtCodId.value.length<10){
											for(i=0;i<10-txtCodId.value.length;i++){
												re="0"+re;
											}
											txtCodId.value=re+txtCodId.value.toUpperCase();		
										}
									}						
									else if(parseInt(resultado2)=="2"){	
						   			txtCodId.value = NIF;
										if (txtCodId.value.length<10){
											for(i=0;i<10-txtCodId.value.length;i++){
												re="0"+re;
											}
											txtCodId.value=re+txtCodId.value.toUpperCase();		
										}
									}else if(parseInt(resultado2) ==-1){
													fijarAtencion(txtCodId);
													return false;}						
							}else if (parseInt(resultado)==2){	
								alert("El NIF debe corresponder a una persona física.");
								fijarAtencion(txtCodId);
								return;	
						}else if(parseInt(resultado)==9){
						
						var cadena = txtCodId.value.toUpperCase();
						cadena = cadena.substr(1,9);
						resultado2=compruebaLetraDNI2(cadena);		
							   	if (parseInt(resultado2)=="1"){	
							   		if (txtCodId.value.length<10){
											for(i=0;i<10-txtCodId.value.length;i++){
												re="0"+re;
											}
											txtCodId.value=re+txtCodId.value.toUpperCase();		
										}
									}	
									else if(parseInt(resultado2)=="0"){
						   			//txtCodId.value = NIF;
										if (txtCodId.value.length<10){
											for(i=0;i<10-txtCodId.value.length;i++){
												re="0"+re;
											}
											txtCodId.value=re+txtCodId.value.toUpperCase();
										}
									}						
									else if(parseInt(resultado2)=="2"){	
						   			txtCodId.value = NIF;
										if (txtCodId.value.length<10){
											for(i=0;i<10-txtCodId.value.length;i++){
												re="0"+re;
											}
											txtCodId.value=re+txtCodId.value.toUpperCase();		
										}
									}else if(parseInt(resultado2) == "-1"){
									txtCodId.focus();	
									return false;}																							
						}else{
									alert("Por favor introduzca un DNI correcto");
									fijarAtencion(txtCodId);
									return false;}						
					}else{	
						alert("Por favor introduzca un DNI correcto");
						fijarAtencion(txtCodId);
						return false;}				
				}
		return true;
	}
function comasPuntos(s) {
  return s.replace(/\,/g, ".");
}	

/**********************************************************************************/
/******************  Función que rellena con ceros a tantas posi ******************/
/******************  ciones como indica el campo pos, por la izqda ****************/
/**********************************************************************************/
function rellenarCeros(valor,pos){
	var longitud = valor.length;
	var resultado = valor;
	for(k=0;k<pos-longitud;k++){
		resultado = "0"+resultado;
	}
	return resultado;
}

function compruebaCIF(F) 
{
	//si tiene un cero a la izquierda lo eliminamos
	var len = F.length;	
  	if (len==10 && F.substr(0,1)=='0') F = F.substr(1,10);
  	
  	// pasar a mayúsculas
	var value = F.toUpperCase();

	//comprobación del formato
	if (!/^[A-Za-z0-9]{9}$/.test(value)) // Son 9 dígitos?
		return false;
	else if (!/^[ABCDEFGHKLMNPQS]/.test(value)) 	// Es una letra de las admitidas ?
		return false;

 	var v1 = new Array(0,2,4,6,8,1,3,5,7,9);
  	var v2 = new Array('j','a','b','c','d','e','f','g','h','i'); 
  	var v3 = new Array('J','A','B','C','D','E','F','G','H','I'); 
  	var temp = 0; 
  	var temp1;

  
  	for( i = 2; i <= 6; i += 2 ) 
    {
      	temp = temp + v1[ parseInt(F.substr(i-1,1)) ];
      	temp = temp + parseInt(F.substr(i,1));
    };

  	temp = temp + v1[ parseInt(F.substr(7,1)) ];

  	temp = (10 - ( temp % 10));

  	//El último dígito ha de ser igual al dígito de control calculado (temp) o su análogo en letra (a=1, b=2,..,j=0 ó 10)
	if (temp == 10) temp = 0;
	if (temp != F.charAt(8) && F.charAt(8) != v2[temp] && F.charAt(8) != v3[temp] ){
		return false;
	}	else {
		return true;		 	
	}
}

function validaNIE(txtCodId)
{
	var F = txtCodId.value;
	var result = false;
	var len = F.length;
  	if (len==10 && F.substr(0,1)=='0') F = F.substr(1,10);
	if (F.substr(0,1).toUpperCase()=='X') // puede ser un NIE
	{
		result = validaId(txtCodId,"NIE"); 
		len = F.length;
		if (len==10) F = F.substr(1,10);
	} 
	return result;
}

function validaNIF(txtCodId)
{
	var F = txtCodId.value;
	var result = false;
	var len = F.length;

  	if (len==10 && F.substr(0,1)=='0') F = F.substr(1,10);
	if (F.substr(0,1).toUpperCase()!='X') 
	{
		result = validaId(txtCodId,"NIF");
		len = F.length;
		if (len==10) F = F.substr(1,10);
	}	
	return result;
}
