// valida strings de texto
function isBlank(s) {
	for(var i = 0; i < s.length; i++) {

		var c = s.charAt(i);
		
		if(c != ' ' && c != '\n' && c != '\t') return false;
	}
	return true;
}

// valida numeros inteiros positivos
function isInteger(n) {
	var pattern = /^[0-9]+$/;
	return (n != "" && pattern.test(n));
}

// valida datas no formato aaaa-mm-dd
var days_of_month = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
	
function isDate(d) {
	var reg = d.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/)
	
	if(reg == null) {
		return false;
	}
	if(reg[1] < 1900 || reg[2] < 1 || reg[2] > 12) {
		return false;
	}
	var max_day = days_of_month[reg[2] - 1] + (reg[2] == 2 && (reg[1] & 3) == 0 ? 1 : 0);
	
	if(reg[3] < 1 || reg[3] > max_day) {
		return false;
	}
	return true;
}

/*
Campos definidos pelo utilizador:
	required	- campo obrigatório
	minlength	- comprimento mínimo para o campo
	numeric		- campo numérico
	integer		- campo numérico inteiro positivo
	min			- valor mínimo para o campo
	max			- valor máximo para o campo
	date		- campo data
*/
function validateForm(f) {
	var msg = "";
	
	for(var i = 0; i < f.length; i++) {
		var e				= f.elements[i];
		var description		= (e.description ? e.description : e.name);
		var validate		= e.required || !isBlank(e.value);
		
		if(e.type == "text" || e.type == "textarea" || e.type == "password" || e.type == "file") {
			if(validate && isBlank(e.value)) {
				msg += "- The field " + description + " must be filled out\n";
				continue;
			}
			if(validate && e.minlength != null && e.value.length < e.minlength) {
				msg += "- The field " + description + " must have " + e.minlength + " ou mais caracteres\n";
				continue;
			}
			if(validate && (e.numeric || e.integer || e.min != null || e.max != null)) {
				var n = parseFloat(e.value);
				
				if(isNaN(n)) {
					msg += "- The field " + description + " não é um número válido\n";
				}
				else if(e.integer && !isInteger(e.value)) {
					msg += "- The field " + description + " não é um número inteiro positivo\n";
				}
				else if(e.min != null && n < e.min) {
					msg += "- The field " + description + " tem de ser um número maior ou igual a " + e.min + "\n";
				}
				else if(e.max != null && n > e.max) {
					msg += "- The field " + description + " tem de ser um número menor ou igual a " + e.max + "\n";
				}
				continue;
			}
			if(validate && e.date && !isDate(e.value)) {
				msg += "- The field " + description + " não é uma data válida.\n";
			}
		}
	}
	if(msg != "") {
		var message = "The following errors had occurred when submitting this form!\n";
		message += "Please correct them and try again:\n\n";
		message += msg;
		alert(message);
		return false;
	}
	return true;
}
