//PRIVADO

	function aceptar (n) {
		 for (i=0;i<document.frm.elements.length;i++){
            if (document.frm.elements[i].type == "text" || document.frm.elements[i].type == "password"){
				//alert(document.frm.elements[i].value.indexOf("_") )
				if ( document.frm.elements[i].value.indexOf("'") == "-1" && document.frm.elements[i].value.indexOf(" ") == "-1" && document.frm.elements[i].value.indexOf("-") == "-1" ){
					//alert(document.frm.elements[i].value.indexOf("'") )
					//alert ("dentro")
					document.frm.Accion.value = n;	
					document.frm.submit();
				}else{
					//alert (document.frm.elements[i].value);
					document.frm.Accion.value = n;
					document.frm.elements[i].value = "";
					document.frm.elements[i].value = "";
					document.frm.submit();
			
				}
            }
        }
	}

/*
	function aceptar (n) {
		
		if ( document.frm.clave.value.indexOf("'") == "-1" && document.frm.clave.value.indexOf(" ") == "-1" && document.frm.clave.value.indexOf("-") == "-1" ){
			//alert(document.frm.clave.value.indexOf("'") )
			//alert ("dentro")
			document.frm.Accion.value = n;
			document.frm.submit();
		}else{
			//alert (document.frm.usuario.value);
			document.frm.Accion.value = n;
			document.frm.usuario.value = "";
			document.frm.clave.value = "";
			document.frm.submit();
			
		}
		
	}
*/
/******************************************************************
	Validaciones sobre un formulario
	Ej.
	<input type=text name=a value='' validacion='#NOBLANCO#MAYUSCULAS' nombre="campo a">

	#NOBLANCO -> el campo no puede estar en blanco
	#MAYUSCULAS -> Pasar a mayúsculas antes de hacer submit
	#NUMERO -> el campo es un valor numérico válido o cero si está en blanco
	#TAMAÑO -> valor de caracteres máximo que puede tener un campo
	#FECHA -> fecha válida en formato 'd/m/y'
	#HORA -> Hora válida en formato 'h:m'
	#HORA_SINLIMITE -> para horas de más de 24 (duración curso, etc).
	#NIF ->	 numero+letra, comprueba nif válido, pasa la letra a mayúsculas, quita puntos, espacios o guiones
	#EMAIL -> comprueba el patrón de un email válido texto@servidor.dominio
*******************************************************************/
function BRKFind(n, d) {
	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 = BRKFind(n,d.layers[i].document);
	if(!x && document.getElementById) x=document.getElementById(n); return x;
}

