var errors = '';
var hasErrors = false;
var form_name = '';

//Set tooltips when document is loaded
$(document).ready(function()
{
	setTooltips();
});

function getValidationText(validation)
{
	//This function return the correct language var from type (required "type")
	if(validation == 'letter')
		return letter;
	else if(validation == 'nif')
		return nif;
	else if(validation == 'mail')
		return mail;
	else if(validation == 'phone')
		return phone;
	else if(validation == 'empty')
		return empty;
	else if(validation == 'postcode')
		return postcode;
	else if(validation == 'nif')
		return nif;
	else if(validation == 'number')
		return number;
	else if(validation == 'bankaccount')
		return bankaccount;
}

function setTooltips()
{
	//For each input with class required
	$(".required").each(function(i)
	{
		//p input container
		var parent = $(this).parent();
		//input
		var input = $(this);
		//validation type (ex: letter, nif, phone...)
		if($(this).attr('class') != 'required') var type = input.attr("class").substring(9);
		else var type = 'empty';
		
		if($(this).attr("type") != "checkbox")
		{
			//Add focus event (tooltip)
			input.focus(function(e)
			{
				$(parent).append('<div class="tooltip">' + getValidationText(type) + '</div>');
				$(".tooltip").fadeIn(400);
			});
	
			//Add blur event (basically removing focus event)
			input.blur(function(e)
			{
				$(".tooltip").remove();
			});
			
			if(type == "bankaccount")
			{
				input.keypress(function(e)
				{
					var key = e.keyCode ? e.keyCode : e.which;
					return (key <= 40 || (key >= 48 && key <= 57) && $(this).val().length < 23);
				});
			}
		
			input.keyup(function(e)
			{
				var key = e.keyCode ? e.keyCode : e.which;
				
				if(key != '9') $(".tooltip").remove();
				if(type == "bankaccount")
				{
					var aux_string = $(this).val().replace(/-/g, '');

					if(aux_string.length == 4 || aux_string.length == 8 || aux_string.length == 10)
					{
						if(key != 8 && $(this).val().substring($(this).val().length - 1) != '-')
							$(this).val($(this).val() + "-");
						else
							$(this).val($(this).val().substring(0, $(this).val().length - 1))
					}
				}
				if(hasErrors)
				{
					validate(form_name, false);
				}
			});
		}
		else
		{
			input.click(function(e)
			{
				if(hasErrors)
				{
					validate(form_name, false);
				}
			});
		}
	});
}

function validate(form, clicked)
{
	if(clicked == null)
		clicked = true;
	//For each input with class required
	$(".required").each(function(i)
	{
		//p input container
		var parent = $(this).parent();
		//input
		var input = $(this);
		//validation type (ex: letter, nif, phone...)
		if($(this).attr('class') != 'required') var type = input.attr("class").substring(9);
		else var type = 'empty';
		
		//Make the validation
		process(input, parent, type);
	});
	
	if(errors == '' && clicked)
	{
		form.submit();
	}
	else if(errors == '')
	{
		$("#response").html('<p>' + noerrors_found + '</p>');
	
		$("#response").attr('class','noerrors');
	}
	else
	{
		$("#response").html('<p>' + errors_found + '</p>');
		$("#response").append('<ul>');
		$("#response").append(errors);
		$("#response").append('</ul>');
		
		$("#response").attr('class','errors');
		
		errors = '';
		hasErrors = true;
		form_name = form;
		return false;
	}
}

function process(input, parent, type)
{
	errors += validateEmpty(input, parent, 'empty');
	if(type == 'letter')
		errors += validateLetter(input, parent, type);
	else if(type == 'mail')
		errors += validateEmail(input, parent, type);
	else if(type == 'phone')
		errors += validatePhone(input, parent, type);
	else if(type == 'postcode')
		errors += validatePostalCode(input, parent, type);
	else if(type == 'nif')
		errors += validateNIF(input, parent, type);
	else if(type == 'number')
		errors += validateNumber(input, parent, type);
	else if(type == 'bankaccount')
		errors += validateBankAccount(input, parent, type);
		
	return errors;
}

//This function validate if value is a valid bankaccount number

function validateBankaccount(value)
{	
	var numero = value.replace(/-/g,"");

	var factores1 = new Array(4, 8, 5, 10, 9, 7, 3, 6);
	var factores2 = new Array(1, 2, 4, 8, 5, 10, 9, 7, 3, 6);

	var suma1 = 0;
	var suma2 = 0;

	for(j = 0; j < 8; j++)
		suma1 += parseInt(numero.charAt(j)) * parseInt(factores1[j]);
	for(j = 0; j < 10; j++)
		suma2 += parseInt(numero.charAt(10 + j)) * parseInt(factores2[j]);

	var resto1 = suma1 % 11;
	var resto2 = suma2 % 11;
	var clave1 = 0;
	var clave2 = 0;

	if(resto1 == 0 || resto1 == 1) clave1 = resto1; else clave1 = 11 - resto1;
	if(resto2 == 0 || resto2 == 1) clave2 = resto2; else clave2 = 11 - resto2;

	return numero.charAt(8) == clave1 && numero.charAt(9) == clave2;
}

