function isEmpty(s) {
	return ((s == null) || (s.length == 0) || (s.charAt(0) == " "));}

function qtdnomes(s) {
	qtd=s.split(" ");
	n=qtd.length;
	return (n < 2);}

function ifspace(s) {
    n=0;
	for (i=0;i < s.length;i++)
	{ if (s.charAt(i) == " ")
	  n++;
	}
	return (n != 0);}

function isNumerico(s) {
    n=0;
	t=0;
	c=0;
	for (i=0;i < s.length;i++)	{
	  if ((s.charAt(i) == "-") || (s.charAt(i) == "-")) t++
	  else
	  if ((s.charAt(i) >= "0") && (s.charAt(i) <= "9")) n++
	  else
	  c++;	}
	return (c != 0) || (t > 1);}

function ValidaCPF (cpf) {
	cpf = sonumero (cpf);
    if (cpf.length != 11)
		return 1;
    for (i = 10; i <= 11; i++) {
		d = 0
		for (j = i; j >= 2; j--)
	    	d += parseInt (cpf.charAt (i-j)) * j
			d = (d %= 11) < 2 ? 0 : 11 - d
			if (parseInt (cpf.charAt (i-1)) != d)
	    	return 2;	    }
	}

function ValidaCNPJ (cgc) {
    cgc = sonumero (cgc);
    if (cgc.length != 14)
	return 1;
    for (i = 13; i <= 14; i++) {
	d = 0
	for (j = i; j >= 2; j--)
	    d += parseInt (cgc.charAt (i-j)) * ((j-2) % 8 + 2)
		d = (d %= 11) < 2 ? 0 : 11 - d
	if (parseInt (cgc.charAt (i-1)) != d)
	    return 2;    }
	}

function sonumero (s) {
    saida = new String()
    for (i = 0; i < s.length; i++) {
		car=s.charAt(i)
		if (isnumeric (car))
		    saida += car;		    }
	    return saida;
	}

function isnumeric (c) {
    return (c >= "0") && (c <= "9")
}

function emailCheck (emailStr) {
	var emailPat=/^(.+)@(.+)$/
	var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
	var validChars="\[^\\s" + specialChars + "\]"
	var quotedUser="(\"[^\"]*\")"
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
	var atom=validChars + '+'
	var word="(" + atom + "|" + quotedUser + ")"
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")
	var matchArray=emailStr.match(emailPat)

	if (matchArray==null) {
		return 1; }
	var user=matchArray[1]
	var domain=matchArray[2]
	
	if (user.match(userPat)==null) {
	    return 2; }
	var IPArray=domain.match(ipDomainPat)
	if (IPArray!=null) {
		  for (var i=1;i<=4;i++) {
		    if (IPArray[i]>255) {
			return 3;  }   }}
	var domainArray=domain.match(domainPat)
	if (domainArray==null) {
	    return 4;}
	var atomPat=new RegExp(atom,"g")
	var domArr=domain.match(atomPat)
	var len=domArr.length
	if (domArr[domArr.length-1].length<2 || 
	    domArr[domArr.length-1].length>3) {
	   return 5;}
	if (len<2) {
	   return 6;}	}

function CPF(obj){   
  document.form.cpf_resp.value = JuntaCPFCNPJ(document.form.cpf_resp);
  document.form.cpf_resp.value = MascaraCPFCNPJ(obj);
}

function CNPJ(obj){   
  document.form.cnpj.value = JuntaCPFCNPJ(document.form.cnpj);
  document.form.cnpj.value = MascaraCPFCNPJ(obj);
}
	