function Validar(idForm){
	
	var tError = "";
    var numveces = 0;
    var theForm;
    
    if (!idForm){
		theForm = document.forms[0];
    }
    else{
		theForm = BRKFind(idForm);
    }
	for (i=0;i<theForm.elements.length;i++){
		obj = theForm.elements[i];
		validacion = "";
		nom = obj.name;
		valor = obj.value;
		if (obj.type){ tipo = obj.type; } else { tipo = ""; }
		//---------- para los botones de radio -----------
		if ( tipo == 'radio'){
			valor = "";
			for (jj=0;jj < document.all( obj.name ).length;jj++){
				if (document.all( obj.name )[jj].validacion){
					validacion = document.all( obj.name )[jj].validacion;
					if (document.all( obj.name )[jj].nombre){
						nom =  document.all( obj.name )[jj].nombre;
					}
				}
				if (document.all( obj.name )[jj].checked){
					valor = document.all( obj.name )[jj].value;
				}
			}
		} else {
			validacion = obj.validacion 
			if (obj.nombre){
				nom = obj.nombre;
			}
		}

		//------- Validar caracteres raros ----------
		aNoVale = new Array("'");// ,'"','<','>');
		for (contaNoVale=0;contaNoVale<aNoVale.length;contaNoVale++){
			if (valor.indexOf(aNoVale[contaNoVale])>=0 && tipo != 'hidden'){
				if (numveces==0){
					tError = tError + "No se admiten caracteres especiales: [" + "']";//+ '"' + ", ', <, >].\n";
				}
				numveces = numveces + 1;
				try{
					obj.focus();
					break;
				}
				catch(e){
					break;
				}
			}
		}

		if ((tError=='')&&(validacion)){
			TieneValor = (trim(valor) != "" )
			
			//-------
			if ((tError=='')&&(validacion.indexOf("#NOESPECIALES")>=0)&&(TieneValor)){
				
				aNoVale = new Array(".","-",",");// ,'"','<','>');
				for (contaNoVale=0;contaNoVale<aNoVale.length;contaNoVale++){
					if (valor.indexOf(aNoVale[contaNoVale])>=0 && tipo != 'hidden'){
						if (numveces==0){
							tError = tError + "No se admiten caracteres especiales: [" + " .  -  , " + "]";//+ '"' + ", ', <, >].\n";
						}
						numveces = numveces + 1;
						try{
							obj.focus();
							break;
						}
						catch(e){
							break;
						}
					}
				}
			}

			if ((tError=='')&&(validacion.indexOf("#NUMERO")>=0)&&(TieneValor)){
				valor = valor.replace(/,/g, "." );  //-- cambiar coma  por punto decimal
				if (isNaN(parseFloat(valor))) {
					tError = tError + "El campo [" + nom + "] debe ser un valor numérico válido.\n";
					obj.focus();
					break;
				} else {
					obj.value = parseFloat(valor);
				}
			}

			if ((tError=='')&&(validacion.indexOf("#NOBLANCO")>=0)&&(!TieneValor)){
				tError = tError + "El campo [" + nom + "] no puede estar en blanco.\n"					
				if(tipo!="hidden")obj.focus();
				break;
			}

			if ((tError=='')&&(validacion.indexOf("#CORREO")>=0)){				
				if (!TieneValor){
					tError = tError + "El campo [" + nom + "] no puede estar en blanco.\n"					
					if(tipo!="hidden")obj.focus();
					break;
				}
				if(valor.indexOf("@")<0){
					tError = tError + "El campo [" + nom + "] debe ser una dirección de correo válida.\n"
					if(tipo!="hidden") obj.focus();
					break;
				}
			}

			if ((tError=='')&&(validacion.indexOf("#MAYUSCULAS")>=0)&&(TieneValor) ) {
				obj.value = valor.toUpperCase();
			}
			if ((tError=='')&&(validacion.indexOf("#TAMAÑO(")>=0)&&(TieneValor) ) {
				x = validacion.substring(validacion.indexOf("#TAMAÑO(")+8);
				x = parseInt( x.substring( 0, x.indexOf(")")));
				if (valor.length > x){
					tError = "El campo [" + nom + "] debe tener un tamaño máximo de " + x + " caracteres, tamaño actual: " + valor.length + " caracteres.\n"
					break;
				}
			}
			if ((tError=='')&&(validacion.indexOf("#TAMMIN(")>=0)&&(TieneValor) ) {
				x = validacion.substring(validacion.indexOf("#TAMMIN(")+8);
				x = parseInt( x.substring( 0, x.indexOf(")")));
				if (valor.length < x){
					tError = "El campo [" + nom + "] debe tener un tamaño mínimo de " + x + " caracteres, tamaño actual: " + valor.length + " caracteres.\n"
					break;
				}
			}

			if ((tError=='')&&(validacion.indexOf("#HORA")>=0)&&(TieneValor)){
				tError = validHora( obj, true )
				if (tError != ''){
					tError = "Campo [" + nom + "] \n" + tError + "\n";
					obj.focus();
					break;
				}
			}

			if ((tError=='')&&(validacion.indexOf("#SINLIMITE_HORA")>=0)&&(TieneValor)){
				tError = validHora( obj, false )
				if (tError != ''){
					tError = "Campo [" + nom + "] \n" + tError + "\n";
					obj.focus();
					break;
				}
			}

			if ((tError=='')&&(validacion.indexOf("#FECHA")>=0)&&(TieneValor)){
				tError = validFecha( obj );
				if (tError != ''){
					tError = "Campo [" + nom + "] \n" + tError + "\n";
					obj.focus();
					break;
				}
			}

			if ((tError=='')&&(validacion.indexOf("#EMAIL")>=0)&&(TieneValor)){
				if ((valor.indexOf("@")<0)||(valor.lastIndexOf(".")<valor.indexOf("@"))||(valor.lastIndexOf(".")==(valor.length-1))){
					tError = "Campo [" + nom + "] \nNo es una dirección de correo electrónico válida\n";
					obj.focus();
					break;
				}
				var b=/^[^@\s]+@[^@\.\s]+(\.[^@\.\s]+)+$/;
				//devuelve verdadero si validacion OK, y falso en caso contrario   
				if (!b.test(valor)) {
					tError = "Campo [" + nom + "] \nNo es una dirección de correo electrónico válida...\n";
					obj.focus();
					break;
				}

			}

			if ((tError=='')&&(validacion.indexOf("#NIF")>=0)&&(TieneValor)){
				xnumero = "";
				xletra = "";
				for (k=0;k<valor.length;k++){
					xcar = valor.substring(k,k+1);
					if ( ",.:- ".indexOf( xcar )<0 ){
						if ( "0123456789".indexOf( xcar )>=0 ){
							xnumero += xcar;
						} else {
							xletra += xcar;
						}
					}
				}
				//---- quitar ceros iniciales
				ceroInicial = true;
				xnume = "";
				for (k=0;k<xnumero.length;k++){
					if (!((xnumero.substr(k,1)=='0')&&(ceroInicial))){
						ceroInicial = false;
						xnume += xnumero.substr(k,1);
					}
				}
				xnumero = xnume;
				obj.value = xnumero + xletra.toUpperCase();
				if (xletra!=''){
					xletra = xletra.toUpperCase();
					if (!ValidarNIF( parseInt(xnumero),xletra )){
						tError = "Campo [" + nom + "] \nLa letra del NIF no se corresponde con el número\n";
						obj.focus();
						break;
					} else {
						obj.value = xnumero + xletra;
					}
				}
			}

		}
	}
	if (tError != "" ){
		alert( tError );
		return false;
	} else {
		//document.forms[0].submit();
		return true;
	}
}


