/************************************************
* 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 verificaDataform
* Verifica se um campo data é válido.
* Input: Campo do formulário que contém a data
* Esta função pega o campo diretamente, pois assim
* pode dar uma resposta melhor ao usuário.
*************************************************/

function verificaDataform(data){
	var Date = new String(data);
	Day = "";
	Month = "";
	Year = "";
	i =  0;
	for (i=0;(i<Date.length) && (Date.charAt(i) != '/');i++)
		Day = Day + Date.charAt(i);
	i++;
	for (;(i<Date.length) && (Date.charAt(i) != '/');i++)
		Month = Month + Date.charAt(i);
	i++;
	for (;(i<Date.length);i++)
		Year = Year + Date.charAt(i);
	for(i=0;i<Date.length;i++){
		NroAsc = asc(Date.substring(i,i+1))
		if (!(NroAsc>=48 && NroAsc<=57) || !(NroAsc = 47) )  {
			return false;
		}
	}
	if(!isNumeric(Month)) {
		return false;
	}
	if (eval(Month) > 12){
		return false;
	}
	if(!isNumeric(Day)) {
		return false;
	}
	if (eval(Day) > 31){
		return false;
	}
	if(!isNumeric(Year)) {
		return false;
	}
	if(eval(Year) < 1900) {
		return false;
	}
	return true;
}


/************************************************
* function verificaCPF
* Verifica se um CPF é válido
* Input: cpf a ser verificado
************************************************/

function verificaCPF(cpf)
{
	var dac = "", inicio = 2, fim = 10, soma, digito, i, j
	for (j=1;j<=2;j++) {
		soma = 0
		for (i=inicio;i<=fim;i++) {
			soma += parseInt(cpf.substring(i-j-1,i-j))*(fim+1+j-i)
		}
		if (j == 2) { soma += 2*digito }
		digito = (10*soma) % 11
		if (digito == 10) { digito = 0 }
		dac += digito
		inicio = 3
		fim = 11
	}
	return (dac == cpf.substring(cpf.length-2,cpf.length))
}

/************************************************
* function verificaCGC
* Verifica se um CGC é válido
* Input: cgc a ser verificado
************************************************/

function verificaCGC(scgc) {
	cgc = trimtodigits(scgc);
	if ((cgc.indexOf("-") != -1) || (cgc.indexOf(".") != -1) || (cgc.indexOf("/") != -1)){
		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) )
	return (dac == cgc.substring(cgc.length-2,cgc.length))
}

/************************************************
* 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 */


// 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;
}


