$(document).ready(function()
{
   /**
   	* @desc funcion exists para comprobar los campos existentes en el registro del registro. 
   	* Evita errores por declaraciones sobre id's inexistentes
   	* @return true si el id existe
   	*/
   jQuery.fn.exists = function(){return jQuery(this).length>0;}

//Filtro para cargar las siguientes acciones solo si existe el formulario de registro
	//if ( jQuery().validate ) {
	//	alert('cargado');
	//}
	//else {
	//	alert('validate cargado');
	//}
	//alert($("input[name=registro_id_usuario]").parents("form").length);

	//if($("#registro").exists())
	if ($("input[name=registro_id_usuario]").parents("form").exists())

	{
		$("input[name=registro_id_usuario]").parents("form").validate({
		//$("#registro").validate({
   		onkeyup: false,
   		groups:
    	{
    		fecha_nacimiento: 'registro_dia registro_mes registro_anyo'
			},
    	rules:
    	{
    			registro_id_usuario:
    			{
	   				rangelength: [4,20],
	   				formato: "^([0-9a-zA-Z/-]*)$",
	   				remote: '/apoyo/comprobar_disponibilidad.php'
					},
					registro_password:
					{
						minlength: 4
					},
					registro_confirmar_password:
					{
					},
	   			registro_email_usuario:
	   			{
						maxlength: 250, 
	   				email:true,
	   				remote: '/apoyo/comprobar_disponibilidad.php'
					},
					registro_confirmar_email:
					{
					},
					registro_nombre:
					{
						maxlength: 250 
					},
					registro_apellidos:
					{
						maxlength: 250 
					},
					registro_dia:
					{
						range: [1,31]
					},
					registro_mes:
					{
						range: [1,12]
					},
					registro_anyo:
					{
						range: [1900,2100]
					},
					registro_pais:
					{
						formato: "^([A-Z]{2})$"  
					},
					registro_provincia:
					{
						maxlength: 250 
					},
					registro_ciudad:
					{
						maxlength: 100 
					},
					registro_cp:
					{
						rangelength: [5,5],
						formato: "^([0-9]*)$" 
					},
					registro_telefono:
					{
						rangelength: [3,25],
						formato: "^([0-9]*)$" 
					},
					registro_estudios:
					{
						maxlength: 250 
					},
					registro_ocupacion:
					{
						maxlength: 250 
					},
					registro_email_alternativo:
					{
						maxlength: 200, 
						email: true
					},
					registro_webs:
					{
						url: true
					},
					registro_bio:
					{
					},
					registro_publi:
					{
						maxlength: 250 
					},
					registro_sexo:
					{
						formato: "^(hombre|mujer)$" 
					},
					registro_visibilidad_perfil:
					{
						range: [0,2]
					},
					registro_referer:
					{
						url: true
					},
					registro_confirmar_condiciones_legales:
					{
					}
			},
			errorClass: "registro_error",
			errorPlacement: function(error,element)
			{
				if(element.attr('name') == 'recaptcha_response_field')
				{
					error.insertAfter($('#div_captcha'));
				}
				else if(element.attr('name') == 'registro_dia' || element.attr('name') == 'registro_mes' || element.attr('name') == 'registro_anyo')
				{
					error.insertAfter($('[name=registro_anyo]'));
				}
				else if(element.attr('name') == 'registro_publi')
				{
					error.insertAfter(element.parent().parent());
				}
				else if(element.attr('name') == 'registro_confirmar_condiciones_legales')
				{
					error.insertAfter(element.parent());
				}
				else
				{
					error.insertAfter(element);
				}
			},
			invalidHandler: function(e,validator)
			{
			},
			submitHandler: function(form)
			{
				form.submit();
			}
	});
 	 // llamada a la funcion de fortaleza de contraseña
 	 	if($('div#registro_password_text, div#registro_password_bar').exists())
 	 	{
 			 $('[name=registro_password]').keyup(function()
 			 {
 	 					runPassword($(this).attr('value'), 'registro_password');
			 })
		}
 	 
 	 // llamada a autocompletar
 	 if(typeof autocompletar == 'undefined')
 	 {
 	 		autocompletar = 'off';
	 }
 	 
 	 if(autocompletar=='on')
 	 {
 	   $('[name=registro_nombre]').keyup(function()
 		 {
			 autocompletar_nick();
		 })
	 }
	 
	 /////////////////////////
	 // Condiciones legales //
	 /////////////////////////
	 $('a.condiciones_legales').toggle
	 (
	 	function()
	 	{
	 		$('div#condiciones_legales').show();
	 		return false;
		},
		function()
		{
	 		$('div#condiciones_legales').hide();
	 		return false;
		}
	 )
	 
	 // Actualizacion pais
	 if(typeof select_pais == 'undefined')
	 {
	 	select_pais = '';
	 }
	 $('[name=registro_pais]').attr('value',select_pais);
			
 	 
 	 ///////////////////////////////
 	 // Validacion del formulario	//
 	 ///////////////////////////////
 	   
   // Llamada ajax para obtener los campos obligatorios del registro
   $.ajax(
   {
   		url: "apoyo/campos_obligatorios_registro.php",
      data:({id_registro : $('input[name=id_registro]').attr('value')}),
      type: "POST",
      success: CamposObligatorios
   })
   // Llamada ajax para obtener el xml con los mensajes de error
   $.ajax(
   {
     url: "apoyo/xml_mensajes_error.php",
     dataType: 'xml', //($.browser.msie) ? 'text' : 'xml',
     success: ReglasValidacion
	 })
   
   $.validator.addMethod
   (
   		"formato", function(value, element, param)
      {
      	if(value != '')
      		return value.match(new RegExp(param));
      	else
      		return true;
  		}
	 )
   
   
 }
	   /**
    * @desc Añade la regla required a los campos obligatorios del formulario y realiza la llamada ajax
    * para obtener el xml con los mensajes de error
    * @param resp string con los parametros obligatorios devuelto por la llamada ajax
    */
   function CamposObligatorios(resp)
   {
   		var campos_obligatorios = resp.split(',');
   		
   		$.each(campos_obligatorios,function(index,value)
   		{
   			// Se añade la regla 'required' a los campos obligatorios
   			if($('[name=registro_'+value+']').exists())
   			{
   						$('[name=registro_'+value+']').rules('add','required');
				}
				// Para la fecha nacimiento:
				if(value == 'fecha_nacimiento')
				{
						if($('[name=registro_dia]').exists())
						 	$('[name=registro_dia]').rules('add','required');
						if($('[name=registro_mes]').exists())
							$('[name=registro_mes]').rules('add','required');
						if($('[name=registro_anyo]').exists())
							$('[name=registro_anyo]').rules('add','required');
				}
			})
			
			// Si existen los campos de confirmar mail/pswd deben ser iguales a los primeros
			if($('[name=registro_confirmar_email]').exists() && $('[name=registro_email_usuario]').exists())
			{
				$('[name=registro_confirmar_email]').rules('add',{ equalTo: '[name=registro_email_usuario]'});
			} 
			if($('[name=registro_confirmar_password]').exists() && $('[name=registro_password]').exists())
			{
				$('[name=registro_confirmar_password]').rules('add',{ equalTo: '[name=registro_password]' });
			} 
		  //Si existe el campo captcha debe ser obligatorio
			if($('#recaptcha_response_field').exists())
				$('#recaptcha_response_field').rules('add','required');
	 }

	 /**
	  * @desc Actualiza las reglas de validacion y los mensajes de error de los 
	  * campos del formulario
	  * @param resp string con los mensajes de error devuelto por la llamada ajax
	  */
	 function ReglasValidacion(xml)
	 {
		  var campo = '';
		  var regla = '';
		  var mensaje = '';
		  
		  $(xml).find('campo').each(function()
		  {
		  	campo = 'registro_' + $(this).attr('name');
		  	
		  	$(this).find('regla').each(function()
		  	{
		  		regla = $(this).attr('name');
		  		mensaje = $(this).text();
		  				  	
					if(mensaje!='')
					{
							if(campo == 'registro_captcha')
							{
								if($('#recaptcha_response_field').exists() && regla == 'required')
									$('#recaptcha_response_field').rules('add', {messages: {required: jQuery.validator.format(mensaje) } });
							}
							else
							{
	        				if($('[name=' + campo + ']').exists())
		  						{
       								if(regla == 'required')
       									$('[name=' + campo + ']').rules('add',{messages: { required : jQuery.validator.format(mensaje) } });
       								if(regla == 'formato')
       									$('[name=' + campo + ']').rules('add',{messages: { formato : jQuery.validator.format(mensaje) } });
       								if(regla == 'disponibilidad')
       									$('[name=' + campo + ']').rules('add',{messages: { remote : jQuery.validator.format(mensaje) } });
       								if(regla == 'equalTo')
       									$('[name=' + campo + ']').rules('add',{messages: { equalTo : jQuery.validator.format(mensaje) } });
       								if(regla == 'minlength')
       									$('[name=' + campo + ']').rules('add',{messages: { minlength : jQuery.validator.format(mensaje) } });
       								if(regla == 'maxlength')
       									$('[name=' + campo + ']').rules('add',{messages: { maxlength : jQuery.validator.format(mensaje) } });
       								if(regla == 'rangelength')
       									$('[name=' + campo + ']').rules('add',{messages: { rangelength : jQuery.validator.format(mensaje) } });
       								if(regla == 'range')
       									$('[name=' + campo + ']').rules('add',{messages: { range : jQuery.validator.format(mensaje) } });
       								if(regla == 'email')
       									$('[name=' + campo + ']').rules('add',{messages: { email : jQuery.validator.format(mensaje) } });
       								if(regla == 'url')
       									$('[name=' + campo + ']').rules('add',{messages: { url : jQuery.format(mensaje) } });
									}
							}
					}
				})
			})
	 }
 	 

					
})	
	
	
	///////////////////////////////
	// Auto-completar id_usuario //
	///////////////////////////////
	
	/**
	 * @desc Construye el nick del usuario a partir del nombre que escribe el usuario
	 * pero solo con caracteres validos
	 */
	function autocompletar_nick()
	{
		var caracteres_invalidos = new RegExp("^[^0-9a-zA-Z/-]$", "g");
		var nombre = $('[name=registro_nombre]').attr('value');
		var nick = new String();
		
		// Se comprueba caracter a caracter el nombre, y se eliminann los caracteres no válidos
		for(var i=0; i<nombre.length; i++)
		{
			var caracter = nombre.charAt(i);
			caracter = caracter.replace(caracteres_invalidos,'');
			nick = nick + caracter;
		}
		// Se actualiza el nick
		$('[name=registro_id_usuario]').attr('value',nick);
	}	
		
		
	////////////////////////////////
	// Fortaleza de la contraseña //
	////////////////////////////////
		
		// Password strength meter v2.0
		// Matthew R. Miller - 2007
		// www.codeandcoffee.com
		// Based off of code from:
		//  http://www.intelligent-web.co.uk
		//  http://www.geekwisdom.com/dyn/passwdmeter

		/*
			Password Strength Algorithm:
			
			Password Length:
				5 Points: Less than 4 characters
				10 Points: 5 to 7 characters
				25 Points: 8 or more
				
			Letters:
				0 Points: No letters
				10 Points: Letters are all lower case
				20 Points: Letters are upper case and lower case

			Numbers:
				0 Points: No numbers
				10 Points: 1 number
				20 Points: 3 or more numbers
				
			Characters:
				0 Points: No characters
				10 Points: 1 character
				25 Points: More than 1 character

			Bonus:
				2 Points: Letters and numbers
				3 Points: Letters, numbers, and characters
				5 Points: Mixed case letters, numbers, and characters
				
			Password Text Range:
			
				>= 90: Very Secure
				>= 80: Secure
				>= 70: Very Strong
				>= 60: Strong
				>= 50: Average
				>= 25: Weak
				>= 0: Very Weak
				
		*/

