/**
 * Checks the strength of a password.
 * Returns  on empty input string, -2 on weak password, 0 on medium strength password or 1 on strong password.
 * @param passwordToCheck string
 * @return integer

Created By Rashid for Web developer juice
 */

$(document).ready(function(){
	$( 'input.password-box' ).bind( 'keyup', function() {
		//var howStrong = passwordStrength($('input:text[name=login]').val(), $( this ).val());
		var howStrong = passwordStrength($('input:text[name=login]').val(), $( this ).val());
		$( '.strength-text').text( howStrong );
		var sColor = '#555';
		switch( howStrong ) {
			case 'Nivel Alto' :
				$('.password-strength').removeClass("password-strength-high").removeClass("password-strength-medium").removeClass("password-strength-low").removeClass("password-strength-tooshort").addClass("password-strength-high");
				break;
			case 'Nivel Medio' :
				$('.password-strength').removeClass("password-strength-high").removeClass("password-strength-medium").removeClass("password-strength-low").removeClass("password-strength-tooshort").addClass("password-strength-medium");
				break;
			case 'Nivel Bajo' :
				$('.password-strength').removeClass("password-strength-high").removeClass("password-strength-medium").removeClass("password-strength-low").removeClass("password-strength-tooshort").addClass("password-strength-low");
				break;
			case 'Demasiado corta' :
				$('.password-strength').removeClass("password-strength-high").removeClass("password-strength-medium").removeClass("password-strength-low").removeClass("password-strength-tooshort").addClass("password-strength-tooshort");
				break;
			default :
				$('.password-strength').removeClass("password-strength-high").removeClass("password-strength-medium").removeClass("password-strength-low").removeClass("password-strength-tooshort");
		}
	});
	$( 'input.password-box' ).bind('blur', function() {
		$( this ).trigger( 'keyup' );
		});

	});

function passwordStrength(login, pwd) {
	var strongRegex = new RegExp( "^(?=.{8,})(((?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]))|((?=.*[A-Z])(?=.*[a-z])(?=.*\\W))|((?=.*[A-Z])(?=.*[0-9])(?=.*\\W))|((?=.*[a-z])(?=.*[0-9])(?=.*\\W))).*$", "g" );
	var mediumRegex = new RegExp( "^(?=.{6,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))).*$", "g" );
	var enoughRegex = new RegExp( "(?=.{6,}).*", "g" );
	
	if (pwd.length == 0) {
		return 'Escriba la contraseña';
	} else if( false == enoughRegex.test( pwd ) ) {
		return 'Demasiado corta';
	} else if( strongRegex.test( pwd ) && login != pwd) {
		return 'Nivel Alto';
	} else if( mediumRegex.test( pwd ) && login != pwd) {
		return 'Nivel Medio';
	} else {
		return 'Nivel Bajo';
		}
	}

function isNumeric( thisString ) {
	return !isNaN( thisString );
}

function isAlphaNumeric( thisString ) {
	if( val.match( /^[a-zA-Z0-9]+$/ ) ) {
		return true;
	} else {
		return false;
	}
}

function hasAlphabets( thisString ) {
	if( thisString.match( /^[a-zA-Z]+$/ ) ) {
		return true;
	} else {
		return false;
	}
}

function isValidEmailAddress( thisString ) {
	if( thisString.match( /^([a-zA-Z0-9])+([.a-zA-Z0-9_-])*@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-]+)+/ ) ) {
		return true;
	} else {
		return false;
	}
}

String.prototype.trim = String.prototype.trim ? String.prototype.trim : function() {
	var tempStr = this;
	while( tempStr.charAt( 0 ) == ' ' || tempStr.charAt( 0 ) == 'n' || tempStr.charAt( 0 ) == '\t' || tempStr.charAt( 0 ) == '\r' ) {
		tempStr = tempStr.substring( 1 );
	}
	while( tempStr.charAt( tempStr.length - 1 ) == ' ' || tempStr.charAt( tempStr.length - 1 ) == 'n' || tempStr.charAt( tempStr.length - 1 ) == '\t' || tempStr.charAt( tempStr.length - 1 ) == '\r' ) {
		tempStr = tempStr.substring( 0, tempStr.length - 1 );
	}
	return tempStr;
};