function validaform(){
	if(isEmpty(document.cadSocio.nome.value) || !checkField(document.cadSocio.nome.value))
	{
		warnInvalid(document.cadSocio.nome,'O NOME está vazio ou contém caracteres inválidos!');
		return false;
	}
	if(isEmpty(document.cadSocio.nomepai.value) || !checkField(document.cadSocio.nomepai.value))
	{
		warnInvalid(document.cadSocio.nomepai,'O NOME DO PAI está vazio ou contém caracteres inválidos!');
		return false;
	}
	if(isEmpty(document.cadSocio.nomemae.value) || !checkField(document.cadSocio.nomemae.value))
	{
		warnInvalid(document.cadSocio.nomemae,'O NOME DA MÃE está vazio ou contém caracteres inválidos!');
		return false;
	}
	if(isEmpty(document.cadSocio.rg.value))
	{
		warnInvalid(document.cadSocio.nomemae,'O RG está vazio!');
		return false;
	}
	if(isEmpty(document.cadSocio.rg.value))
	{
		warnInvalid(document.cadSocio.nomemae,'O RG está vazio!');
		return false;
	}
	if(isEmpty(document.cadSocio.cpf.value) || !checkField(document.cadSocio.cpf.value))
	{
		warnInvalid(document.cadSocio.cpf,'O CPF está vazio ou contém caracteres inválidos!');
		return false;
	}
	else
	{
		var v_cpf = new String(document.cadSocio.cpf.value);
		bValida = false
		if (isDigit(v_cpf.charAt(0)) && isDigit(v_cpf.charAt(1)) && isDigit(v_cpf.charAt(2)) && isDigit(v_cpf.charAt(4)) && isDigit(v_cpf.charAt(5)) && isDigit(v_cpf.charAt(6)) && isDigit(v_cpf.charAt(8)) && isDigit(v_cpf.charAt(9)) && isDigit(v_cpf.charAt(10)) && isDigit(v_cpf.charAt(12)) && isDigit(v_cpf.charAt(13)))
			bValida = true;
		if (v_cpf.charAt(3) == "." && v_cpf.charAt(7) == "." && v_cpf.charAt(11) == "-")
			bValida = true;
		if (!bValida)
		{
			warnInvalid(document.cadSocio.cpf,'O CPF é inválido, verifique  o formato xxx.xxx.xxx-xx');
			return false;
		}
		if(isEmpty(document.cadSocio.cpf.value) || !verificaCPF(trimtodigits(document.cadSocio.cpf.value)))
		{
			warnInvalid(document.cadSocio.cpf,'O CPF está vazio ou é inválido!');
			return false;
		}
	}
	if(isEmpty(document.cadSocio.endereco.value) || !checkField(document.cadSocio.endereco.value))
	{
		warnInvalid(document.cadSocio.endereco,'O ENDEREÇO está vazio ou contém caracteres inválidos!');
		return false;
	}
	if(isEmpty(document.cadSocio.ddd.value) || !isNumber(document.cadSocio.ddd.value))
	{
		warnInvalid(document.cadSocio.ddd,'O DDD DO TELEFONE está vazio ou contém caracteres inválidos!');
		return false;
	}
	if(isEmpty(document.cadSocio.fone.value) || !isNumber(document.cadSocio.fone.value))
	{
		warnInvalid(document.cadSocio.fone,'O TELEFONE está vazio ou contém caracteres inválidos!');
		return false;
	}
	if(isEmpty(document.cadSocio.cidade.value) || !checkField(document.cadSocio.cidade.value))
	{
		warnInvalid(document.cadSocio.cidade,'A CIDADE está vazia ou contém caracteres inválidos!');
		return false;
	}
	if(isEmpty(document.cadSocio.cxpostal.value) || !checkField(document.cadSocio.cxpostal.value))
	{
		warnInvalid(document.cadSocio.cxpostal,'A CAIXA POSTAL está vazia ou contém caracteres inválidos!');
		return false;
	}
	if(isEmpty(document.cadSocio.cep1.value) || !isNumber(document.cadSocio.cep1.value))
	{
		warnInvalid(document.cadSocio.cep1,'O CEP está incompleto!');
		return false;
	}
	if(isEmpty(document.cadSocio.cep2.value) || !isNumber(document.cadSocio.cep2.value))
	{
		warnInvalid(document.cadSocio.cep2,'O CEP está incompleto!');
		return false;
	}
	return true;
}

function validaform2(){
	if(isEmpty(document.cadSocio.empresa.value) || !checkField(document.cadSocio.empresa.value))
	{
		warnInvalid(document.cadSocio.empresa,'A EMPRESA está vazia ou contém caracteres inválidos!');
		return false;
	}
	if(isEmpty(document.cadSocio.endereco.value) || !checkField(document.cadSocio.endereco.value))
	{
		warnInvalid(document.cadSocio.endereco,'O ENDEREÇO está vazio ou contém caracteres inválidos!');
		return false;
	}
	if(isEmpty(document.cadSocio.cnpj.value) || !checkField(document.cadSocio.cnpj.value))
	{
		warnInvalid(document.cadSocio.cnpj,'O CNPK está vazio ou contém caracteres inválidos!');
		return false;
	}
	if(isEmpty(document.cadSocio.contato.value) || !checkField(document.cadSocio.contato.value))
	{
		warnInvalid(document.cadSocio.contato,'O CONTATO está vazio ou contém caracteres inválidos!');
		return false;
	}
	if(isEmpty(document.cadSocio.email.value) || !verificaEmail(document.cadSocio.email.value))
	{
		warnInvalid(document.cadSocio.email,'O E-MAIL está vazio ou contém caracteres inválidos!');
		return false;
	}
	if(isEmpty(document.cadSocio.ddd.value) || !isNumber(document.cadSocio.ddd.value))
	{
		warnInvalid(document.cadSocio.ddd,'O DDD DO TELEFONE está vazio ou contém caracteres inválidos!');
		return false;
	}
	if(isEmpty(document.cadSocio.fone.value) || !isNumber(document.cadSocio.fone.value))
	{
		warnInvalid(document.cadSocio.fone,'O TELEFONE está vazio ou contém caracteres inválidos!');
		return false;
	}
	if(isEmpty(document.cadSocio.cidade.value) || !checkField(document.cadSocio.cidade.value))
	{
		warnInvalid(document.cadSocio.cidade,'A CIDADE está vazia ou contém caracteres inválidos!');
		return false;
	}
	return true;
}