
var bCheckNumbers = true;
var bCheckUpperCase = true;
var bCheckLowerCase = true;
var bCheckPunctuation = true;
var nPasswordLifetime = 365;



$(document).ready(function(){

      $("input.browse_A_ALE").filestyle({ 
          image: "/portal/imagenes/browse_A_ALE.jpg",
          imageheight : 25,
          imagewidth : 115,
          width : 110
      });

      $("input.browse_A_CHI").filestyle({ 
          image: "/portal/imagenes/browse_A_CHI.jpg",
          imageheight : 25,
          imagewidth : 115,
          width : 110
      });

      $("input.browse_A_ENG").filestyle({ 
          image: "/portal/imagenes/browse_A_ENG.jpg",
          imageheight : 25,
          imagewidth : 115,
          width : 110
      });

      $("input.browse_A_ESP").filestyle({ 
          image: "/portal/imagenes/browse_A_ESP.jpg",
          imageheight : 25,
          imagewidth : 115,
          width : 110
      });

      $("input.browse_A_FRE").filestyle({ 
          image: "/portal/imagenes/browse_A_FRE.jpg",
          imageheight : 25,
          imagewidth : 115,
          width : 110
      });

      $("input.browse_A_GRE").filestyle({ 
          image: "/portal/imagenes/browse_A_GRE.jpg",
          imageheight : 25,
          imagewidth : 115,
          width : 110
      });

      $("input.browse_A_HOL").filestyle({ 
          image: "/portal/imagenes/browse_A_HOL.jpg",
          imageheight : 25,
          imagewidth : 115,
          width : 110
      });

      $("input.browse_A_ITA").filestyle({ 
          image: "/portal/imagenes/browse_A_ITA.jpg",
          imageheight : 25,
          imagewidth : 115,
          width : 110
      }); 
              
      $("input.browse_A_POL").filestyle({ 
          image: "/portal/imagenes/browse_A_POL.jpg",
          imageheight : 25,
          imagewidth : 115,
          width : 110
      });
      
      $("input.browse_A_POR").filestyle({ 
          image: "/portal/imagenes/browse_A_POR.jpg",
          imageheight : 25,
          imagewidth : 115,
          width : 110
      });   	
   	
      $("input.browse_A_SW").filestyle({ 
          image: "/portal/imagenes/browse_A_SW.jpg",
          imageheight : 25,
          imagewidth : 115,
          width : 110
      });   	
   	
   	});



/**
	Funcion que permite validar un email
*/
function checkEmail(emailAdress){
/**
	var testresults;
	var str=emailAdress;
	var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
	if (filter.test(str)){
		testresults=true
	}
	else{		
		testresults=false;
	}
*/
	var email;
	if(emailAdress.indexOf("@")!=-1){	
		email = emailAdress.substring(emailAdress.indexOf("@"),emailAdress.length);
		if(email.indexOf(".")!=-1){
			return true;
		}
		else{
			return false;
		}
	}
	else{
		return false;
	}
	
}

function IsAlphaNumeric()
{
	var alfanumber = $("#user").val();
	var Template = /^[a-z0-9]+$/i //Formato de alfanumerico
	return (Template.test(alfanumber)) ? 1 : 0 //Compara "YourAlphaNumeric" con el formato "Template" y si coincidevuelve verdadero si no devuelve falso
}

function mostrarNombre() 
{ 
             
            // Este problema es con IE normalmente (firefox no)  
            //pero por si acaso lo hacemos para todos... 
            var componente = document.getElementById("fileImagen"); 
            var pieces = componente.value.split("\\"); // Windows  
            if (pieces.length == 0) 
            { 
               pieces = componente.value.split("/"); //Linux, una vez más para todos! 
            } 
            document.getElementById("nombreFichero").value=pieces[pieces.length-1]; 
} 
/**
	Validacion de la fortaleza de la contrasea
*/