var defaultEmptyOK = false
var digits = "0123456789";
var whitespace = " \t\n\r";


function trim(cad)
{	
	var aux="";
	if ((cad!=null)&&(cad!="")){
		var i,lg = cad.length;
		for (;lg>0 && cad.charAt(lg-1)<=' ';lg--);
		for (i=0;i<lg && cad.charAt(i)<=' ';i++);

		for (;i<lg;i++)
			aux = aux + cad.charAt(i);
	}

	return aux;
}

function isEmpty(s)
{   return ((s == null) || (s.length == 0))
}

function isLetter (c)
{   return ( ((c >= "a") && (c <= "z")) || ((c >= "A") && (c <= "Z")) || (c == "ñ") || (c == "Ñ"))
}


function isDigit (c)
{   return ((c >= "0") && (c <= "9"))
}

function isLetterOrDigit (c)
{   return (isLetter(c) || isDigit(c))
}

function isAlphanumeric (s)
{   var i;

    if (isEmpty(s)) 
       if (isAlphanumeric.arguments.length == 1) return defaultEmptyOK;
       else return (isAlphanumeric.arguments[1] == true);

    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
        if (! (isLetter(c) || isDigit(c) ) )
        return false;
    }

    return true;
}


function isLetterSpace (c)
{   
	return ( 
		((c >= "a") && (c <= "z")) || 
		((c >= "A") && (c <= "Z")) || 
		(c == " ") ||
		(c == "á") || (c == "é") || (c == "í") || (c == "ó") || (c == "ú") || 
		(c == "Á") || (c == "É") || (c == "Í") || (c == "Ó") || (c == "Ú") || 
		(c == "ñ") || 
		(c == "Ñ")
	)
}

function isAlphanumericSpace (s)
{   var i;

    if (isEmpty(s)) 
       if (isAlphanumeric.arguments.length == 1) return defaultEmptyOK;
       else return (isAlphanumeric.arguments[1] == true);

    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
        if (! (isLetterSpace(c) || isDigit(c) ) )
        return false;
    }

    return true;
}
function isAlphabeticSpace (s)
{   var i;

    if (isEmpty(s)) 
       if (isAlphabetic.arguments.length == 1) return defaultEmptyOK;
       else return (isAlphabetic.arguments[1] == true);
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is letter
        var c = s.charAt(i);

        if (!isLetterSpace(c))
        return false;
    }
    return true;
}