// Settings
// -- Toggle to true or false, if you want to change what is checked in the password
var m_strUpperCase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var m_strLowerCase = "abcdefghijklmnopqrstuvwxyz";
var m_strNumber = "0123456789";
var m_strCharacters = "!@#$%^&*?_~"

// Check password
function checkPassword(strPassword)
{
	// Reset combination count
	var nScore = 0;
	
	// Password length
	// -- Less than 4 characters
	if (strPassword.length < 5)
	{
		nScore += 5;
	}
	// -- 5 to 7 characters
	else if (strPassword.length > 4 && strPassword.length < 8)
	{
		nScore += 10;
	}
	// -- 8 or more
	else if (strPassword.length > 7)
	{
		nScore += 25;
	}

	// Letters
	var nUpperCount = countContain(strPassword, m_strUpperCase);
	var nLowerCount = countContain(strPassword, m_strLowerCase);
	var nLowerUpperCount = nUpperCount + nLowerCount;
	// -- Letters are all lower case
	if (nUpperCount == 0 && nLowerCount != 0) 
	{ 
		nScore += 10; 
	}
	// -- Letters are upper case and lower case
	else if (nUpperCount != 0 && nLowerCount != 0) 
	{ 
		nScore += 20; 
	}
	
	// Numbers
	var nNumberCount = countContain(strPassword, m_strNumber);
	// -- 1 number
	if (nNumberCount == 1)
	{
		nScore += 10;
	}
	// -- 3 or more numbers
	if (nNumberCount >= 3)
	{
		nScore += 20;
	}
	
	// Characters
	var nCharacterCount = countContain(strPassword, m_strCharacters);
	// -- 1 character
	if (nCharacterCount == 1)
	{
		nScore += 10;
	}	
	// -- More than 1 character
	if (nCharacterCount > 1)
	{
		nScore += 25;
	}
	
	// Bonus
	// -- Letters and numbers
	if (nNumberCount != 0 && nLowerUpperCount != 0)
	{
		nScore += 2;
	}
	// -- Letters, numbers, and characters
	if (nNumberCount != 0 && nLowerUpperCount != 0 && nCharacterCount != 0)
	{
		nScore += 3;
	}
	// -- Mixed case letters, numbers, and characters
	if (nNumberCount != 0 && nUpperCount != 0 && nLowerCount != 0 && nCharacterCount != 0)
	{
		nScore += 5;
	}
	
	
	return nScore;
}
 
