function IsEmail(str) 
{
	var r1
	var r2

  // are regular expressions supported?
  r1 = new RegExp("(@.*@)|(\\.\\.)|(@\\.)|(^\\.)");
	// Expresion regular inicial. Tragaba cualquier cosa al izq de la @
	// r2 = new RegExp("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,4}|[0-9]{1,4})(\\]?)$");
  r2 = new RegExp("^[a-zA-Z0-9\\-\\.\\_]+\\@(\\[?)[a-zA-Z0-9\\-\\.\\_]+\\.([a-zA-Z]{2,4}|[0-9]{1,4})(\\]?)$");
  return (!r1.test(str) && r2.test(str));
}

function ComprobarUsuario(CampoFormulario)
{
  var stUrl;
	var usuario = CampoFormulario.value;
// Validación Tamaño Usuario
	if ((usuario.length<6) ||(usuario.length>15))
	{
    alert("Por favor, indique un nombre de usuario de entre 6 y 15 caracteres."); 
    CampoFormulario.focus(); 
		return false;		
	}
// Caracteres validos
	if (!caracteresUserPwd(usuario))
	{
		alert("El usuario contiene caracteres no válidos.");
	  CampoFormulario.focus(); 
		return false;	
	}	
	stUrl = "/privada/includes/UsuarioRepetido.asp?Usuario="+usuario;
	msgwindow = window.open (stUrl,"UsuarioRepetido","height=400,width=500,top=20,left=20");
	return true;
}

function ComprobarEmail(CampoFormulario)
{
  var stUrl;
	var email = CampoFormulario.value;

// Validación Email
  if (email.length==0) 
  { 
    alert("Por favor, introduzca un e-mail."); 
    CampoFormulario.focus(); 
    return false; 
  }
	if (!IsEmail(email))
	{
		alert("El e-mail indicado es incorrecto. Por favor, introduzca un e-mail válido.");
		CampoFormulario.focus(); 
		return false;
	}
	stUrl = "/privada/includes/EmailRepetido.asp?Email="+email;
	msgwindow = window.open (stUrl,"EmailRepetido","height=400,width=500,top=20,left=20");
	return true;
}

function caracteresUserPwd(campo)
{
	var car="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
	for(a=0; a<campo.length; a++)
	{
		var b=campo.charAt(a);
		if (car.indexOf(b)==-1)
		{
			return false;
		}
	}
	return (true);
}

function caracteresTexto(campo)
{
	var car="ABCDEFGHIJKLMNÑOPQRSTUVWXYZÁÉÍÓÚ abcdefghijklmnñopqrstuvwxyzáéíóú1234567890-_.Çç";
	for(a=0; a<campo.length; a++)
	{
		var b=campo.charAt(a);
		if (car.indexOf(b)==-1)
		{
			return false;
		}
	}
	return (true);
}

function caracteresNumero(campo)
{
	var car="1234567890";
	for(a=0; a<campo.length; a++)
	{
		var b=campo.charAt(a);
		if (car.indexOf(b)==-1)
		{
			return false;
		}
	}
	return (true);
}

function EsNumero (vVariable){		// True  ( 23 / 12.5 / "23")  No acepta el 0 ni negativos
	if (isNaN(parseInt(vVariable)) || vVariable==0 || vVariable!=Math.abs(vVariable)) return (false)
    return !(isNaN(vVariable));		// False (0 / "" / "eew" / 12,3)
}

function ValidarDNI(nDNI){				//DNI o NIE
var cLetra,nLetra;
var bRetCode = false;

	nDNI=nDNI.replace(/\s/g,"");		//Quita espacios
	nDNI=nDNI.replace(/\./g,"");		//Quita puntos
	nDNI=nDNI.replace(/-/g,"");			//Quita guiones

	var nDNIfixed=nDNI;

	cLetra=nDNI.substring(0,1).toUpperCase();		//NIE
	if ((cLetra=="K" || cLetra=="L" || cLetra=="X")) {
		nDNI=nDNI.substring(1,nDNI.length)
		cLetra=nDNI.substring(nDNI.length-1,nDNI.length).toUpperCase();		//letra al final
//		nLetra = cLetra.charCodeAt(0)
		if(nLetra>=65 || nLetra<=90) nDNI=nDNI.substring(0,nDNI.length-1)
	}

 	if(EsNumero(nDNI) && (nDNI>=1 && nDNI<=99999999)) {
//		nDNI = Texto2Numero(nDNI)
		bRetCode=true;
		if (BuscaEnArray (g_a_sAutoCorregir,sNameForm) !=-1) eval ("oFormName."+sNameForm+".value=nDNIfixed")
	}
	return bRetCode;
}