function checkPassword(strPassword)
{

	// Reset combination count
	nCombinations = 0;
	
	// Check numbers
	if (bCheckNumbers)
	{
		strCheck = "0123456789";
		if (doesContain(strPassword, strCheck) > 0) 
		{ 
        		nCombinations += strCheck.length; 
    		}
	}
	
	// Check upper case
	if (bCheckUpperCase)
	{
		strCheck = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
		if (doesContain(strPassword, strCheck) > 0) 
		{ 
        		nCombinations += strCheck.length; 
    		}
	}
	
	// Check lower case
	if (bCheckLowerCase)
	{
		strCheck = "abcdefghijklmnopqrstuvwxyz";
		if (doesContain(strPassword, strCheck) > 0) 
		{ 
        		nCombinations += strCheck.length; 
    		}
	}
	
	// Check punctuation
	if (bCheckPunctuation)
	{
		strCheck = ";:-_=+\|//?^&!.@$£#*()%~<>{}[]";
		if (doesContain(strPassword, strCheck) > 0) 
		{ 
        		nCombinations += strCheck.length; 
    		}
	}

	
	// Calculate
	// -- 500 tries per second => minutes 
    	var nDays = ((Math.pow(nCombinations, strPassword.length) / 500) / 2) / 86400;

 
	// Number of days out of password lifetime setting
	var nPerc = nDays / nPasswordLifetime;

	
	return nPerc;
}



function doesContain(strPassword, strCheck)
 {
    	nCount = 0; 
 
	for (i = 0; i < strPassword.length; i++) 
	{
		if (strCheck.indexOf(strPassword.charAt(i)) > -1) 
		{ 
	        	nCount++; 
		} 
	} 
 
	return nCount; 
} 






function fortalezaPassword(p){


	l = 0;
	v1 = 'aeiou1234567890';
	v2 = 'AEIOUbcdfghjklmnpqrst';
	v3 = 'vxyzBCDFGHJKLMNPQRST';
	v4 = 'VXYZ$@#';
	for (i = 0; i < p.length; i++){
	  if (v1.indexOf(p[i]) != -1) l += 1;
	  else if (v2.indexOf(p[i]) != -1) l += 2;
	  else if (v3.indexOf(p[i]) != -1) l += 3;
	  else if (v4.indexOf(p[i]) != -1) l += 4;
	  else l += 5;
	}
	l *= 3;
	if(l > 100)l = 100;
	
	if(l <=30){
		return 0;
	}
	
	if(l <= 60){
		return 1;
	}
	return 2;
}



// Runs password through check and then updates GUI 
function runPassword(strPassword) 
{
	// Check password
	nPerc = checkPassword(strPassword);
	
    	
    // Set new width
    
    
    var nRound = Math.round(nPerc * 100);
    
    	
	if (nRound < (strPassword.length * 5)) 
	{ 
		nRound += strPassword.length * 5; 
	}
	
	
	if (nRound > 100)
		nRound = 100;

 	if (nRound > 70)
 	{
		return 2;
 	}
 	else if (nRound > 30)
 	{
		return 1;
	}	
 	else 
 	{
		return 0;
 	}
}



function actualizarMensajeFortalezaPassword(debil,optima,muydebil,media,event){
      //reestablecemos el color por defecto
      $("#imagenFortaleza").attr("src","/portal/imagenes/V_pass_short.gif");
      $("#contenedorMensajeFortalezaPassword").attr("class","passw_short");
     
      //$("#mensajeFortalezaPassword").is(':visible') == true)
 	 var len = $("#password").val().length;
  
  /*if (event.keyCode == 8)
        {
        len = len-1;
	}*/
  
  
	if (len <= 3) {
		     $("#mensajeFortalezaPassword").hide();
            $("#fortalezaPassword").hide();
            $("#imagenFortaleza").hide();
            return false;
            }
	else{
      switch(runPassword($("#password").val())){
            case 0:
                        //cuando la fortaleza es debil i.e 0 solamente mostramos el td oculto

                        $("#mensajeFortalezaPassword").show();
                        $("#fortalezaPassword").show();
                        $("#imagenFortaleza").show();
                        $("#fortalezaPassword").html(muydebil);                                
                        $("#mensajeFortalezaPassword").show('');
                        $("#oculto").attr("value",true);
                        $("#m").attr("value",false);
                        
            break;
            case 1:

                                         $("#mensajeFortalezaPassword").show();
                        $("#fortalezaPassword").show();
                        $("#imagenFortaleza").show();
                  //fortaleza media
                  $("#fortalezaPassword").html(media);                                   
                  $("#mensajeFortalezaPassword").show('');
                  $("#oculto").attr("value",true);
                  $("#m").attr("value",false);
            break;                  
            default:          
                  //fortaleza alta
                  // cuando tiene esta fortaleza debemos cambiar la imagen que se muestra

                                               $("#mensajeFortalezaPassword").show();
                        $("#fortalezaPassword").show();
                        $("#imagenFortaleza").show();            
                  $("#imagenFortaleza").attr("src","/portal/imagenes/V_pass_ok.gif");
                  $("#contenedorMensajeFortalezaPassword").attr("class","passw_ok");
                  $("#fortalezaPassword").html(optima);                                  
                  $("#mensajeFortalezaPassword").show(''); 
                  $("#oculto").attr("value",true);
                  $("#m").attr("value",false);
      }
      }
}


