// 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 email_0 = "";
	var email_1 = "";
	var cpf = "";
	var tipo_pessoa = "";

	// 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 == "password") || (e.type == "radio")
|| (e.type == "checkbox")) && !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;
			}


			// Gardamos os valores para o campo email para
			// Verificarmos a igualdade
			if (e.name == "email_0") {
				email_0 = e.value;
			} else if (e.name == "email_1") {
				email_1 = e.value;
			}

			// Gardamos os valores para o campo cpf_cgc para
			// Verificarmos a idoneidade
			if (e.name == "cpf") {
				cpf = e.value;
			}


			// Gardamos os valores para o campo tipo_pessoa para
			// definir tipo de validação cpf ou cnpj
			if (e.name == "tipo_pessoa" && e.checked) {
				tipo_pessoa = e.value;


			} 



			if (e.name == "declaracao" && !e.checked) {
				errors += "- Confirme que leu nossas condições de uso";
			}
			

			// 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";
	}

	if ( email_0 != email_1 ) {
		errors += "\n - Os campos email devem conter mesmo valor\n";
	}



	if ( cpf != "" ) {

		 alert("ok");
		s = cpf;
		var c = s.substr(0,9);
		var dv = s.substr(9,2);
		var d1 = 0;
 
		for (i = 0; i < 9; i++)
 
		{
	 
			d1 += c.charAt(i)*(10-i);
 
		}
 
		if (d1 == 0){
 

			//errors += "\n - CPF invalido\n";

			alert("CPF Invalido")
 
			return false;
 
		}
 
		d1 = 11 - (d1 % 11);
 
		if (d1 > 9) d1 = 0;
 
		if (dv.charAt(0) != d1)
 
		{
 
			// errors += "\n - CPF invalido\n";

			alert("CPF Invalido")
 
			return false;
			
 
		}
 
 
		d1 *= 2;
 
		for (i = 0; i < 9; i++)
 
		{
 
			d1 += c.charAt(i)*(11-i);
	 
		}
 
		d1 = 11 - (d1 % 11);
 
		if (d1 > 9) d1 = 0;
 
		if (dv.charAt(1) != d1)
 
		{
 
			// errors += "\n - CPF invalido\n";

			alert("CPF Invalido")
 
			return false;
			
 
		}
 
		//return true;
 

 
	}



if ( tipo_pessoa == "J" ) {

var cgc = cpf_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;

	}

	

}


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