function ValidarNIF(sNIF){
var a_cOrden = new Array ("T","R","W","A","G","M","Y","F","P","D","X","B","N","J","Z","S","Q","V","H","L","C","K","E","F") 
var cLetra,nLetra;
var bRetCode = false;

	sNIF=sNIF.replace(/\s/g,"");		//Quita espacios
	sNIF=sNIF.replace(/\./g,"");		//Quita puntos
	sNIF=sNIF.replace(/-/g,"");			//Quita guiones

	cLetra=sNIF.substring(sNIF.length-1,sNIF.length).toUpperCase();		//letra al final
	nLetra = cLetra.charCodeAt(0)
	if(nLetra<65 || nLetra>90) {
		cLetra=sNIF.substring(0,1).toUpperCase();		//o al principio
		sNIF  = sNIF.substring(1,sNIF.length);			//sino falla Texto2Numero
	}
	nLetra = cLetra.charCodeAt(0)
	if(nLetra>=65 && nLetra<=90) {
		nNIF = Texto2Numero(sNIF)
 		if(cLetra==a_cOrden[(nNIF % 23)]) {
 			bRetCode=true;
			if (BuscaEnArray (g_a_sAutoCorregir,sNameForm) !=-1) eval ("oFormName."+sNameForm+".value=nNIF+cLetra")
		}
	}

	return bRetCode;
}


function ValidarCIF(sCIF){
var cLetra,nLetra;
var bRetCode = false;
var letrasInicialesCIF= "ABCDEFGHKLMPQSXZ";

	sCIF=sCIF.replace(/\s/g,"");		//Quita espacios
	sCIF=sCIF.replace(/\./g,"");		//Quita puntos
	sCIF=sCIF.replace(/-/g,"");			//Quita guiones

	if (sCIF.length==9){			
		cLetra=sCIF.substring(0,1).toUpperCase();		//letra al principio
		sIdentificacion = sCIF

		if (perteneceA(sIdentificacion.charAt(0),letrasInicialesCIF)){
			if ( valV10 (sIdentificacion.substr(1,sIdentificacion.length -2 ))){
				bRetCode = true;
				var Valor =  sIdentificacion.substr(1 , sIdentificacion.length - 2);                      
				var cerosAdicionales = 7 - Valor.length;
				for ( i=0 ; i < cerosAdicionales ; i++){
					Valor = "0" + Valor;
				}
	
				var DC = sIdentificacion.charAt(sIdentificacion.length-1);
				var sumaA = Number(Valor.charAt(1)) + Number(Valor.charAt(3)) + Number(Valor.charAt(5));
				var sumaB = 0;
				for (i = 0 ; i < 8 ; i = i + 2)	{
					aux1 = String(Number(Valor.charAt(i)) * 2);
					if (aux1.length > 1){
						aux2 = Number(aux1.charAt(0)) + Number(aux1.charAt(1));	
					}
					else{
						aux2 = Number(aux1);	
					}									
					sumaB = sumaB + aux2;
				}								
				var sumaC= String(sumaA + sumaB);
				
				var DCbis;
				DCbis = 10 - Number(sumaC.charAt(1));
				if (sumaC.length > 1){
					if (sumaC.charAt(1) == "0"){
						DCbis = 0;
					}
					else{
						DCbis = 10 - Number(sumaC.charAt(1));
					}
				}
				else{
					DCbis = 10 - Number(sumaC);
				}
	
				if (perteneceA(DC,mayusculas)){
					if (DCbis != (mayusculas.indexOf(DC)+1)) bRetCode = false
				}
				else if (perteneceA(DC,digitos)){
						if (DCbis != DC) bRetCode = false
				}
				else{
					bRetCode = false
				}
			}
		}
	}
	if (bRetCode && BuscaEnArray (g_a_sAutoCorregir,sNameForm) !=-1) eval ("oFormName."+sNameForm+".value=sCIF")
	return bRetCode;
}