function ValidBlanks(frmField,strFldName,foco)
{
	if (frmField.value == "" || frmField.value == null)
	{
	        alert("Debe insertar alg?n valor en el campo " + strFldName);
	        if(foco==null) frmField.focus();
	        return (false);
	} 
	return (true);
}
//CAMBIO añadir esta funcion 
function BusqCaracteres(texto)
{
	return true;
}
function validField(strFldName,frmField,intLength,strDtType,obligatorio,foco)
{

	frmField.value=trim(frmField.value)
	
	switch (strDtType)
		{
			case 'string' : 
					if ((obligatorio) && (!ValidBlanks(frmField,strFldName))) return (false);

					if (frmField.value != "")
						//CAMBIO aádir esta primera condicion
						if(!BusqCaracteres(frmField.value))
							{
							alert("'" + strFldName + "' no es válido.");
							if(foco==null) frmField.focus();
							return (false);				
							}
						if (frmField.value.length > intLength)
							{
							alert("'" + strFldName + "' no puede tener más de " + intLength + " caracteres.");
							if(foco==null) frmField.focus();
							return (false);
							}
				break;
			case 'mail': 
					if ((obligatorio) && (!ValidBlanks(frmField,strFldName))) return (false);
					
					if (frmField.value != "")
						if (!isEmail(frmField.value))
							{
							alert("El contenido del campo " + strFldName + " no es correcto");
							alert("'" + strFldName + "' no es una dirección de correo electr?nico v?lida.");
							if(foco==null) frmField.focus();
							return (false);
							}
							
						if (frmField.value.length > intLength)
							{
							alert("'" + strFldName + "' no puede tener más de " + intLength + " caracteres.");
							if(foco==null) frmField.focus();
							return (false);
							}							
				break;	
			case 'nif': 
					if ((obligatorio) && (!ValidBlanks(frmField,strFldName))) return (false);
					
					if (frmField.value != "")
						if (!isNif(frmField.value))
							{
							alert("'" + strFldName + "' no es un NIF válido.");
							if(foco==null) frmField.focus();
							return (false);
							}	
						if (frmField.value.length > intLength)
							{
							alert("'" + strFldName + "' no puede tener más de " + intLength + " caracteres.");
							if(foco==null) frmField.focus();
							return (false);
							}	
				break;	
			case 'nie': 
					if ((obligatorio) && (!ValidBlanks(frmField,strFldName))) return (false);
					
					if (frmField.value != "")
						if (!isNie(frmField.value))
							{
							alert("'" + strFldName + "' no es un NIE válido.");
							if(foco==null) frmField.focus();
							return (false);
							}	
						if (frmField.value.length > intLength)
							{
							alert("'" + strFldName + "' no puede tener más de " + intLength + " caracteres.");
							if(foco==null) frmField.focus();
							return (false);
							}	
				break;				
			case 'cif': 
					if ((obligatorio) && (!ValidBlanks(frmField,strFldName))) return (false);
					
					if (frmField.value != "")
						if (!isCif(frmField.value))
							{
							alert("'" + strFldName + "' no es un CIF válido.");
							if(foco==null) frmField.focus();
							return (false);
							}
						if (frmField.value.length > intLength)
							{
							alert("'" + strFldName + "' no puede tener más de " + intLength + " caracteres.");
							if(foco==null) frmField.focus();
							return (false);
							}	
				break;	
			case 'codPos': 
					if ((obligatorio) && (!ValidBlanks(frmField,strFldName))) return (false);
					
					if (frmField.value != "")
						if (!isCodPostal(frmField.value))
							{
							alert("'" + strFldName + "' no es un código postal válido.");
							if(foco==null) frmField.focus();
							return (false);
							}
						if (frmField.value.length > intLength)
							{
							alert("'" + strFldName + "' no puede tener más de " + intLength + " caracteres.");
							if(foco==null) frmField.focus();
							return (false);
							}							
				break;	
			case 'telefono': 
					if ((obligatorio) && (!ValidBlanks(frmField,strFldName))) return (false);
					
					if (frmField.value != "")
						if (!isFono(frmField.value))
							{
							alert("'" + strFldName + "' no es un número de teléfono válido.");
							if(foco==null) frmField.focus();
							return (false);
							}	
				break;					
			case 'double': 
					if ((obligatorio) && (!ValidBlanks(frmField,strFldName))) return (false);
					
					if (frmField.value != "")
						if (!isNumber(frmField.value))
							{
							alert("'" + strFldName + "' debe ser un número.");
							if(foco==null) frmField.focus();
							return (false);
							}	
						if (frmField.value.length > intLength)
							{
							alert("'" + strFldName + "' no puede tener más de " + intLength + " caracteres.");
							if(foco==null) frmField.focus();
							return (false);
							}							
				break;
			case 'integer': 
					if ((obligatorio) && (!ValidBlanks(frmField,strFldName))) return (false);
					
					if (frmField.value != "")
						if (!isInteger(frmField.value))
							{
							alert("'" + strFldName + "' no es un entero.");
							if(foco==null) frmField.focus();
							return (false);
							}	
						if (frmField.value.length > intLength)
							{
							alert("'" + strFldName + "' no puede tener más de " + intLength + " caracteres.");
							if(foco==null) frmField.focus();
							return (false);
							}							
				break;				
			case 'hour': 
					if ((obligatorio) && (!ValidBlanks(frmField,strFldName))) return (false);
								
					if (frmField.value != "")
						if (!isHour(frmField.value))
							{
							alert("'" + strFldName + "' no es una hora correcta.El formato correcto es hh:mm.");
							if(foco==null) frmField.focus();
							return (false);
							}	
						if (frmField.value.length > intLength)
							{
							alert("'" + strFldName + "' no puede tener más de " + intLength + " caracteres.");
							if(foco==null) frmField.focus();
							return (false);
							}							
							
				break;	
			case 'date': 
					if ((obligatorio) && (!ValidBlanks(frmField,strFldName))) return (false);
					
					if (frmField.value != "")
						if (isDate(frmField.value)== false)
							{
							alert("'" + strFldName + "' no es una fecha correcta. El formato correcto es DD/MM/AAAA.");
							if(foco==null) frmField.focus();
							return (false);
							}
						if (frmField.value.length > intLength)
							{
							alert("'" + strFldName + "' no puede tener más de " + intLength + " caracteres.");
							if(foco==null) frmField.focus();
							return (false);
							}							
							
				break;
			case 'list' : 
                    if ((obligatorio) && (frmField.selectedIndex==0))
                    {
                            //alert("Debe seleccionar algún valor de la lista '" + strFldName + "'");
                            alert("'" + strFldName + "' es un campo obligatorio.");
                            if(foco==null) frmField.focus();
                            return (false);
                    }
				break;			
			case 'porcentaje' :
					if ((obligatorio) && (!ValidBlanks(frmField,strFldName))) return (false);
					if (frmField.value != null && frmField.value!=''){
						if(frmField.value.indexOf('.')!=-1){
							alert("El contenido del campo " + strFldName + " debe utilizar el carácter ',' como separador decimal.");
							if(foco==null) frmField.focus();
							return (false);
						}							
						
						if (!isNumber(frmField.value))
						{
							alert("El contenido del campo " + strFldName + " debe ser numérico");
							if(foco==null) frmField.focus();
							return (false);
						}
						
						if (isPorcentaje(frmField.value)== false)
						{
							alert("El contenido del campo " + strFldName + " no es correcto.");
							if(foco==null) frmField.focus();
							return (false);
						}
					}
				break;							
		}
	return (true);
}


