// 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 = "";
	var cnpj = "";
	var cnt = 0;

	// 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 == "file") ||
			 (e.type == "password")||
			 (e.type == "radio")||
			 (e.type == "select-one")) && !e.optional) {
			// first check if the field is empty
			if ((e.value == null) || (e.value == "") || isblank(e.value)) {
			empty_fields += "\n          " + e.name;
			continue;
			}
			if (e.name=="santuario" && e.checked) {
				cnt = 1;
			} 
			// Gardamos os valores para o campo senha para
			// Verificarmos a igualdade
			if (e.name == "senha") {
				pass_0 = e.value;
			} else if (e.name == "senha1") {
				pass_1 = e.value;
			}

			if (e.name == "cnpj") {
				cnpj = e.value;
			}

			if (e.name == "email") {
				
				var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
				if (! filter.test(e.value)) {
				errors += "Email inválido";
					errors += ".\n";

				}
			}

			// 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 apenas números";
					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";
	}
	

	if ( cnt == 0) {
		alert("Escolha pelo menos um Santuário");	
	}*/

	

	if ( cnpj != "" ) {
		 
		var cgc = cnpj;

 		if ((cgc.indexOf("-") != -1) || (cgc.indexOf(".") != -1) || (cgc.indexOf("/") != -1)){
				alert("O CGC deve conter somente números.")
				return( false )
		}
  		var df, resto, dac = ""
		df = 5*cgc.charAt(0)+4*cgc.charAt(1)+3*cgc.charAt(2)+2*cgc.charAt(3)+9*cgc.charAt(4)+8*cgc.charAt(5)+7*cgc.charAt(6)+6*cgc.charAt(7)+5*cgc.charAt(8)+4*cgc.charAt(9)+3*cgc.charAt(10)+2*cgc.charAt(11)
		resto = df % 11
		dac += ( (resto <= 1) ? 0 : (11-resto) )
		df = 6*cgc.charAt(0)+5*cgc.charAt(1)+4*cgc.charAt(2)+3*cgc.charAt(3)+2*cgc.charAt(4)+9*cgc.charAt(5)+8*cgc.charAt(6)+7*cgc.charAt(7)+6*cgc.charAt(8)+5*cgc.charAt(9)+4*cgc.charAt(10)+3*cgc.charAt(11)+2*parseInt(dac)
		resto = df % 11
		dac += ( (resto <= 1) ? 0 : (11-resto) )

		if ( (dac == cgc.substring(cgc.length-2,cgc.length)) == false) {

			alert("CNPJ inválido");
			return false;

		}
		//return true;
	}

	// 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