// Runs password through check and then updates GUI 
function runPassword(strPassword, strFieldID) 
{
	// Check password
	var nScore = checkPassword(strPassword);
	
	 // Get controls
    	var ctlBar = document.getElementById(strFieldID + "_bar"); 
    	var ctlText = document.getElementById(strFieldID + "_text");
    	if (!ctlBar || !ctlText)
    		return;
    	
    	// Set new width
    	ctlBar.style.width = nScore + "%";

 	// Color and text
	// -- Very Secure
 	if (nScore >= 90)
 	{
 		var strText = "Muy seguro";
 		var strColor = "#0ca908";
 	}
 	// -- Secure
 	else if (nScore >= 80)
 	{
 		var strText = "Seguro";
 		var strColor = "#007f00";
	}
	// -- Very Strong
 	else if (nScore >= 70)
 	{
 		var strText = "Muy Fuerte";
 		var strColor = "#1740ef";
	}
	// -- Strong
 	else if (nScore >= 60)
 	{
 		var strText = "Fuerte";
 		var strColor = "#5a74e3";
	}
	// -- Average
 	else if (nScore >= 50)
 	{
 		var strText = "Normal";
 		var strColor = "#8d7e00";
	}
	// -- Weak
 	else if (nScore >= 25)
 	{
 		var strText = "Débil";
 		var strColor = "#ff7f00";
	}
	// -- Very Weak
 	else
 	{
 		var strText = "Muy débil";
 		var strColor = "#e71a1a";
	}
	ctlBar.style.backgroundColor = strColor;
	ctlText.innerHTML = "<span style='color: " + strColor + ";'>" + strText + "</span>";
}
 
// Checks a string for a list of characters
function countContain(strPassword, strCheck)
{ 
	// Declare variables
	var nCount = 0;
	
	for (i = 0; i < strPassword.length; i++) 
	{
		if (strCheck.indexOf(strPassword.charAt(i)) > -1) 
		{ 
	        	nCount++;
		} 
	} 
 
	return nCount; 
}

/////////////////////////////////////
// Solicitud de password para BAJA //
/////////////////////////////////////

function comprobar_password()
{
		$.ajax(
	  {
	  	url: "/apoyo/comprobar_password.php",
	  	data:({password : $('#facebox input[name=password]').attr('value')}),
	  	type: "POST",
	  	success: ComprobarPassword
	  })
}

function ComprobarPassword(resp)
  {
  	if(resp == 'OK')
   	{
   		$('#div_error_baja').hide();
   		$('#form_razon_baja').submit();
   	}
   	else
   	{
   		$(document).trigger('close.facebox');
   		$('#div_error_baja').show();
   	}
  }
