/************************************************
* function checkField
* Verificação básica de um campo de formulário por "coisas bobas": & < > | \ / 
* Input: campo a ser verificado
************************************************/

function checkField(s) {
	if ((s.indexOf("&")>=0) || (s.indexOf("<")>=0) || (s.indexOf(">")>=0) || (s.indexOf("|")>=0) || (s.indexOf("\"")>=0) || (s.indexOf("/")>=0) )
		return false;
	return true;
}

/************************************************
* function isEmpty
* Verifica se um campo está vazio
* Input: campo a ser verificado
************************************************/		

function isEmpty(s) {
	return ((s == null) || (s.length == 0));
}


/************************************************
* function verificaEmail
* Verifica se um email é válido
* Input: email a ser verificado
************************************************/

function verificaEmail(email) {
	var s = new String(email);
	// { } ( ) < > [ ] | \ /
	if ((s.indexOf("{")>=0) || (s.indexOf("}")>=0) || (s.indexOf("(")>=0) || (s.indexOf(")")>=0) || (s.indexOf("<")>=0) || (s.indexOf(">")>=0) || (s.indexOf("[")>=0) || (s.indexOf("]")>=0) || (s.indexOf("|")>=0) || (s.indexOf("\"")>=0) || (s.indexOf("/")>=0) )
		return false;
	if (vogalAcentuada(email))
		return false;
	// & * $ % ? ! ^ ~ ` ' "
	if ((s.indexOf("&")>=0) || (s.indexOf("*")>=0) || (s.indexOf("$")>=0) || (s.indexOf("%")>=0) || (s.indexOf("?")>=0) || (s.indexOf("!")>=0) || (s.indexOf("^")>=0) || (s.indexOf("~")>=0) || (s.indexOf("`")>=0) || (s.indexOf("'")>=0) )
		return false;
	// , ; : = #
	if ((s.indexOf(",")>=0) || (s.indexOf(";")>=0) || (s.indexOf(":")>=0) || (s.indexOf("=")>=0) || (s.indexOf("#")>=0) )
		return false;
	// procura se existe apenas um @
	if ( (s.indexOf("@") < 0) || (s.indexOf("@") != s.lastIndexOf("@")) )
		return false;
	// verifica se tem pelo menos um ponto após o @
	if (s.lastIndexOf(".") < s.indexOf("@"))
		return false;
	return true;
}

/************************************************
* function verificaCEP
* Verifica se o CEP está no formato correto
* Input: CEP a ser verificado
************************************************/

function verificaCEP (cep) {
	s = new String(cep);
	if ((s.length > 9) || (s.length < 5))
		return false;
	if (!isInteger(cep))
		return false;
	return true;
}

/************************************************
* function isInteger
* Verifica se um campo é inteiro, inclui dígitos de 0 a 9, vírgula, ponto, espaços e -
* Input: campo a ser verificado
************************************************/

function isInteger(s){
	var i;
	if (isEmpty(s)) 
		return false;
	for (i = 0; i < s.length; i++)
	{   
		var c = s.charAt(i);
		if (!isNumber(c)) return false;
	}
	return true;
}

/************************************************
* function isNumeric
* Verifica se um campo é numérico. Se contém apenas dígitos de 0 a 9
* Input: campo a ser verificado
************************************************/

function isNumeric(s){
	var i;
	if (isEmpty(s)) 
		return false;
	for (i = 0; i < s.length; i++)
	{   
		var c = s.charAt(i);
		if (!isDigit(c)) return false;
	}
	return true;
}

/************************************************
* function warnInvalid
* Gera um alert para o usuário e volta o foco para
* o campo que está com problema
* Input: theField - campo do formulário com problema
*        warnText - texto a ser mostrado no alert
************************************************/

function warnInvalid (theField, warnText)
{   theField.focus()
    theField.select()
	alert(warnText)
    return false
}

// Verifica se o caracter pode fazer parte de um número: 0-9 , . ( ) - e espaço
function isNumber (c)
{ return ((c >= "0") && (c <= "9") || (c=="-") || (c=="(") || (c==")") || (c==" ") || (c==".") || (c==",")) }