/*MODIFICACIONES PARA QUE FUNCIONES EN TODOS LOS NAVEGADORES*/
/*
//genera un array de objetos indicando en cada objeto que validaciones tiene
function valida(id,validacion,nombre)
{
	this.id=id;
	this.nombre=nombre;
	this.validacion=validacion;
	return this;
}
	
	
function ValidarTodos(aObj)
{
	var tError = "";
	
	for (i=0;i<aObj.length;i++){
		obj = findObj(aObj[i].id)
		if (aObj[i].validacion){
			if ((tError=='')&&(aObj[i].validacion.indexOf("#NUMERO")>=0)&&(obj.value!="")){
				if (isNaN(parseFloat(obj.value))) {
					tError = tError + "El campo [" + aObj[i].nombre + "] debe ser un valor numérico válido.\n"
					obj.focus();
				}
			}
			if ((tError=='')&&(aObj[i].validacion.indexOf("#NOBLANCO")>=0)&&(obj.value=="")){
				tError = tError + "El campo [" + aObj[i].nombre + "] no puede estar en blanco.\n"
				obj.focus();
			}
			if ((tError=='')&&(aObj[i].validacion.indexOf("#MAYUSCULAS")>=0)&&(obj.value!="")) {
			    obj.value = obj.value.toUpperCase();
				obj.focus();
			}
		}
	}
	if (tError != "" ){
		alert( tError );
		return false;
	} else {
		//document.forms[0].submit();
		return true;
	}
}

*/

//Encuentra un objeto dentro de una página
function findObj(n, d) { //v4.0
  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=findObj(n,d.layers[i].document);
  if(!x && document.getElementById) x=document.getElementById(n); return x;
}
/*FIN MODIFICACIONES*/

