function trim(str)
{
	if (typeof(str) != "string")
	{ return str; }
	
	strReturn = str.replace(/&nbsp;/," "); // replace &nbsp; with a real spaces		
	strReturn = strReturn.replace(/ {2,}/g," "); // eliminate every two spaces
	strReturn = strReturn.replace(/^\s+|\s+$/g, ""); // trim spaces at beginning and end
	
	return strReturn;
}

function validateForm()
{
	var args = validateForm.arguments;
	var strErrors = "";
	var pos = -1;
	var val = "", i, aux = 0;
	var objName = "";
	
	for (i = 0; i < (args.length-1); i+=2)
	{
		obj = args[i];
		conditions = args[i+1];
		if (obj.type != "file")
		{ obj.value = trim(obj.value); }
		objName = obj.title;
		
		if (obj.value != "")
		{
			pos = conditions.search(/[0-9]/g);
			if (pos != -1) // minimum length restriction
			{
				aux = parseInt(conditions.substr(pos),10);
				if ((aux > 0) && (obj.value.length < aux))
				{
					strErrors += "- " + objName + " deve conter, no mínimo, " + aux + " caracteres.\n";
					continue;
				}
			}
			
			if (conditions.indexOf("int") != -1)
			{
				if (obj.value.search(/[^0-9]/g) != -1)
				{ strErrors += "- " + objName + " deve conter um número inteiro não-negativo.\n"; }
			}
			else if (conditions.indexOf("email") != -1)
			{				
				if (obj.value.search(/^[A-Z0-9._-]+@[A-Z0-9._-]+\.[A-Z]{2,}$/gi) == -1)
				{ strErrors += "- " + objName + " deve conter um endereço de E-mail.\n"; }
			}
			else if (conditions.indexOf("pwd") != -1)
			{
				if (obj.value.search(/\W/g) != -1)
				{ strErrors += "- " + objName + " não pode ter outros caracteres para além de letras, números e _ (underscore).\n"; }
			}
			else if (conditions.indexOf("file") != -1)
			{
				if (obj.value.search(/'/g) != -1)
				{ strErrors += "- " + objName + " não pode conter ' (plica). Por favor, renomeie o ficheiro.\n"; }
				else
				{
					val = conditions.substring(conditions.indexOf("("),conditions.lastIndexOf(")")+1);						
					re = new RegExp("^.+\\." + val + "$","gi");
					if (obj.value.search(re) == -1)
					{ 
						val = val.replace(/[\(\)]/g,"");
						val = val.replace(/\|/g,",").toUpperCase();
						strErrors += "- " + objName + " apenas pode ter um ficheiro do(s) tipo(s) " + val + ".\n";
					}
				}
			}
		}
		else if (conditions.indexOf("R") != -1)			
		{ strErrors += "- " + objName + " é obrigatório.\n"; }
	}
	
	if (strErrors != "")
	{ alert("Ocorreram os seguintes erros:\n" + strErrors); }
		
	document.canSubmitForm = (strErrors == "");	
}