var Validator = function Validator()
{
	this.forms = new Array();
}

Validator.prototype.addForm = function(form, response)
{
	data = new Array();
	data['form'] = form;
	data['response'] = response;
	this.forms[this.forms.length] = data;
	this.errors = '';
	this.addTooltips(form);
	this.addMessages(form);
	
	$("#" + this.forms[0]['form'] + " button").click(function()
	{
		$("#error").remove();
		$("#ok").remove();
		$("#" + validator.forms[0]['response'] + ' p').remove();
		$("#" + validator.forms[0]['response'] + ' ul').remove();
		$(".input-error").removeClass('input-error');
		return validator.validate();
	});
}


Validator.prototype.addMessages = function(form)
{
	$('.ok').append('<p>' + noerrors_alert + '</p>');
	$('.error').append('<p>' + error_captcha + '</p>');
}


Validator.prototype.addTooltips = function(form)
{
	//$('#' + form + ' label + input.required, #' + form + ' label + textarea.required, #' + form + ' label + select.required').each(function()
	$('#' + this.forms[0]['form'] + ' .required').each(function()
	{
		var msg = '<strong>' + $(this).prev().html() + '</strong>' + empty;
		if($(this).attr('class') == 'required letter')
		{
			msg = '<strong>' + $(this).prev().html() + '</strong>' + letter;
		}
		else if($(this).attr('class') == 'required phone')
		{
			msg = '<strong>' + $(this).prev().html() + '</strong>' + phone;
		}
		else if($(this).attr('class') == 'required email')
		{
			msg = '<strong>' + $(this).prev().html() + '</strong>' + mail;
		}
		else if($(this).attr('class') == 'required nif')
		{
			msg = '<strong>' + $(this).prev().html() + '</strong>' + nif;
		}
		
		$(this).focus(function()
		{
			$('.tooltip').remove();
			$(this).prev().after('<div class="tooltip"><div class="tooltip_top"></div><p>' + msg + '</p><div class="tooltip_bottom"></div></div>');
			to = $(this).offset().top;
			lo = $(this).offset().left + 120;
			$('.tooltip').css({position:'absolute',top:to,left:lo});
		});
		
		$(this).keydown(function()
		{
			$('.tooltip').remove();
		});
	});
}

Validator.prototype.process = function(input, parent, type)
{
	this.errors += this.validateEmpty(input, parent, 'empty');
	if(this.validateEmpty(input, parent, 'empty') != '')
		$(input).addClass('input-error');
	if(type == 'letter')
	{
		this.errors += this.validateLetter(input, parent, type);
		if(this.validateLetter(input, parent, type) != '')
			$(input).addClass('input-error');
	}
	else if(type == 'email')
	{
		this.errors += this.validateEmail(input, parent, type);
		if(this.validateEmail(input, parent, type))
			$(input).addClass('input-error');
	}
	else if(type == 'phone')
	{
		this.errors += this.validatePhone(input, parent, type);
		if(this.validatePhone(input, parent, type))
			$(input).addClass('input-error');
	}
	else if(type == 'postcode')
	{
		this.errors += this.validatePostalCode(input, parent, type);
		if(this.validatePostalCode(input, parent, type))
			$(input).addClass('input-error');
	}
	else if(type == 'nif')
	{
		this.errors += this.validateNIF(input, parent, type);
		if(this.validateNIF(input, parent, type))
			$(input).addClass('input-error');
	}
	else if(type == 'number')
	{
		this.errors += this.validateNumber(input, parent, type);
		if(this.validateNumber(input, parent, type))
			$(input).addClass('input-error');
	}
	else if(type == 'bankaccount')
	{
		this.errors += this.validateBankAccount(input, parent, type);
		if(this.validateBankAccount(input, parent, type))
			$(input).addClass('input-error');
	}
	
	return this.errors;
}

Validator.prototype.getValidationText = function(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 == 'email')
		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;
}

Validator.prototype.validate = function()
{
	//$('#' + this.forms[0]['form'] + ' label + input.required, #' + this.forms[0]['form'] + ' label + textarea.required, #' + this.forms[0]['form'] + ' label + select.required').each(function()
																																																 	$('#' + this.forms[0]['form'] + ' .required').each(function()
	{
		
		//input
		var input = $(this);
		//p input container
		var parent = $(this).parent();
		//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
		validator.process(input, parent, type);
		
	});
	
	if(this.errors == '')
	{
		//alert('Ok');
		$("#" + validator.forms[0]['form']).submit();
	}
	else
	{
		//alert('Error');
		$("#" + validator.forms[0]['response']).append('<p>' + errors_found + '</p>');
		$("#" + validator.forms[0]['response']).append('<ul>' + this.errors + '</ul>');
		$("#" + validator.forms[0]['response']).fadeIn(1000);
	}
	
	this.errors = '';

	return false;
}

Validator.prototype.validateBankaccount = function(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;
}

Validator.prototype.validateBankAccount = function(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>" + this.getValidationText(type) + "</li>";
	}
	return error;
}

//This function test if input is not empty

Validator.prototype.validateEmpty = function(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>" + this.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

Validator.prototype.validateNIF = function(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>" + this.getValidationText(type) + "</li>";
	}
	return error;
}

//This function test if input is a valid phone number

Validator.prototype.validatePhone = function(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>" + this.getValidationText(type) + "</li>";
	}
	return error;
}

//This function test if input is a valid number

Validator.prototype.validateNumber = function(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>" + this.getValidationText(type) + "</li>";
	}
	return error;
}

//This function test if input is a valid postal code

Validator.prototype.validatePostalCode = function(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>" + this.getValidationText(type) + "</li>";
	}
	return error;
}

//This function test if input has only letter contents

Validator.prototype.validateLetter = function(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>" + this.getValidationText(type) + "</li>";
	}
	return error;
}

//This function test if input is a valid email adress

Validator.prototype.validateEmail = function(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>" + this.getValidationText(type) + "</li>";
	}
	return error;
}