function Texto2Numero(sNumero){		// 	Genera un Numero a partir de un String - Transforma de 1.000,5 a 1000.5 
var nPuntoPos1,nComaPos1,nPuntoPos2,nComaPos2,regExp,nNumero
var regCantidades=/[^0-9 .,-]/gi

	sNumero = "" + sNumero
	sNumero = sNumero.replace(regCantidades,"")		//quito puntos	
	if (sNumero=="") sNumero="0"

	nPuntoPos2 = sNumero.lastIndexOf(".")
	nComaPos2 = sNumero.lastIndexOf(",")

	if (nComaPos2>nPuntoPos2){		//'Decimales con ,
		nComaPos1 = sNumero.indexOf(",")
		regExp = /[\x2e]/g			// \x25\s
		sNumero = sNumero.replace(regExp,"")		//quito puntos	
		if (nComaPos1==nComaPos2){
			regExp = /[\x2c]/g
			sNumero = sNumero.replace(regExp,"\x2e")  		//cambio comas por puntos  
		}
		else{
			regExp = /[\x2c]/g
			sNumero = sNumero.replace(regExp,"")		//quito comas		
		}
	}
	else{							// Decimales con .
		nPuntoPos1 = sNumero.indexOf(".")
		regExp = /[\x2c]/g
		sNumero = sNumero.replace(regExp,"")		//quito comas		
		if (nPuntoPos1!=nPuntoPos2){
			regExp = /[\x2e]/g
			sNumero = sNumero.replace(regExp,"")		//quito puntos
		}
	}

	nPuntoPos2 = sNumero.lastIndexOf(".")	//Excepcion para numeros del tipo 1.000
	if (nPuntoPos2==sNumero.length-4 && sNumero.length<=7){
		regExp = /[\x2e]/g
		sNumero = sNumero.replace(regExp,"")		//quito puntos	
	}
	nNumero= parseFloat(sNumero)
	return nNumero
}

// Devuelve el numero con la puntuación y el numero de decimales que se le diga.
function Numero2Texto(nNum,nNumDec,nFormato,bForzarDecs){			//1.05	nFormato: 1/2 (Español/Ingles)
var a_sPuntEnt = new Array (0,".",",");
var a_sPuntDec = new Array (0,",",".");
var sSigno="";

	nNum = Texto2Numero(nNum)			//Verifica el numero
	if (nFormato==null) nFormato=1
	if (nNum<0){
		sSigno="-";
		nNum= Math.abs(nNum);
	}

	if (nNumDec) {				// Con decimales los redondea
		nNum = Math.round(nNum * Math.pow(10,nNumDec))
		nNum = nNum/Math.pow(10,nNumDec)
		sNumeroEntero = Math.floor(nNum).toString()
	}
	else{ 						// Sin decimales
		sNumeroEntero = Math.round(nNum).toString()
	}
	sNumero=nNum.toString()

	nInicioDec = sNumeroEntero.length+1
	sDecimales = sNumero.substring(nInicioDec,nInicioDec+nNumDec)
	if (bForzarDecs) for (i=sDecimales.length;i<nNumDec;i++) sDecimales += "0";

	sEntero=""
	while (sNumeroEntero>=1000){
		sEntero = a_sPuntEnt[nFormato] + sNumeroEntero.substring(sNumeroEntero.length-3,sNumeroEntero.length) + sEntero ;
		sNumeroEntero = sNumeroEntero.substring(0,sNumeroEntero.length-3) ;
	}
	sEntero = sNumeroEntero + sEntero;
	if (sDecimales.length) sNumeroEntero= sSigno + sEntero + a_sPuntDec[nFormato] + sDecimales;
	else sNumeroEntero= sSigno + sEntero;
	return sNumeroEntero;
}


function BuscaEnArray (a_vArray,vValor){			//3.1 Busca la posicion en el array del ultimo valor que se le pasa (Devuelve -1 si no encuentra ninguna)
	var nLen = a_vArray.length
	var nPos=-1
	while (nPos<--nLen){ 
		if (a_vArray[nLen]==vValor) nPos=nLen
	}
	return nPos
}


var	oFormName="",sNameForm,vValueForm,cTipoForm,cValidacion,bError;
g_a_sAutoCorregir = new Array ("U_NIF","V_NIF")

function EsNumero (vVariable){		// True  ( 23 / 12.5 / "23")  No acepta el 0 ni negativos
	if (isNaN(parseInt(vVariable)) || vVariable==0 || vVariable!=Math.abs(vVariable)) return (false)
    return !(isNaN(vVariable));		// False (0 / "" / "eew" / 12,3)
}



var digitos = "0123456789";
var minusculas = "abcdefghijklmnopqrstuvwxyz";
var mayusculas = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

function perteneceA(c,s){
var result = false;  
    for (var i = 0; i < s.length; i++){
        if (c == s.charAt(i)){
            result = true;
            break;
        }
    }   
    return result;
}


function valV10(s){
var c;
var result = true;    
    for (var i = 0; i < s.length; i++){
        c = s.charAt(i);                            
        if (!(perteneceA(c,digitos))){
            result = false;
            break;
        }
    }
    return result;
}