function isInteger (s)
{   var i;
    if (isEmpty(s)) 
       if (isInteger.arguments.length == 1) return defaultEmptyOK;
       else return (isInteger.arguments[1] == true);
    
    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
        if( i != 0 ) {
            if (!isDigit(c)) return false;
        } else { 
            if (!isDigit(c) && (c != "-") || (c == "+")) return false;
        }
    }
    return true;
}
function isDouble (s)
{   var i;
    if (isEmpty(s)) 
       if (isInteger.arguments.length == 1) return defaultEmptyOK;
       else return (isInteger.arguments[1] == true);
    if(isInteger(s)) return true;
    var withPoint=false;
    var decimalcount=0;
    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
        if( i != 0 ) {
            if (!isDigit(c) && c == '.' && withPoint) {
            	return false;
            } else if(c == '.') {
            	withPoint=true;
            } else if (!isDigit(c)) {
            	return false;
            }
        } else { 
            if (!isDigit(c) && (c != "-") || (c == "+")) return false;
        }
        if(withPoint) {
        	decimalcount++;
        	if(decimalcount > 3) {
        		return false;
        	}
        }
    }
    return true;
}
function isPorcentaje (s)
{  
	s=s.replace(',','.')
	esPorcentaje=true;
	if(s.indexOf('.')!=-1)
	{
		s=s.split('.')
		if(s[0] >100 || s[1].length>2) esPorcentaje=false;
		if(s[0] ==100 && s[1]>0) esPorcentaje=false;
	}
	else
	{
		if((s>100) || (s<0) ) esPorcentaje=false
	}

return esPorcentaje

}
function isNumber (s)
{   
    var i;
    var dotAppeared;
    dotAppeared = false;
    if (isEmpty(s)) 
       if (isNumber.arguments.length == 1) return defaultEmptyOK;
       else return (isNumber.arguments[1] == true);
    
    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
        if( i != 0 ) {
            if ( c == "," ) {
                if( !dotAppeared )
                    dotAppeared = true;
                else
                    return false;
            } else     
                if (!isDigit(c) && c != ".") return false;
        } else { 
            if ( c == "," ) {
                if( !dotAppeared )
                    dotAppeared = true;
                else
                    return false;
            } else
                if (!isDigit(c) && (c != "-") || (c == "+")) return false;
        }
    }
    return true;
}