function validateBankAccount(field, parent, type)
{
	error = '';
	if(field.val() != "" && !validateBankaccount($(field).val()))
	{
		var label = '';
		$("label").each(function(e)
		{
			if($(this).attr("for") == $(field).attr("name"))
				label = $(this).html();
		});
		error = "<li>" + "<strong>" + label + "</strong>" + getValidationText(type) + "</li>";
	}
	return error;
}

//This function test if input is not empty

function validateEmpty(field, parent, type)
{
	error = '';
	
	if(field.val() == '' && field.attr("type") != "checkbox")
	{
		var label = '';
		$("label").each(function(e)
		{
			if($(this).attr("for") == $(field).attr("name"))
				label = $(this).html();
		});
		error = "<li>" + "<strong>" + label + "</strong>" + getValidationText(type) + "</li>";
	}
	else if(field.attr("type") == "checkbox" && !field.is(":checked"))
	{
		var label = '';
		$("label").each(function(e)
		{
			if($(this).attr("for") == $(field).attr("name"))
				label = $(this).html();
		});
		error = "<li>" + "<strong>" + label + "</strong>" + checkbox + "</li>";
	}
	return error;
}

//This function test if input is a valid nif number

function validateNIF(field, parent, type)
{	
	var regNif = /^[0-9]{8,8}[a-zA-Z]{1,1}$/;
	var regRes = /^(X|x)[0-9]{7,7}[a-zA-Z]{1,1}$/;
	var error = "";

	//Test if the letter match with the number

	var dni = field.val().substring(0, field.val().length -1);
	var lockup = 'TRWAGMYFPDXBNJZSQVHLCKE';
	var isValid = field.val().charAt(field.val().length -1).toUpperCase() == lockup.charAt(dni % 23);
	
	//Test if is a correct NIF or Residence Permission number

	if(field.val() != "" && !((field.val().match(regRes) || field.val().match(regNif)) && isValid))
	{
		var label = '';
		$("label").each(function(e)
		{
			if($(this).attr("for") == $(field).attr("name"))
				label = $(this).html();
		});
		error = "<li>" + "<strong>" + label + "</strong>" + getValidationText(type) + "</li>";
	}
	return error;
}

//This function test if input is a valid phone number

function validatePhone(field, parent, type)
{	
	var regExp = /(^([0-9]{9,9})|^)$/;
	var error = "";

	if(!field.val().match(regExp) && field.val() != '')
	{
		var label = '';
		$("label").each(function(e)
		{
			if($(this).attr("for") == $(field).attr("name"))
				label = $(this).html();
		});
		error = "<li>" + "<strong>" + label + "</strong>" + getValidationText(type) + "</li>";
	}
	return error;
}

//This function test if input is a valid number

function validateNumber(field, parent, type)
{	
	var regExp = /^[0-9]/;
	var error = "";

	if(!field.val().match(regExp) && field.val() != '')
	{
		var label = '';
		$("label").each(function(e)
		{
			if($(this).attr("for") == $(field).attr("name"))
				label = $(this).html();
		});
		error = "<li>" + "<strong>" + label + "</strong>" + getValidationText(type) + "</li>";
	}
	return error;
}

//This function test if input is a valid postal code

function validatePostalCode(field, parent, type)
{	
	var regExp = /^(5[0-2]|[0-4][0-9])[0-9]{3}$/;
	var error = "";

	if(!field.val().match(regExp) && field.val() != '')
	{
		var label = '';
		$("label").each(function(e)
		{
			if($(this).attr("for") == $(field).attr("name"))
				label = $(this).html();
		});
		error = "<li>" + "<strong>" + label + "</strong>" + getValidationText(type) + "</li>";
	}
	return error;
}

//This function test if input has only letter contents

function validateLetter(field, parent, type)
{
	var regExp = /^(?:\+|-)?[A-Za-záéíóúàèìòù ]+$/;
	var error = "";
	
	if(!field.val().match(regExp) && field.val() != '')
	{
		var label = '';
		$("label").each(function(e)
		{
			if($(this).attr("for") == $(field).attr("name"))
				label = $(this).html();
		});
		error = "<li>" + "<strong>" + label + "</strong>" + getValidationText(type) + "</li>";
	}
	return error;
}

//This function test if input is a valid email adress

function validateEmail(field, parent, type)
{
	var regExp = /^[A-Za-z0-9._%-]+@+[A-Za-z0-9.-]+\.+([A-Za-z]{2,4})$/;
	var error = "";
	
	if(!field.val().match(regExp) && field.val() != '')
	{
		var label = '';
		$("label").each(function(e)
		{
			if($(this).attr("for") == $(field).attr("name"))
				label = $(this).html();
		});
		error = "<li>" + "<strong>" + label + "</strong>" + getValidationText(type) + "</li>";
	}
	return error;
}
