// This script was extract from the book
// "Javascript - The Definitive Guide"
// O'Reilly, pg. 312


// A utility function that returns true if a string contains only
// whitespace characters.
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;
}

// This is the function that performs form verification. It will be invoked
// from the onSubmit() event handler. The handler should return whatever
// value this function returns.
function verify(f)
{

	var msg;
	var empty_fields = "";
	var errors = "";
	var pass_0 = "";
	var pass_1 = "";

	// loop through the elements of the form, looking for all
	// text and textarea elements that don´t have an "optional" property
	// defined. Then, check for fields that are empty and make a list of them.
	// also, if any of these elements have a "min" or a "max" property defined,
	// then verify that they are numbers and that they are in the right range.
	// Put together error messages for fields that are wrong.
	for(var i = 0; i < f.length; i++) {
		var e = f.elements[i];
		if (((e.type == "text") ||
			 (e.type == "textarea") ||(e.type == "checkbox")|| (e.type == "password")) && !e.optional) {
			// first check if the field is empty
			if ((e.value == null) || (e.value == "") || isblank(e.value)) {
			empty_fields += "\n          " + e.name;
			continue;
			}
			
			// Gardamos os valores para o campo senha para
			// Verificarmos a igualdade
			if (e.name == "senha_0") {
				pass_0 = e.value;
			} else if (e.name == "senha_1") {
				pass_1 = e.value;
			}



			// Now check for fields that are supposed to be numeric.
			if (e.numeric) {
				var v = parseFloat(e.value);
				if (isNaN(v)) {
					errors += "- O campo " + e.name + " deve conter um número";
					errors += ".\n";

				} // end if

			} // end if
		
		} // end if

	} // end for

	
	if ( pass_0 != pass_1 ) {
		errors += "\n - Os campos senha devem conter mesmo valor\n";
	}


	// Now, if there were any errors, display the messages, and
	// return false to prevent the form from being submitted.
	// Otherwise return true.
	if (!empty_fields && !errors) return true;

	msg  = "______________________________________________________\n\n";
	msg += "O formulário não foi submetido por causa do(s) seguinte(s) erro(s).\n";
	msg += "Por favor corrija-o(s) e submita-o novamente.\n";
	msg += "______________________________________________________\n\n";

	if (empty_fields) {
		msg += "- O(s) seguinte(s) campo(s) exigido(s) está/estão vazio(s):";
		msg += empty_fields + "\n";
		if (errors) msg += "\n"; 

	}

	msg += errors;
	alert(msg);
	return false;


} // end verify