/**************************************************************************************************
* function MascaraCPFCNPJ
* Retorna CPF ou CNPJ com a sua mascara respectiva.
* Input: campo a ser colacado a mascara.
***************************************************************************************************/
function MascaraCPFCNPJ(objeto){
var fc_i;
var fc_char1;
var flag;
var fc_a = objeto.value.length - 1;

fc_char1 = '';

 if(objeto.value != ''){
 if(CaracteresValidos('0123456789', objeto, 'Digite apenas números', 2)){
  // CPF.
  if(fc_a == 10){
    for(fc_i=0; fc_i<=fc_a; fc_i++) {
      fc_char1 = fc_char1 + objeto.value.substring(fc_i, fc_i + 1)
        switch(fc_i){
		  case 2:
			fc_char1 = fc_char1 + '.';
			break;
		  case 5:
			fc_char1 = fc_char1 + '.'; 
			break;
		  case 8:
			fc_char1 = fc_char1 + '-'; 
			break;
		}
    }
	return fc_char1;
  }

  // CNPJ.
  if(fc_a == 13){
    for(fc_i=0; fc_i<=fc_a; fc_i++) {
      fc_char1 = fc_char1 + objeto.value.substring(fc_i, fc_i + 1)
        switch(fc_i){
		  case 1:
			fc_char1 = fc_char1 + '.';
			break;
		  case 4:
			fc_char1 = fc_char1 + '.'; 
			break;
		  case 7:
			fc_char1 = fc_char1 + '/'; 
			break;
		  case 11:
			fc_char1 = fc_char1 + '-'; 
			break;
		}
    }
    return fc_char1;
  }	

  return objeto.value;
 }
 }

  return objeto.value;

}


/**************************************************************************************************
* function JuntaCPFCNPJ
* Retorna CPF ou CNPJ com a sua mascara retirada.
* Input: campo a ser retirado a mascara.
***************************************************************************************************/
function JuntaCPFCNPJ(objeto){
var fc_i;
var fc_char1 = '';
var flag;
var fc_a = objeto.value.length - 1;
var fc_char2 = ''

    for(fc_i=0; fc_i<=fc_a; fc_i++) {
	  fc_char2 = objeto.value.substring(fc_i, fc_i + 1)
        switch(fc_char2){
		  case '.':
			break;
		  case '/':
			break;
		  case '-':
			break;
		  default:
	        fc_char1 = fc_char1 + objeto.value.substring(fc_i, fc_i + 1)			
			break;
		}
    }
	
  return fc_char1;  
}
  
/**************************************************************************************************
* function CaracteresValidos
* Retorna TRUE se o string str for composto somente por caracteres contidos no string CharsValidos.
* Input: caracteres validados, campo a ser verificado e mensagem a ser mostrada.
***************************************************************************************************/
function CaracteresValidos(CharsValidos,objeto,msg,teste){
var fc_i;
var fc_char1;
var flag;
var fc_a=objeto.value.length - 1;
for (fc_i=0; fc_i<=fc_a; fc_i++) {
  fc_char1 = objeto.value.substring(fc_i, fc_i+1)
	flag=CharsValidos.indexOf(fc_char1)
		if (flag==-1){
 		  if(teste == 1){
			objeto.value='';
			alert(msg)
			objeto.focus();
		  }
			return(false);
	}
}
return(true);
}

function sodatas(fld, e) {
	var sep = 0;
	var key = '';
	var i = j = 0;
	var len = len2 = 0;
	var strCheck = '0123456789/';
	var aux = aux2 = '';
	var whichCode = (window.Event) ? e.which : e.keyCode;
	if (whichCode == 13) return true;  // Enter
	key = String.fromCharCode(whichCode);  // Get key value from key code
	if (strCheck.indexOf(key) == -1) return false;  // Not a valid key
	if ((key==',') && fld.value.indexOf(key) != -1) return false;
	return true;
}
	
function monta_data(data) {
	numeros="";
	for (i=0;i<data.value.length;i++) {
	    if (data.value.charAt(i)!="/") numeros+=data.value.charAt(i);}
	nova_data="";
	for (i=0;i<numeros.length;i++) {
		if ((i==2) || (i==4)){	nova_data+="/"+numeros.charAt(i);}
		else{	nova_data+=numeros.charAt(i);}
		}
	data.value=nova_data;	
}