// Verifica se o caracter é um dígito de 0 a 9
function isDigit (c)
{ return ((c >= "0") && (c <= "9")) }

// Verifica se uma string tem vogais acentuadas
function vogalAcentuada(s) {
	ls = s.toLowerCase();
	if ((ls.indexOf("á")>=0) || (ls.indexOf("à")>=0) || (ls.indexOf("ã")>=0) || (ls.indexOf("â")>=0) || (ls.indexOf("é")>=0) || (ls.indexOf("í")>=0) || (ls.indexOf("ó")>=0) || (ls.indexOf("õ")>=0) || (ls.indexOf("ô")>=0) || (ls.indexOf("ú")>=0) || (ls.indexOf("ü")>=0))
		return true;
}

// Gera uma string com os caracteres básicos na sequência de códigos ASC
function makeCharsetString(){
	var astr
	astr = ' !"#$%&\'()*+,-./0123456789:;<=>?@'
	astr+= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
	astr+= '[\]^_`abcdefghijklmnopqrstuvwxyz'
	astr+= '{|}~'
	return astr
}

// Retorna o código ASC do caracter passada por parâmetro
function asc(achar){
	var n=0;
	var ascstr = makeCharsetString()
	for(i=0;i<ascstr.length;i++){
		if(achar==ascstr.substring(i,i+1)){
			n=i;
			break;
		}
	}
	return n+32
}

//Remove todos os caracteres excetos 0-9
function trimtodigits(tstring){
  s=""; 
  ts=new String(tstring);
  for (x=0;x<ts.length;x++){
   ch=ts.charAt(x);
    if (asc(ch)>=48 && asc(ch)<=57){
      s=s+ch;
    }
  }
  return s;
}
/*inicio */


//Remove todos os caracteres excetos 0-9
function trimtodigits(tstring){
  s="";
  ts=new String(tstring);
  for (x=0;x<ts.length;x++){
   ch=ts.charAt(x);
    if (asc(ch)>=48 && asc(ch)<=57){
      s=s+ch;
    }
  }
  return s;
}

// Retorna o código ASC do caracter passada por parâmetro
function asc(achar){
	var n=0;
	var ascstr = makeCharsetString()
	for(i=0;i<ascstr.length;i++){
		if(achar==ascstr.substring(i,i+1)){
			n=i;
			break;
		}
	}
	return n+32
}
// Gera uma string com os caracteres básicos na sequência de códigos ASC
function makeCharsetString(){
	var astr
	astr = ' !"#$%&\'()*+,-./0123456789:;<=>?@'
	astr+= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
	astr+= '[\]^_`abcdefghijklmnopqrstuvwxyz'
	astr+= '{|}~'
	return astr
}

// Verifica se uma string tem vogais acentuadas
function vogalAcentuada(s) {
	ls = s.toLowerCase();
	if ((ls.indexOf("á")>=0) || (ls.indexOf("à")>=0) || (ls.indexOf("ã")>=0) || (ls.indexOf("â")>=0) || (ls.indexOf("é")>=0) || (ls.indexOf("í")>=0) || (ls.indexOf("ó")>=0) || (ls.indexOf("õ")>=0) || (ls.indexOf("ô")>=0) || (ls.indexOf("ú")>=0) || (ls.indexOf("ü")>=0))
	return true;
}

// Verifica se o caracter pode fazer parte de um número: 0-9 , . ( ) - e espaço
function isNumber (c) { 
	return ((c >= "0") && (c <= "9") || (c=="-") || (c=="(") || (c==")") || (c==" ") || (c==".") || (c==",")) 
}

// Verifica se o caracter é um dígito de 0 a 9
function isDigit (c) { 
	return ((c >= "0") && (c <= "9")) 
}

/************************************************
* function checkField
* Verificação básica de um campo de formulário por "coisas bobas": & < > | \ /
* Input: campo a ser verificado
************************************************/