/**
	Funcion que se encarga de realizar la validacion de los datos de entrada para la creacion de una cuenta
*/
function validacionCrearCuenta(idFormulario,urlCreacion,error3,error4,error1,texto_ayuda2,error2,errorAvatar){
	validacionOK = true;
	validacionOK1 = true;
	
	//vamos a ocultar todos los campos para que cuando validen por segunda o tercera o... solo se muestre errores en los que exista
	$("#mensajeErrorEmail").hide();
	$("#mensajeErrorPassword").hide();
	$("#mensajeFortalezaPassword").hide();
	$("#mensajeErrorPasswordRepetido").hide();
	
	//lo primero que realizaremos es la validacion de email
	selectorIdFormulario = "#"+idFormulario;	
	
	if(checkEmail($("#email").val())==false){
		//email incorrecto asi que debemos mostrar el mensaje
		//mensajeError = "Debes ingresar una direccion de email v&aacute;lida";
		
		if($("#email").val()==""){
			$("#mensajeErrorEmail").html(error2);
			$("#mensajeErrorEmail").show('');

			validacionOK = false;
		}
		
		else{
			$("#mensajeErrorEmail").html(error4);
			$("#mensajeErrorEmail").show('');
			validacionOK = false;
		}
	}

	if($("#password").val()==""){
		$("#mensajeErrorPassword").html(error2);
		$("#mensajeErrorPassword").show('');
		validacionOK = false;
	}

	else if($("#password").val().length <= 3){
		$("#mensajeErrorPassword").html(error1);
		$("#mensajeErrorPassword").show('');
		validacionOK = false;
	}
	//validacion el password repetido
	//primero miramos si son iguales
	if(($("#password_r").val()==$("#password").val())){
	}
	else{
		//si no son iguales para mostrar el mensaje de error miramos si esta vacio o si no son iguales realmente		
		if($("#password_r").val()==""){
			//password repetido vacio solamente mostramos el mensaje de error
			$("#mensajeErrorPasswordRepetido").show('');			
		}
		else{
			//escribieron otro password distinto al proporcionado en la fila anterior
			//mensajeError = "Los password que has introducido no coinciden";
			$("#mensajeErrorPasswordRepetido").html(error3);
			$("#mensajeErrorPasswordRepetido").show('');
		}
		validacionOK = false;
	}
	
	var nombre_userForo = $("#user").val();
	//var avatar_Foro = $("#fileImagen").val();


	if(checkEmail($("#email").val())==false){

		$("#password").attr("value","");
		$("#password_r").attr("value","");
	}	
	
	$('#error_extension').hide();
	$('#errorAvatar').hide();
	
	//if(nombre_userForo.trim() == "" && avatar_Foro.trim() != ""){
	//	validacionOK1 = false;
	//	$("#errorAvatar").attr("style"," ");
	//	$("#password").attr("value","");
	//	$("#password_r").attr("value","");
	//	$("#w1").attr("style","display:none;");
	//}
	//else
	//{

	//if($("#fileImagen").val()!=""){

		//validarExtensionTam();
	
	
			//if (/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent)){ //test for Firefox/x.x or Firefox x.x (ignoring remaining digits);
		 		//var ffversion=new Number(RegExp.$1); // capture x.x portion and store as a number
		 		//if (ffversion>=3){
		 		
		 		//	if(document.getElementById('fileImagen').files) {
		 		//		var tama = document.getElementById('fileImagen').files.item(0).fileSize;
		 			//	if(tama>768000){
		 				//	$('#error_extension').show();
		 			//		validacionOK1 = false;
		 			//	}
		 		//	}
		 	//	}
		//	}
	//	}
	//}

	if(validacionOK && validacionOK1){
		//si la validacion es correcta enviamos la peticion de crear cuenta
		document.getElementById("formularioCreacionCuenta").submit();
	}
}

	
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g,"");
}


function validarExtensionTam() {

	validacionOK1 = true;
	var fich = $("#fileImagen").val();

	var ext = fich.substring(fich.lastIndexOf(".")).toLowerCase();

	

	if(ext!='') {
		if( ext ==".jpg" || ext ==".gif" || ext ==".png" || ext ==".jpeg"){
			validacionOK1 = true;
		}
		else{
			validacionOK1 = false;
			$('#error_extension').show();
			
		}
	}
	return validacionOK1;
}