//SOLO DEJA INTRODUCIR NÚMEROS
function SoloNumeros(evento)
{
	var codigo;
	if(evento.which)
		codigo = evento.which
	else
		codigo = evento.keyCode	
	if(codigo < 48 || codigo > 57){
		if(evento.which)
			evento.which=0;
		else			
			evento.keyCode = 0;
		
		return false;		
	}
	return true;
}
//SÓLO PUEDEN ESCRIBIR LETRAS
function SoloLetras(evento)
{
	var codigo;
	if(evento.which)
		codigo = evento.which
	else
		codigo = evento.keyCode

	if((codigo < 65 || codigo >90) && (codigo < 97 || codigo >122))
	{
		evento.keyCode = 0;
		return false;		
	}		
	return true;
}

//NO PUEDEN ESCRIBIR # Para los campos dinámicos de la solicitud
function otrosDatos(evento)
{
	var codigo;
	if(evento.which)
		codigo = evento.which
	else
		codigo = evento.keyCode
			
	if(codigo==35)
	{
		evento.keyCode = 0;
		return false;		
	}		
	return true;
}

//---------- Eliminar blancos ------------
function ltrim ( s ){ return s.replace( /^\s*/, "" );  } 
function rtrim ( s ){ return s.replace( /\s*$/, "" ); } 
function  trim ( s ){ 
	if (!s){ s = ""; }
	return rtrim(ltrim(s)); 
} 

//------------- Comprueba que la letra del NIF corresponda al Número de DNI ----
function ValidarNIF( nmDni, dsLetra ){
var letraC;
var ValidarNIF_ok = true;
var LetrasNif = "TRWAGMYFPDXBNJZSQVHLCKET";
	if ((nmDni > 0) && (dsLetra) && (dsLetra != "") ){
		letraC = LetrasNif.substr( (nmDni % 23) , 1);
//alert((dsLetra!="") + "   " + (dsLetra.toUpperCase() != letraC) +  "   " + dsLetra.toUpperCase() + "  " + letraC );
		ValidarNIF_ok = ( (dsLetra!="") && (dsLetra.toUpperCase() == letraC) );
	}
	return (ValidarNIF_ok);	

}


/* --------------------------------------------------------------
         Validar Horas como textos
		 Devuelve un texto con el error o nada si es correcto
-------------------------------------------------------------- */
function validHora( objh, limite24 ){
	var ss, t, ok , ss, hms, ConSegundos;
	var vh = objh.value;
	var hh=0, mm=0;
	ok = false;
	t = '';
	hms = vh.split(":");
   //-------------------- argumentos -----------
	if (hms.length<2){
	   t = 'La hora es incorrecta';
	   ok = true;
	}
	if (hms.length>=1){ hh = StrtoInt( hms[0] ); }
	if (hms.length>=2){ mm = StrtoInt( hms[1] ); }
	ss = 0;
	ConSegundos = (hms.length > 2);
	if (ConSegundos){ ss = StrtoInt( hms[2] );}

   //------------------------- hora -------------
   if ((!ok)&&(limite24)){
      if (isNaN(hh) || (hh<0) || (hh>23)){
         t = 'La hora no es correcta (de 0 a 23)';
         ok = true;
      }
   }

   //------------------------- minutos -------------
   if (!ok){
      if (isNaN(mm) || (mm<0) || (mm>59)){
         t = 'Los minutos no son correctos (de 0 a 59)';
         ok = true;
      }
   }

   //------------------------- segundos ------------
   if (!ok){
      if (isNaN(ss) || (ss<0) || (ss>59)){
         t = 'Los segundos no son correctos (de 0 a 59)';
         ok = true;
      }
   }

   //--------------- ver resultado ----------------------
   if (ok){
		objh.focus();
   } else {
		mm = '' + mm;
		hh = '' + hh;
		ss = '' + ss;
		if (mm.length < 2){ mm = '0' + mm }
		if (mm.length < 2){ mm = '0' + mm }
		if (hh.length < 2){ hh = '0' + hh }
		if (hh.length < 2){ hh = '0' + hh }
		if (ss.length < 2){ ss = '0' + ss }
		if (ss.length < 2){ ss = '0' + ss }
		objh.value = hh + ':' + mm;
		if (ConSegundos){ objh.value = objh.value + ':' + ss; }
   }
   return( t );
}


