function valFechaCastellano(v){
	if(v != ""){
		if(v.length < 10)return false;
		
		//dia=parseInt(v.substring(0,2),10);
		//mes=parseInt(v.substring(3,5),10);
		//anio=parseInt(v.substr(6),10);		

		dia=v.substring(0,2);
		mes=v.substring(3,5);
		anio=v.substr(6);		
		if ( !isFinite(anio) || !isFinite(mes) || !isFinite(dia))return false;
		if ( anio > 2100 || anio < 1900 ) return false;	
		if (mes < 1 || mes > 12) return false;
		if (dia < 1)return false;
				
		if (mes == 1 || mes == 3 || mes == 5 || mes == 7 || mes == 8 || mes == 10 || mes == 12){
			//meses de 31 dias
			if (dia > 31) return false;	
		}else{
			if (mes == 2 && anio % 4 == 0){
				if (dia > 29) 
					return false;
				else if (anio % 4 != 0)
					if (dia > 28)return false
			}else if(mes == 2 && anio % 4 != 0){
				if (dia > 28) return false
			}else{
				if (dia > 30)return false
			}
		}		
	}	
	return true;
}

function valFechaEuskera(v){
	if(v != ""){
		if(v.length < 10)return false;
		
		//dia=parseInt(v.substring(0,2),10);
		//mes=parseInt(v.substring(3,5),10);
		//anio=parseInt(v.substr(6),10);		

		dia=v.substring(8);
		mes=v.substring(5,7);
		anio=v.substr(0,4);				
		if ( !isFinite(anio) || !isFinite(mes) || !isFinite(dia))return false;
		if ( anio > 2100 || anio < 1940 ) return false;	
		if (mes < 1 || mes > 12) return false;
		if (dia < 1)return false;
				
		if (mes == 1 || mes == 3 || mes == 5 || mes == 7 || mes == 8 || mes == 10 || mes == 12){
			//meses de 31 dias
			if (dia > 31) return false;	
		}else{
			if (mes == 2 && anio % 4 == 0){
				if (dia > 29) 
					return false;
				else if (anio % 4 != 0)
					if (dia > 28)return false
			}else if(mes == 2 && anio % 4 != 0){
				if (dia > 28) return false
			}else{
				if (dia > 30)return false
			}
		}		
	}	
	return true;
}
function gfComprobarFechaC(pfecha){
	if (valFechaCastellano(pfecha.value)==false) {
		alert("No es una fecha válida.\nFormato correcto: dd/mm/aaaa");
		pfecha.value="";
		pfecha.focus();
		return false;
	}
	else{
		return true;
	}
}
function gfComprobarFechaE(pfecha){
	if (valFechaEuskera(pfecha.value)==false) {
		alert("Datak ez dauka formatu ona.\nFormatu ona: aaaa/mm/dd");
		//pfecha.value="";
		pfecha.focus();
		return false;
	}
	else{
		return true;
	}
}

function ComprobarNumero(pValor, pIdioma){
	var devolver=true;
	pnumero=pValor.value;
	if (!isFinite(pnumero)){
		devolver=false;
	}
	
	if(pnumero!="" && pnumero!=0){
		for(i=0;i<pnumero.length;i++){
			if(pnumero.charAt(i)!="" && pnumero.charAt(i)!="," && pnumero.charAt(i)!=".")vale=isFinite(pnumero.charAt(i));
			if(vale==false) devolver=false;
		}
	}		
	if (devolver==false){
		if (pIdioma =='E') {
			alert("Balio sartua ez da baliozkoa.")
		}else{
			alert("El valor introducido no es válido.");
		}
		pValor.focus();
	}
	return devolver;
}

function Fichero(ruta,cAdjunto,cRutaRel,cCarpeta){ //Abre el formulario de adjuntar fichero
	if (cCarpeta!="") {			
		var fichero = "../Fichero.asp?Func=1&cRuta="+ruta+"&cAdjunto="+cAdjunto+"&cRutaRel="+cRutaRel+"&cCarpeta="+cCarpeta	
	}else {			
		var fichero = "../Fichero.asp?Func=1&cRuta="+ruta+"&cAdjunto="+cAdjunto+"&cRutaRel="+cRutaRel	
	}
	var ventana=window.open(fichero,'seleccion','top=50,left=100,width=418,height=250');
	if (ventana.opener==null){
		ventana.opener=this;
	}
}
//función que ejecuta un trim a un string
function trim(argvalue) {
  var tmpstr = ltrim(argvalue);

  return rtrim(tmpstr);
}