function Valid_Date_Nova(obj){
 var monthDays = '101010110101';
 var validDate = new String('');
 var aDay, aMonth, aYear;
 var aN, aMonthFlg;
 validDate = obj.value;
 
  if(validDate.length == 0){
    return false;
  }
    
  if( validDate.length != 10 ) {
    alert('Data deve estar no formato dd/mm/aaaa.');
    obj.value = '';
    obj.focus();
    return false;
  }
    
  aDay = validDate.substring(0, 2);
  aMonth = validDate.substring(3, 5);
  aYear = validDate.substring(6, 10);
  if(isNaN(parseInt(aDay)) || isNaN(parseInt(aMonth)) || isNaN(parseInt(aYear))){
    alert('Dia, Mês e Ano devem ser numéricos.');
    obj.focus();
    return false;
  }
	
  aN = parseInt(aDay);
  if((aN < 0) || (aN > 31)){
	alert(' Dia do Mes deve estar entre 1 e 31.');
    obj.focus();
    return false;
  }
	
 if((aMonth < 1) || (aMonth > 12)){
   alert('Mes deve estar entre 1 e 12.');
   obj.focus();
   return false;
 }
	
 if((aMonth == 2) && (aDay > 28)){
   alert('Fevereiro possui até 28 dias.');
   obj.focus();
   return false;
 }
	
 aMonthFlg = parseInt(monthDays.substring(aMonth-1, aMonth));
  if((aMonthFlg == 0) && (aDay > 30) ) {
	alert('Mês possui somente 30 dias.');
	obj.focus();
    return false;
  }
	
 return true;
}

function ValidaPonto(objeto){
var fc_i;
var fc_char1;
var flag;
var CharsValidos = ".";
var fc_a = objeto.value.length - 1;
  for (fc_i=0; fc_i<=fc_a; fc_i++) {
    fc_char1 = objeto.value.substring(fc_i, fc_i+1)
    flag = CharsValidos.indexOf(fc_char1)
	if (flag!=-1){
	  return(false);
	}
  }
return(true);
}


// A condição do tp_origem_usu igual a 2 tira a obrigatoriedade dos campos para cadastros promocionais
// Niltinho 03-out-01
  		   