function isAlphabetic (s)
{   var i;

    if (isEmpty(s)) 
       if (isAlphabetic.arguments.length == 1) return defaultEmptyOK;
       else return (isAlphabetic.arguments[1] == true);
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is letter.
        var c = s.charAt(i);

        if (!isLetter(c))
        return false;
    }
    return true;
}



function isAlphanumeric (s)
{   var i;
    if (isEmpty(s)) 
       if (isAlphanumeric.arguments.length == 1) return defaultEmptyOK;
       else return (isAlphanumeric.arguments[1] == true);

    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
        if (! (isLetter(c) || isDigit(c) ) )
        return false;
    }

    return true;
}

function isName (s)
{
    if (isEmpty(s)) 
       if (isName.arguments.length == 1) return defaultEmptyOK;
       else return (isAlphanumeric.arguments[1] == true);
    
    return( isAlphanumeric( stripCharsInBag( s, whitespace ) ) );
}

letras = 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");

function isNif(nif,type)
{
  if(type==null) type=0;
  nif=nif.toLowerCase();

  nifcorrecto = true;
  if(type==1)
	  dni=nif.substring(1,nif.length);
  else 
	 dni=nif.substring(0,nif.length-1);
  dni=parseInt(dni);
  
  if(type==1)
	 letra= nif.charAt(0)
  else    
	letra=nif.charAt(nif.length-1);

  letraCorrecta = letras[ dni % 23];

  if (dni > 99999999)
    nifcorrecto = false;
  if(letra!=letraCorrecta)
    nifcorrecto = false;
   
   return nifcorrecto 

}

function isCif(cif){

	var letrascif=new String("ABCDEFGHPQSKLMX");
	cif=cif.toUpperCase();
// comprobamos la longitud	
	if (cif.length !=9) return false;
// comprobamos que la letra inicial sea una de las v?lidas	
	letra = cif.charAt(0);
	if (letrascif.indexOf(letra)==-1) return false;
// comprobamos la validez del digito de control.	
	digitocontrol=cif.charAt(8);
	aux=cif.substring(1,8);	
	var suma = (parseInt(aux.charAt(1),10) + parseInt(aux.charAt(3),10)+  parseInt(aux.charAt(5),10))
	for (var i=0;i<=6;i=i+2){
		var val = new String(2*parseInt(aux.charAt(i),10));
		if (val.length==1) suma+=parseInt(val.charAt(0),10);
		else suma+=parseInt(val.charAt(0),10) + parseInt(val.charAt(1),10);
	}
	
	var digito = 10 - new String(suma).charAt(1);

	if (letra!="X" && letra!="P"){
		if (digito==10) digito=0;
		if (digitocontrol!=digito) return false;
	} else {
// si es un cif extranjero se valida como un nif, previamente se sustituye la X por un cero
		if (letra=="X") return (isNif("0" + cif.substring(1,9)))
		var ascii = 64 + digito;
		if (digitocontrol.charCodeAt(0)!=ascii) return false;
	}
	
	return true;	
	
}


function isFono(telefono)
{
 esFono=true
	if(telefono.length>15 || telefono.length<9)
		esFono=false;
	else
		for(hh=0;hh<telefono.length;hh++)
			if(isNaN(telefono.charAt(hh)))
				if(telefono.charAt(hh)!='(' && telefono.charAt(hh)!=')' && telefono.charAt(hh)!='-' && telefono.charAt(hh)!='+')
					esFono=false;

	return esFono
			
}

