//---------------------------------------------------------------------------------
// Form Validator - By Rafael C.P. rcpinto@inf.ufrgs.br
//---------------------------------------------------------------------------------

function validacampo(campo) {
	var id = campo.getAttribute('id');
 	if (id == '' || id == null) id = campo.name;
 	var invalid = campo.form.getAttribute('invalid');
 	if (!invalid) invalid = 'Campo Inválido: ';
 	var errormsg = invalid+'\''+id+'\'';
 	if (campo.getAttribute('required') != null && campo.value == '') {
  		alert(errormsg);campo.focus();return false;
 	}
 	if (campo.getAttribute('validation') != null && campo.value != '') {
  		var r = regexp(campo.getAttribute('validation'));
  		if (!r.test(campo.value)) {
  			alert(errormsg);
			campo.focus();
			return false
		}
 	}
 	return true;
}

function validaform(f) {
	var resultado = true;
 	for (i = 0; i < f.length; i++) {
  		resultado = resultado && validacampo(f.elements[i]);
 	}
 	return resultado;
}

function regexp(tipo) {
	tipo = tipo.toLowerCase();
	var r = new RegExp(tipo);
	if (tipo == 'email' || tipo == 'e-mail') r =  /^[^@ :]{2,}@[^@ :]{2,}\.\w{2,4}(\.\w{2})?$/;
	if (tipo == 'ip') r = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
	if (tipo == 'float' || tipo == 'real' || tipo == 'fracionario') r = /^[-+]?([0-9]*[.,])?[0-9]+([eE][-+]?[0-9]+)?$/;
	if (tipo == 'moeda') r = /^[0-9]+(,[0-9]{2})?$/;
	if (tipo == 'currency') r = /^[0-9]+(\.[0-9]{2})?$/;
	if (tipo == 'mm/dd/yyyy' || tipo == 'date') r = /^(0[1-9]|1[012])\/(0[1-9]|[12][0-9]|3[01])\/\d{4}$/;
	if (tipo == 'dd/mm/yyyy' || tipo == 'data') r = /^(0[1-9]|[12][0-9]|3[01])\/(0[1-9]|1[012])\/\d{4}$/;
	if (tipo == 'zip' || tipo == 'cep') r = /^\d{5}(-?\d{3})?$/;
	if (tipo == 'phone' || tipo == 'fone') r = /^[\d\-() ]+$/;
	if (tipo == 'letters' || tipo == 'letras') r = /^[a-zA-Z]+$/;
	if (tipo == 'numbers' || tipo == 'numeros') r = /^[0-9]+$/;
	return r;
}