function f_critica_form () {
	// LOGIN
	if (isEmpty(document.form.login_usuario.value)) {
	  	alert("'Login' deve ser preenchido.");
		return false; }
	else if (ifspace(document.form.login_usuario.value)) {
		alert("'Login' não pode conter espaços.");
		return false; }
	else if (document.form.login_usuario.value.length < 3) {
		alert("'Login' deve ter 3 ou mais caracteres.");
		return false; }
	else if (!ValidaPonto(document.form.login_usuario)) {
		alert("'Login' não pode conter pontos.");
		return false; }

	// SENHA / CONFIRMA SENHA		
	if (document.form.gera_senha.value=="N") {
		if (isEmpty(document.form.senha_usuario.value)) {
		  	alert("'Senha' deve ser preenchida.");
			return false; }
		else if (ifspace(document.form.senha_usuario.value)) {
			alert("'Senha' não pode conter espaços.");
			return false; }
		else if (document.form.senha_usuario.value.length < 6) {
			alert("'Senha' deve conter mais de 6 caracteres.");
			return false; }
		if ((document.form.senha_usuario.value) != (document.form.confirma_senha.value)) {
			alert("'Confirma Senha' deve ser igual a 'Senha'");
			return false; }
		}

	// PESSOA JURIDICA - RAZAO SOCIAL / CNPJ
	if (document.form.tipo_usuario.value=="J") {
		if (isEmpty(document.form.razao_social.value))	{
		  	alert("'Razão Social' deve ser preenchida.");
			return false; }
		if (isEmpty(document.form.nome_fantasia.value))	{
		  	alert("'Nome Fantasia' deve ser preenchido.");
			return false; }
		if (isEmpty(document.form.cnpj.value)) 	{
		  	alert("'CNPJ' deve ser preenchido.");
			return false; }
		if (ValidaCNPJ(document.form.cnpj.value)) {
		  	alert("'CNPJ' inválido.");
			return false; }  		
		if (isEmpty(document.form.qtd_func.value)) 	{
		  	alert("'Quantidade de Funcionários' deve ser preenchida.");
			return false; }
		if (isEmpty(document.form.cod_segmento.value)) 	{
		  	alert("'Segmento/Área de Atuação' deve ser preenchido.");
			return false; }
		if (isEmpty(document.form.dsc_site.value)) 	{
		  	alert("'Site' deve ser preenchido.");
			return false; }
		input_nome_resp 	= "'Responsável'"
	} else {
		input_nome_resp 	= "'Nome Assinante'"
	}

	// NOME RESP
	if (isEmpty(document.form.nome_resp.value)) {
	  	alert(input_nome_resp+" deve ser preenchido.");
		return false; }
	else if (qtdnomes(document.form.nome_resp.value)) {
		alert(input_nome_resp+" deve conter Nome e Sobrenome.");
		return false; }

	// Cargo/Profissão
	if (document.form.cargo_resp.value=="") {
		if (document.form.tipo_usuario.value=="F") {
	  		alert("'Profissão' deve ser preenchida.");
		} else {
	  		alert("'Cargo' deve ser preenchido.");
		}
		return false; 
	}

	// CPF RESP
//	if (document.form.tipo_usuario.value=="F") {
		if (ValidaCPF(document.form.cpf_resp.value)) {
	  		alert("'CPF' inválido.");
			return false; 
		}
//	}

	// E-MAIL
	if (isEmpty(document.form.email.value)) {
	  	alert("'E-mail' deve ser preenchido.");
		return false; }
	else if (emailCheck(document.form.email.value)) {
	  	alert("'E-mail' inválido.");
		return false; }
	if ((document.form.email.value) != (document.form.confirma_email.value)) {
		alert("'Confirma E-mail' deve ser igual a 'E-mail'");
		return false; }

	// TELEFONE
	if (isEmpty(document.form.ddd.value)) {
  	alert("'DDD' deve ser preenchido.");
		return false; }
 	if (document.form.ddd.value.length < 2) {
  	alert("'DDD' deve conter ao menos 2 (dois) dígitos.");
		return false; }
	if (isEmpty(document.form.telefone.value)) {
		alert("'Telefone' deve ser preenchido.");
		return false; 	}
	if (document.form.telefone.value.length < 6) {
		alert("'Telefone' deve conter ao menos 6 (seis) dígitos.");
		return false; }
	tel_inv="9,8,7";
 	if (tel_inv.indexOf(document.form.telefone.value.charAt(0))!=-1) {
  	alert("'Telefone' não pode começar com "+tel_inv+".");
		return false; } 
	if (isEmpty(document.form.celular.value)) {
		alert("'Celular' deve ser preenchido.");
		return false; 	}
	if (isEmpty(document.form.fax.value)) {
		alert("'FAX' deve ser preenchido.");
		return false; 	}

  	// DATA  NASC
	if (isEmpty(document.form.dt_nasc_resp.value)) {
		alert("'Data de Nascimento' deve ser preenchida.");
		return false;}
	if (isEmpty(document.form.dt_nasc_resp.value)==false) {
      if(!Valid_Date_Nova(document.form.dt_nasc_resp)){
	    return false;
	  } 
   }

//	if (document.form.tp_origem_usu.value != "03") {

	if (isEmpty(document.form.endereco.value)) {
		alert("'Endereço' deve ser preenchido.");
		return false; }
	if (isEmpty(document.form.num_endereco.value)) {
  	alert("'Número' deve ser preenchido.");
		return false; }
	if (isEmpty(document.form.bairro.value)) {
  	alert("'Bairro' deve ser preenchido.");
		return false; }
	if (isEmpty(document.form.dsc_municipio.value)) {
  	alert("'Município' deve ser preenchido.");
		return false; }
	if (isEmpty(document.form.cod_uf.value)) {
  	alert("'Estado' deve ser informado.");
		return false; }
	if (isEmpty(document.form.cep.value)) {
  	alert("'CEP' deve ser preenchido.");
		return false; }

	if (document.form.tp_indica) {
		if (document.form.tp_indica.length) {
			achou="";
			for (tp=0;tp<document.form.tp_indica.length;tp++) {
				if (document.form.tp_indica[tp].checked==true) achou=document.form.tp_indica[tp].value;
			}
			if (achou=="") {
		  	alert("Favor informar 'Como nos conheceu?'.");
				return false;
			}
			if (achou==99 && document.form.dsc_indica_compl.value=="") {
		  	alert("Favor especificar 'Como nos conheceu?'.");
				return false;
			}
		}
	}

}
//	}
