

$(document).ready(function(){

      $("input.browse_A_de").filestyle({ 
          image: "/portal/imagenes/browse_A_de.jpg",
          imageheight : 25,
          imagewidth : 115,
          width : 110
      });

      $("input.browse_A_zh").filestyle({ 
          image: "/portal/imagenes/browse_A_zh.jpg",
          imageheight : 25,
          imagewidth : 115,
          width : 110
      });

      $("input.browse_A_en").filestyle({ 
          image: "/portal/imagenes/browse_A_en.jpg",
          imageheight : 25,
          imagewidth : 115,
          width : 110
      });

      $("input.browse_A_es").filestyle({ 
          image: "/portal/imagenes/browse_A_es.jpg",
          imageheight : 25,
          imagewidth : 115,
          width : 110
      });

      $("input.browse_A_fr").filestyle({ 
          image: "/portal/imagenes/browse_A_fr.jpg",
          imageheight : 25,
          imagewidth : 115,
          width : 110
      });

      $("input.browse_A_el").filestyle({ 
          image: "/portal/imagenes/browse_A_el.jpg",
          imageheight : 25,
          imagewidth : 115,
          width : 110
      });

      $("input.browse_A_nl").filestyle({ 
          image: "/portal/imagenes/browse_A_nl.jpg",
          imageheight : 25,
          imagewidth : 115,
          width : 110
      });

      $("input.browse_A_it").filestyle({ 
          image: "/portal/imagenes/browse_A_it.jpg",
          imageheight : 25,
          imagewidth : 115,
          width : 110
      }); 
              
      $("input.browse_A_pl").filestyle({ 
          image: "/portal/imagenes/browse_A_pl.jpg",
          imageheight : 25,
          imagewidth : 115,
          width : 110
      });
      
      $("input.browse_A_pt").filestyle({ 
          image: "/portal/imagenes/browse_A_pt.jpg",
          imageheight : 25,
          imagewidth : 115,
          width : 110
      });   	
   	
      $("input.browse_A_sv").filestyle({ 
          image: "/portal/imagenes/browse_A_sv.jpg",
          imageheight : 25,
          imagewidth : 115,
          width : 110
      });
      $("input.browse_A_fi").filestyle({ 
          image: "/portal/imagenes/browse_A_fi.jpg",
          imageheight : 25,
          imagewidth : 115,
          width : 110
      });   
      $("input.browse_A_hu").filestyle({ 
          image: "/portal/imagenes/browse_A_hu.jpg",
          imageheight : 25,
          imagewidth : 115,
          width : 110
      });	
      $("input.browse_A_ja").filestyle({ 
          image: "/portal/imagenes/browse_A_ja.jpg",
          imageheight : 25,
          imagewidth : 115,
          width : 110
      });
      $("input.browse_A_no").filestyle({ 
          image: "/portal/imagenes/browse_A_no.jpg",
          imageheight : 25,
          imagewidth : 115,
          width : 110
      });
      $("input.browse_A_pb").filestyle({ 
          image: "/portal/imagenes/browse_A_pb.jpg",
          imageheight : 25,
          imagewidth : 115,
          width : 110
      });
      $("input.browse_A_ru").filestyle({ 
          image: "/portal/imagenes/browse_A_ru.jpg",
          imageheight : 25,
          imagewidth : 115,
          width : 110
      });
      $("input.browse_A_tr").filestyle({ 
          image: "/portal/imagenes/browse_A_tr.jpg",
          imageheight : 25,
          imagewidth : 115,
          width : 110
      });
      $("input.browse_A_zt").filestyle({ 
          image: "/portal/imagenes/browse_A_zt.jpg",
          imageheight : 25,
          imagewidth : 115,
          width : 110
      });
      $("input.browse_A_sk").filestyle({ 
          image: "/portal/imagenes/browse_A_sk.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)
{
	// JSNOM.IdentifierNamingPattern: 18-05-2010: ANGEL
	// JSNOM.GlobalVarPattern: 18-05-2010: ANGEL 
	// Hago estas variables locales, antes eran globales y no cumplían las normas arriba especificadas
	// también se encuentran en la librería funciones PortalCrear con los mismos valores y el mismo comportamiento
	var bComprobarNumeros = true;
	var bComprobarMay = true;
	var bComprobarMin = true;
	var bComprobarCaractRaros = true;
	var nContrasenaTiempoDeVida = 365;

	// Reset combination count
	var nCombinations = 0;
	var strCheck = "";
	
	// Check numbers
	if (bComprobarNumeros)
	{
		strCheck = "0123456789";
		if (doesContain(strPassword, strCheck) > 0) 
		{ 
        		nCombinations += strCheck.length; 
    		}
	}
	
	// Check upper case
	if (bComprobarMay)
	{
		strCheck = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
		if (doesContain(strPassword, strCheck) > 0) 
		{ 
        		nCombinations += strCheck.length; 
    		}
	}
	
	// Check lower case
	if (bComprobarMin)
	{
		strCheck = "abcdefghijklmnopqrstuvwxyz";
		if (doesContain(strPassword, strCheck) > 0) 
		{ 
        		nCombinations += strCheck.length; 
    		}
	}
	
	// Check punctuation
	if (bComprobarCaractRaros)
	{
		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 / nContrasenaTiempoDeVida;

	
	return nPerc;
}



function doesContain(strPassword, strCheck)
 {
    var	nCount = 0; 
 	var longitud2 = strPassword.length
	for (var i = 0; i < longitud2; i++) 
	{
		if (strCheck.indexOf(strPassword.charAt(i)) > -1) 
		{ 
	        	nCount++; 
		} 
	} 
 
	return nCount; 
} 






function fortalezaPassword(p){


	var l = 0;
	var v1 = 'aeiou1234567890';
	var v2 = 'AEIOUbcdfghjklmnpqrst';
	var v3 = 'vxyzBCDFGHJKLMNPQRST';
	var v4 = 'VXYZ$@#';
	
	var longitud3 = p.length;
	for (var i = 0; i < longitud3; 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
	var 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){
	var validacionOK = true;
	var 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();
	$("#error_extension").hide();
	$("#formato").hide();
	
	
	
	//lo primero que realizaremos es la validacion de email
	var 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;
		 			//	}
		 		//	}
		 	//	}
		//	}
	//	}
	//}
	var extensiones_permitidas = new Array(".gif", ".jpg", ".png");
	var archivo = document.getElementById("fileImagen").value;
	
	if (archivo) { 
      //recupero la extensión de este nombre de archivo 
      var extension = (archivo.substring(archivo.lastIndexOf("."))).toLowerCase(); 

      //compruebo si la extensión está entre las permitidas 
      var permitida = false; 
      for (var i = 0; i < extensiones_permitidas.length; i++) 
      { 
         if (extensiones_permitidas[i] == extension) 
         { 
         permitida = true; 
         break; 
         } 
      } 
	
		if(permitida==false)
		{
			$('#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() {

	var 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;
}