//función que ejecuta un trim por la izquierda a un string
function ltrim(argvalue) {

  while (1) {
    if (argvalue.substring(0, 1) != " ")
      break;
    argvalue = argvalue.substring(1, argvalue.length);
  }

  return argvalue;
}
//función que ejecuta un trim por la derecha a un string
function rtrim(argvalue) {

  while (1) {
    if (argvalue.substring(argvalue.length - 1, argvalue.length) != " ")
      break;
    argvalue = argvalue.substring(0, argvalue.length - 1);
  }
  return argvalue;
}

function CompararFechasCastellano(FechaInicio,FechaFin){
  //fecha_actual = new Date();
  dia_fecha_inicio=FechaInicio.value.substr(0,2);
  mes_fecha_inicio=FechaInicio.value.substr(3,2);
  ano_fecha_inicio=FechaInicio.value.substr(6,4);
  vfecha_inicio=mes_fecha_inicio+"/"+dia_fecha_inicio+"/"+ano_fecha_inicio
  fecha_inicio=new Date(vfecha_inicio);
  
  dia_fecha_fin=FechaFin.value.substr(0,2);
  mes_fecha_fin=FechaFin.value.substr(3,2);
  ano_fecha_fin=FechaFin.value.substr(6,4);
  vfecha_fin=mes_fecha_fin+"/"+dia_fecha_fin+"/"+ano_fecha_fin
  fecha_fin=new Date(vfecha_fin);
  
	var tiempoRestante=fecha_fin.getTime()-fecha_inicio.getTime();
	var dias = Math.floor(tiempoRestante / (1000 * 60 * 60 * 24));
	if (dias<=-1){
		return false;
	}
	else {
		return true;
	}
  }
  
  function CompararFechasEuskera(FechaInicio,FechaFin){
  //fecha_actual = new Date();
  dia_fecha_inicio=FechaInicio.value.substr(8,2);
  mes_fecha_inicio=FechaInicio.value.substr(5,2);
  ano_fecha_inicio=FechaInicio.value.substr(0,4);
  vfecha_inicio=mes_fecha_inicio+"/"+dia_fecha_inicio+"/"+ano_fecha_inicio
  fecha_inicio=new Date(vfecha_inicio);
  
  dia_fecha_fin=FechaFin.value.substr(8,2);
  mes_fecha_fin=FechaFin.value.substr(5,2);
  ano_fecha_fin=FechaFin.value.substr(0,4);
  vfecha_fin=mes_fecha_fin+"/"+dia_fecha_fin+"/"+ano_fecha_fin
  fecha_fin=new Date(vfecha_fin);
  
  var tiempoRestante=fecha_fin.getTime()-fecha_inicio.getTime();
  var dias = Math.floor(tiempoRestante / (1000 * 60 * 60 * 24));
      
  if (dias<=-1){
  	return false;
  }
  else {
  	return true;
  }
  
  }
function over(elemento){
	elemento.style.textDecoration='none';
	elemento.style.color='#003366'
}
function out(elemento){
	elemento.style.textDecoration='none';
	elemento.style.color='#005CD0'
}
function hideSelect(){
	if (document.all){document.all.formselect.style.visibility="hidden";}
}

function unhideSelect(){
	if (document.all){document.all.formselect.style.visibility="visible";}
}