function isEmail (s) 
{
	if (isEmpty(s))
		return false; 
	var i = 1; var sLength = s.length; 
	while ((i < sLength) && (s.charAt(i) != "@")) 
	{ 
		i++;
	}
	if ((i >= sLength) || (s.charAt(i) != "@")) 
		return false; 
	else 
		i += 2;
	
	while ((i < sLength) && (s.charAt(i) != ".")) 
	{
		i++; 
	}
	if ((i >= sLength - 1) || (s.charAt(i) != ".")) 
	 	return false; 

	
	else return true; 
} 
function isHour(s)
{
	var Horacorrecta=true
	var horas,min
	horas=parseInt(s.substring(0,2),10)
	min=parseInt(s.substring(3,5),10)
	if (isNaN(horas))  Horacorrecta=false
	if (isNaN(min))  Horacorrecta=false
	if(s.length!=5) Horacorrecta=false
	if(s.indexOf(':')==-1) Horacorrecta=false
	if(horas>24|| horas<0) Horacorrecta=false
	if(min>60 || min<0) Horacorrecta=false
		
	return Horacorrecta

}
function isDate(s)
{
    var day,month,year,mod,chr

    if (s==null || s.length==0)
        return true
    if (s.length!=10)
        return false

    for (var i=0;i<10;i++)
    {
        chr=s.charAt(i)
        if (i!=2 && i!=5)
        {
            if (chr<"0"||chr>"9") return false
        }
        else
        {
            if (chr!="/") return false
        }
    }
    
    day=parseInt(s.substring(0,2),10)
    month=parseInt(s.substring(3,5),10)
    year=parseInt(s.substring(6,10),10)

    if (1>day || day>31)
        return false
    if (1>month || month>12)
        return false
    if (1>year)
        return false
    if ((month==4 || month==6 || month==9 || month==11) && day==31)
        return false
    if (month==2)
    {
        mod=year%4
    	if (mod==0)
    	{
            mod=year%100
	    if(mod==0)
	    {
                var mod2=year%400
                if(mod2==0 &&  day>29)
                    return false
                else if(mod2!=0 && day>28)
                    return false
            }
	    else if(day>29)
	        return false
        }
        else if (day>28)
            return false
    }
    return true 		
}
function isCodPostal(codigo)
{
var esCodPos=false;

	if(codigo.length!=5 && isNumber(codigo)){
		esCodPos=false;}
	else
	{
		codIni=parseInt(codigo.substring(0,2),10)
		if(codIni>0 && codIni<51)
			esCodPos=true
	}
	return esCodPos

}
//Si s1 < s2 devuelve 2 si s1>s2 devuelve 1
function compDates(s1, s2)
{
    var f1, f2	
    f1 = s1.substring(6,10) + "/";    
    f1 = f1 + s1.substring(3,5) + "/";
    f1 = f1 + s1.substring(0,2); 
    f2 = s2.substring(6,10) + "/";     
    f2 = f2 + s2.substring(3,5) + "/";
    f2 = f2 + s2.substring(0,2);
	if (f1 == f2) 
		return 0
	else	
    	return (f1 < f2) + 1
}


letras = 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");
		
		function isNie(nie)
		{
		if (nie.length == 0) return true;
  		nie=nie.toLowerCase();

  		niecorrecto = true;

  		if (nie.charAt(0)!="x") return false;
  			
	  	dni=nie.substring(1,nie.length);
	   	letra=nie.charAt(nie.length-1);

  		dni=parseInt(dni);
 		letraCorrecta = letras[ dni % 23];

  		if (dni > 99999999)
    		niecorrecto = false;
  		if(letra!=letraCorrecta)
    		niecorrecto = false;

   		return niecorrecto

		}
		
		function isNif(nif)
		{
		if (nif.length == 0) return true;
  		nif=nif.toLowerCase();

  		nifcorrecto = true;

	 	dni=nif.substring(0,nif.length-1);
	 	letra=nif.charAt(nif.length-1);

  		dni=parseInt(dni);
 		letraCorrecta = letras[ dni % 23];

  		if (dni > 99999999)
    		nifcorrecto = false;
  		if(letra!=letraCorrecta)
    		nifcorrecto = false;

   		return nifcorrecto

		}