/* --------------------------------------------------------------
         Validar Fechas como textos
		 Devuelve una cadena con el error o vacía si esta ok.
-------------------------------------------------------------- */
function validFecha( objf ){
   var ss, t, ok, dd, mm, aa;
   var vf = objf.value;
   t = '';
   ok = false;
   ss = vf.split("/");
   //-------------------- argumentos -----------
   if( ss.length < 3 ){
      t = 'La fecha es incorrecta';
      ok = true;
   }
   for (ivalidFecha=0;ivalidFecha<ss.length;ivalidFecha++ ){
		if ((ss[ivalidFecha] != '')&&(ss[ivalidFecha].substr(0,1) == '0')){
			ss[ivalidFecha] = ss[ivalidFecha].substr(1);
		}
   }
   dd = parseInt(ss[0]);
   mm = parseInt(ss[1]);
   aa = parseInt(ss[2]);

   //------------------------- dia -------------
   if (!ok){
      if (isNaN(dd) || (dd<=0) || (dd>31)){
         t = 'El día de la fecha no es correcto ';
         ok = true;
      }
   }
   //------------------------- mes -------------
   if (!ok){
      if ( isNaN(mm) || (mm<=0) || (mm>12)){
         t = 'El mes de la fecha no es correcto';
         ok = true;
      }
   }
   //------------------------- año -------------
   if (!ok){
      if ( isNaN(aa) ){
         t = 'El año de la fecha no es correcto';
         ok = true;
      } else {
         if ( aa <= 50 ){
            aa = aa + 2000;
         }
         if ((aa>50) && (aa<100)){
            aa = aa + 1900;
         }
         objf.value = dd+'/'+mm+'/'+aa;
      }
   }

   //--------------- comprobar que existe la fecha ------
   if (!ok){
      vd1 = new Date( aa, mm-1, dd); 
      if ((vd1.getDate() != dd) || (vd1.getMonth()+1 != mm) || (vd1.getFullYear() != aa)){
         t = 'La fecha no es válida';
         ok = true;
      }
   }

   //--------------- ver resultado ----------------------
   if (ok){
      objf.focus();
   }
   // Colocamos la fecha al completo
   if (dd > 9){
	objf.value = dd.toString() + "/";
   }else{
	objf.value = "0" + dd.toString() + "/";
   }
   
   if (mm > 9){
	objf.value += mm.toString() + "/";
   }else{
	objf.value += "0" + mm.toString() + "/";
   }
   
   objf.value += aa;
      
   return( t );
}

function StrtoInt( x ){
	var n = 0;
	while (x.substring(0,1)=='0'){ x = x.substring(1,x.length); }
	if (x!=''){
		n = parseInt(x);
	}
	return (n);
}


//----------- pasar minutos a una hora válida ---------
function min2hora( iii ){
	var s = '', x, i, signo = '';
	i = parseInt(iii) ;
	if (i<0){ 
		signo = '-' 
		i = (-1) * i; 
	}

	s = Math.floor( (i / 60) );
	x = (i-(s*60));
	if (x<10){x='0'+x}
	s = s + ':'+x;
	return ( signo+s );
}

//----------- psara hora en formato hh:mm a minutos --------
function hora2min( x ){
   return( chora2min(  x.substr(0,2)+ '' + x.substr(3,2) ));
}

//----------- pasar número en formato hhmm a minutos ---------
function chora2min( i ){
	var h = 0;
	var m = 0;
	if ( parseInt(i/100, 10) > 0 ){
		h = parseInt(i/100,10);
	}
	var m = parseInt(i - (h*100),10);
	return( (h*60)+m );
}