function validarTelefono(valor) {
	if (valor != "") {
	  if (/^[0-9]{9,15}$/.test(valor)){
		return (true);
	  } else {
		return (false);
	  }
	}  
}
function gfValidarEmail(valor) {
	if (valor != "") {
		  if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(valor)){
		return (true);
	  } else {
		return (false);
	  }
	}  
}
function gfValidarFactura(valor, pidioma) {
	if (valor != "") {
		if (/^[V|C|R]\d{5}\/\d{4}$/.test(valor.value)){
			return(true);
	  	}else{
			if (pIdioma =='E') {
				alert("Fakturaren formatua ez da zuzena.")
			}else{
				alert("El formato de la factura no es correcto.");
			}
	  	}
	}  
}
function validarEmail(valor) {
	if (valor != "") {
		  if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(valor)){
		return (true);
	  } else {
		return (false);
	  }
	}  
}
function validarCodigoPostal(valor) {
	if (valor != "") {
	  if (/^[0-9]{5}$/.test(valor)){
		return (true);
	  } else {
		return (false);
	  }
	}  
}
// comprobar numero
function ComprobarNumeroDNI(pValor){
	
	var TablaNumeros = "0123456789"
	if (TablaNumeros.indexOf(pValor) != -1){           
    	return true;
    }else {
		return false;
	}
	
}
// Validar DNI
function gfCalculoLetraDNI(dni){
	var TablaLetras = "TRWAGMYFPDXBNJZSQVHLCKE";
	var numero;
	var aux;

	if (trim(dni + "") == ""){	
		return "";
	}	

	numero = "0" + "" + dni;
	
	if  (numero < 23){ 		
		return "";
	}
	
	numero = numero % 23 
	aux = TablaLetras.substring(numero,numero+1) 

	return aux;
}

//Comprobar DNI Castellano
function gfComprobarDNI(dni) {  //dni es el control con el valor, y no el numero a validar
	
	var devolver = true;
	var Indice;
	var strNumero = "";
	var strLetra = "";
	var Caracter;
	var dniValor = dni.value;
	var TablaLetras = "TRWAGMYFPDXBNJZSQVHLCKE";
	
	//Comprobamos si tiene 9 digitos
	if (dniValor.length != 9) {  //No tiene 9
		devolver = false;
	}else { //Si tiene 9
		//Los 8 primeros son numeros
		for (Indice = 0; Indice < 8; Indice++) {
			Caracter = dniValor.substring(Indice, Indice + 1);
			if (ComprobarNumeroDNI(Caracter)){			
				strNumero = strNumero + "" + Caracter;
			}else{
				devolver=false;
			}
		}
		//EL 9º digito es una letra
		Caracter = dniValor.substring(8, 9);
		if (TablaLetras.indexOf(Caracter) != -1){ 
			strLetra = Caracter;
		}else{
			devolver = false;
		}
		//Vemos si la letra es la correcta
		if (gfCalculoLetraDNI(strNumero) != strLetra){
			devolver = false;
		}
	}
	return devolver;
}

//Validar CIF Castellano
function gfComprobarCIF(cif) //cif es el control que contiene el cif, no es el valor
{
  var correcto = false;
 
  var v1 = new Array(0,2,4,6,8,1,3,5,7,9); 
  var cifTemp;
  var temp = 0; 
  var digcontrol;
  var mensaje = "";
  var letraControl = new Array('A','B','C','D','E','F','G','H','I','J');

  cifTemp = cif.value.toUpperCase(); // pasar a mayúsculas

  if (!/^[A-Za-z0-9]{9}$/.test(cifTemp))  // Son 9 dígitos? 
    mensaje = "Longitud incorrecta, un CIF consta de 9 dígitos";
  else if (!/^[ABCDEFGHKLMNPQS]/.test(cifTemp)) // Es una letra de las admitidas ?
    mensaje = "El primer dígito es incorrecto, debe ser una letra de las siguientes: A,B,C,D,E,F,G,H,K,L,M,N,P,Q,S";
  else {
	//Comprobamos que la cadena forma un CIF válido
	digcontrol = cif.value.substr(8,1)
	
    for( i = 2; i <= 6; i += 2 ) 
      {
        temp = temp + v1[ parseInt(cif.value.substr(i-1,1)) ];
        temp = temp + parseInt(cif.value.substr(i,1));
      };

    temp = temp + v1[ parseInt(cif.value.substr(7,1)) ];

    temp = (10 - ( temp % 10));
	
	//alert('Resultado: ' + temp);
	//alert('Digito Control: ' + digcontrol);
	//alert('Letra correspondiente al resultado: ' + letraControl[temp-1]);
	
    if (temp == 10){
	//alert( "El dígito de control es: J ó 0" );
	  if (digcontrol == "J" || digcontrol == "0") {
	    correcto = true;
	  }
	}
	else {
    //alert( "El dígito de control es: "+temp ); 
	  if (digcontrol == temp || digcontrol == letraControl[temp-1]) {
	    correcto = true;
  	  }
    }
  }

  if (correcto == true) {
	//document.forms['SolicitudOCJIE'].txtCIF.value = cif.value
  } else {
  		if (mensaje == '') {
		    //alert("El campo CIF no tiene el formato correcto. Por favor, revíselo.")
			correcto = false;
		} else {
			//alert(mensaje);
			correcto = false;
		}
	cif.focus();
	}
  return correcto;
}