function checkField(s) {
	if ((s.indexOf("&")>=0) || (s.indexOf("<")>=0) || (s.indexOf(">")>=0) || (s.indexOf("|")>=0) || (s.indexOf("\"")>=0) || (s.indexOf("/")>=0) )
		return false;
	return true;
}

/************************************************
* function isEmpty
* Verifica se um campo está vazio
* Input: campo a ser verificado
************************************************/

function isEmpty(s) {
	return ((s == null) || (s.length == 0));
}
/************************************************
* function warnInvalid
* Gera um alert para o usuário e volta o foco para
* o campo que está com problema
* Input: theField - campo do formulário com problema
*        warnText - texto a ser mostrado no alert
************************************************/

function warnInvalid (theField, warnText)
{   theField.focus()
    theField.select()
	alert(warnText)
    return false
}

/************************************************
* function warnInvalid_SelectBox
* Gera um alert para o usuário e volta o foco para
* o campo que está com problema
* Esta função é específica para ser usada com campos Select, para outros campos, usar a warnInvalid
* Input: theField - campo do formulário com problema
*        warnText - texto a ser mostrado no alert
************************************************/

function warnInvalid_SelectBox (theField, s)
{
	theField.focus();
	alert(s);
	return false;
}

// Retorna A MOD B
function mod(a,b){
	temp = Number(b);
	ok=1;
	ant=0;
	if (Number(b)>Number(a)){
		ret=a;
		ok="0";
	}
		while(ok=="1"){
			if (Number(a) >= Number(temp)){
				ant=Number(temp);
				temp=Number(temp)+Number(b);
			}else{
				ret=Number(a)-Number(ant);
				ok = "0";
			     }
		}
	return ret;
}

/*fim*/
function validaform(){
	if(isEmpty(document.formcadastro.nome.value) || !checkField(document.formcadastro.nome.value))
	{
		warnInvalid(document.formcadastro.nome,'O NOME está vazia ou é inválido!');
		return false;
	}
	if(isEmpty(document.formcadastro.profissao.value) || !checkField(document.formcadastro.profissao.value))
	{
		warnInvalid(document.formcadastro.profissao,'A PROFISSÃO está vazia ou é inválido!');
		return false;
	}
	if(isEmpty(document.formcadastro.endereco.value) || !checkField(document.formcadastro.endereco.value))
	{
		warnInvalid(document.formcadastro.endereco,'O ENDERECO está vazio ou contém caracteres inválidos!');
		return false;
	}	
	
	//if(isEmpty(document.formcadastro.numero.value) || !isInteger(document.formcadastro.numero.value))
	//{
	//	warnInvalid(document.formcadastro.numero,'O NÚMERO está vazio ou é inválido!');
//		return false;
//	}
	if(isEmpty(document.formcadastro.cidade.value) || !checkField(document.formcadastro.cidade.value))
	{
		warnInvalid(document.formcadastro.cidade,'A CIDADE está vazia ou é inválido!');
		return false;
	}
//	if(isEmpty(document.formcadastro.ddd.value) || !isInteger(document.formcadastro.ddd.value))
//	{
//		warnInvalid(document.formcadastro.ddd,'O DDD está vazio ou é inválido!');
//		return false;
//	}
	if(isEmpty(document.formcadastro.telefone.value) || !isInteger(document.formcadastro.telefone.value))
	{
		warnInvalid(document.formcadastro.telefone,'O TELEFONE está vazio ou é inválido!');
		return false;
	}
	if(isEmpty(document.formcadastro.email.value) || !verificaEmail(document.formcadastro.email.value))
	{
		warnInvalid(document.formcadastro.email,'O E-MAIL está vazio ou contém caracteres inválidos!');
		return false;
	}
	
	/*if(isEmpty(document.formcadastro.cep.value) || !verificaCEP(document.formcadastro.cep.value))
	{
		warnInvalid(document.formcadastro.cep,'O CEP está vazio ou é inválido!');
		return false;
	}*/
    
	document.formcadastro.submit();
	return true;
}