//Comprobar NIE Castellano
function gfComprobarNIE(nie) {  //nie es el control con el valor, y no el numero a validar
	
	var devolver = true;
	var Indice;
	var strNumero = "";
	var strLetra = "";
	var Caracter;
	var nieValor = nie.value;
	var TablaLetras = "TRWAGMYFPDXBNJZSQVHLCKE";
	
	if (nieValor.length == 10) {  //Tiene 10

		//EL 1º digito es una X
		Caracter = nieValor.substring(0, 1);
		Caracter = Caracter.toUpperCase();
		if ("X" != Caracter){ 
			devolver = false;
		}

		//Los 8 siguientes son numeros
		for (Indice = 1; Indice < 9; Indice++) {
			Caracter = nieValor.substring(Indice, Indice + 1);
			if (ComprobarNumeroDNI(Caracter)){			
				strNumero = strNumero + "" + Caracter;
			}else{
				devolver=false;
			}
		}
		
		//EL 10º digito es una letra
		Caracter = nieValor.substring(9, 10);
		if (TablaLetras.indexOf(Caracter) != -1){ 
			strLetra = Caracter;
		}else{
			devolver = false;
		}
		
		//Vemos si la letra es la correcta
		if (gfCalculoLetraDNI(strNumero) != strLetra){
			devolver = false;
		}
		
	}else {
		devolver = false;
	}
	return devolver;
}

//comprombar que el número de cuenta es valido
function obtenerDigito(valor){
  valores = new Array(1, 2, 4, 8, 5, 10, 9, 7, 3, 6);
  control = 0;
  for (i=0; i<=9; i++)
    control += parseInt(valor.charAt(i)) * valores[i];
  control = 11 - (control % 11);
  if (control == 11) control = 0;
  else if (control == 10) control = 1;
  return control;
}

function numerico(valor){
  cad = valor.toString();
  for (var i=0; i<cad.length; i++) {
    var caracter = cad.charAt(i);
	if (caracter<"0" || caracter>"9")
	  return false;
  }
  return true;
}

function validar(banco, sucursal, dc, cuenta) {
  if (banco == ""  || sucursal == "" || dc == "" || cuenta == "")
    //alert("Por favor, introduzca los datos de su cuenta");
	return false;
  else {
    if (banco.length != 4 || sucursal.length != 4 ||dc.length != 2 || cuenta.length != 10)
      //alert("Por favor, introduzca correctamente los datos de su cuenta. No están completos");
	  return false;
    else {
      if (!numerico(banco) || !numerico(sucursal) ||!numerico(dc) || !numerico(cuenta))
        //alert("Por favor, introduzca correctamente los datos de su cuenta. No son numéricos");
		return false;
      else {
        if (!(obtenerDigito("00" + banco + sucursal) ==
              parseInt(dc.charAt(0))) || 
            !(obtenerDigito(cuenta) ==
              parseInt(dc.charAt(1))))
          //alert("Los dígitos de control no se corresponden con los demás números de la cuenta");
		  return false;
	    else
          return true;
      }
    }
  }
}

function gfValidarFloat(value){
	return(value.match(/^[0-9]+(,[0-9]+)?$/))
}

function gfValidarCampoFloat(pCampo,pIdioma){
	if(pCampo.value!=""){
		if(!gfValidarFloat(pCampo.value)){
			if (pIdioma =='E') {
				alert(pCampo.value + " ez da datu baliozkoa");
			}else{
				alert(pCampo.value + " no es un valor válido");
			}
			try{
				pCampo.focus();
				pCampo.select();				
			}catch(ex){
			   /* nada, porque la excepción se producirá en caso de que al control no se le pueda pasar el foco */
			}
			return(false);
		}
		return(true);
	}
}
