// JavaScript Document

//--Função que chega o campo Login
function validalogin( frm )
{
var login = frm.username.value ;
var msg = "" ;
if ( login.search( /\s/g ) != -1 )
{
msg+= "Não é permitido espaços em branco\n" ;
login = login.replace( /\s/g , "" ) ;
}	
if ( login.search( /[^a-z0-9]/i ) != -1 )
{
msg += "Não é permitido caracteres especiais" ;
login = login.replace( /[^a-z0-9]/gi , "" ) ;
}
if ( msg )
{
alert( msg ) ;
frm.username.value = login ;
return false ;
}
return true ;	
}

//--Função que chama o teste do login
$(document).ready(function()
{
			
	$("#username").blur(function()
	{
		//remove all the class add the messagebox classes and start fading
		$("#msgbox").removeClass().addClass('fonte_padrao_negrito').text('Verificando...').fadeIn("slow");
		//check the username exists or not from ajax
		$.post("ajax.php?do=check_login_exists",{ login:$(this).val() } ,function(data)
        {
		  if(data=='no') //if username not avaiable
		  {
		  	$("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox
			{ 
			  //add message and change the class of the box and start fading
			  $(this).html('Esse login já está em uso, tente outro!').addClass('fonte_vermelha').fadeTo(900,1);
			});		
          }
		  else
		  {
		  	$("#msgbox").fadeTo(200,0.1,function()  //start fading the messagebox
			{ 
			  //add message and change the class of the box and start fading
			  $(this).html('Login disponível para registro.').addClass('fonte_verde').fadeTo(900,1);	
			});
		  }
				
        });
 
	});
	
});

//--Função que testa a seguranca da senha.
function TestaSenha(valor)
{
    var d = document.getElementById('seguranca');
    ERaz = /[a-z]/;
    ERAZ = /[A-Z]/;
    ER09 = /[0-9]/;
    ERxx = /[@!#$%&*+=?|-]/;

    if(valor.length == ''){
        d.innerHTML = '';
    } else {
        if(valor.length < 5){
            d.innerHTML = '<font class=\'fonte_vermelha\'>Senha pequena.</font>';
        } else {
            if(valor.length > 7 && valor.search(ERaz) != -1 && valor.search(ERAZ) != -1 && valor.search(ER09) != -1 || valor.length > 7 && valor.search(ERaz) != -1 && valor.search(ERAZ) != -1 && valor.search(ERxx) || valor.length > 7 && valor.search(ERaz) != -1 && valor.search(ERxx) != -1 && valor.search(ER09) || valor.length > 7  && valor.search(ERxx) != -1 && valor.search(ERAZ) != -1 && valor.search(ER09)){
                d.innerHTML = '<font class=\'fonte_verde\'>Segurança Alta</font>';
            } else {
                if(valor.search(ERaz) != -1 && valor.search(ERAZ) != -1 || valor.search(ERaz) != -1 && valor.search(ER09) != -1 || valor.search(ERaz) != -1 && valor.search(ERxx) != -1 ||valor.search(ERAZ) != -1 && valor.search(ER09) != -1 ||valor.search(ERAZ) != -1 && valor.search(ERxx) != -1 ||valor.search(ER09) != -1 && valor.search(ERxx) != -1){
                    d.innerHTML = '<font class=\'fonte_laranja\'>Segurança Média</font>';
                } else {
                    d.innerHTML = '<font class=\'fonte_vermelha\'>Segurança Baixa</font>';
                }
            }
        }
    }
}
//-->
//-->
//-->

//--Função de mascara nos campos.
function mascara(src, mask) 
{
  var i = src.value.length;
  var saida = mask.substring(0,1);
  var texto = mask.substring(i)
if (texto.substring(0,1) != saida)
  {
	src.value += texto.substring(0,1);
  }
}

//-->
//-->
//-->

window.onload = function() {
	new dgCidadesEstados( 
		document.getElementById('estado'), 
		document.getElementById('cidade'), 
		true
	);
}

habilitaJuridica = function(obj)
{
    document.getElementById("razaosocial").disabled = !obj.checked;
    document.getElementById("cnpj").disabled = !obj.checked;
    document.getElementById("cpf").disabled = obj.checked;
    document.getElementById("rg").disabled = obj.checked;
    document.getElementById("fisica").checked = !obj.checked;
}

habilitaFisica = function(obj)
{
    document.getElementById("razaosocial").disabled = obj.checked;
    document.getElementById("cnpj").disabled = obj.checked;
    document.getElementById("cpf").disabled = !obj.checked;
    document.getElementById("rg").disabled = !obj.checked;
    document.getElementById("juridica").checked = !obj.checked;
}

//-->
//-->
//-->

function ValidaCPF(){
var msgCPF = document.getElementById('msgcpf');
var cpf = document.form.cpf.value;
var filtro = /^\d{3}.\d{3}.\d{3}-\d{2}$/i;
if(!filtro.test(cpf)){
	msgcpf.innerHTML = '<font class=\'fonte_vermelha\'>CPF inválido</font>';
return false;
}
   
cpf = remove(cpf, ".");
cpf = remove(cpf, "-");

if(cpf.length != 11 || cpf == "00000000000" || cpf == "11111111111" ||
cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" ||
cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" ||
cpf == "88888888888" || cpf == "99999999999"){
	msgcpf.innerHTML = '<font class=\'fonte_vermelha\'>CPF inválido</font>';
return false;
}
soma = 0;
for(i = 0; i < 9; i++)
soma += parseInt(cpf.charAt(i)) * (10 - i);
   resto = 11 - (soma % 11);
   if(resto == 10 || resto == 11)
	 resto = 0;
   if(resto != parseInt(cpf.charAt(9))){
	msgcpf.innerHTML = '<font class=\'fonte_vermelha\'>CPF inválido</font>';
return false;
   }
   soma = 0;
   for(i = 0; i < 10; i ++)
	 soma += parseInt(cpf.charAt(i)) * (11 - i);
   resto = 11 - (soma % 11);
   if(resto == 10 || resto == 11)
	 resto = 0;
   if(resto != parseInt(cpf.charAt(10))){
	msgcpf.innerHTML = '<font class=\'fonte_vermelha\'>CPF inválido</font>';
	return false;
   }
   msgcpf.innerHTML = '<font class=\'fonte_verde\'>CPF válido</font>';
   return true;
 }
 
 function remove(str, sub) {
   i = str.indexOf(sub);
   r = "";
   if (i == -1) return str;
   r += str.substring(0,i) + remove(str.substring(i + sub.length), sub);
   return r;
}
 
//-->
//-->
//-->

function ValidaCNPJ() {
var msgcnpj = document.getElementById('msgcnpj');

CNPJ = document.form.cnpj.value;

erro = new String;
if (CNPJ.length < 18) erro += "É necessario preencher corretamente o número do CNPJ! \n\n"; 
if ((CNPJ.charAt(2) != ".") || (CNPJ.charAt(6) != ".") || (CNPJ.charAt(10) != "/") || (CNPJ.charAt(15) != "-")){
if (erro.length == 0) erro += "É necessário preencher corretamente o número do CNPJ! \n\n";
}
//substituir os caracteres que não são números
if(document.layers && parseInt(navigator.appVersion) == 4){
x = CNPJ.substring(0,2);
x += CNPJ. substring (3,6);
x += CNPJ. substring (7,10);
x += CNPJ. substring (11,15);
x += CNPJ. substring (16,18);
CNPJ = x; 
} else {
CNPJ = CNPJ. replace (".","");
CNPJ = CNPJ. replace (".","");
CNPJ = CNPJ. replace ("-","");
CNPJ = CNPJ. replace ("/","");
}
var nonNumbers = /\D/;
if (nonNumbers.test(CNPJ)) erro += "A verificação de CNPJ suporta apenas números! \n\n"; 
var a = [];
var b = new Number;
var c = [6,5,4,3,2,9,8,7,6,5,4,3,2];
for (i=0; i<12; i++){
a[i] = CNPJ.charAt(i);
b += a[i] * c[i+1];
}
if ((x = b % 11) < 2) { a[12] = 0 } else { a[12] = 11-x }
b = 0;
for (y=0; y<13; y++) {
b += (a[y] * c[y]); 
}
if ((x = b % 11) < 2) { a[13] = 0; } else { a[13] = 11-x; }
if ((CNPJ.charAt(12) != a[12]) || (CNPJ.charAt(13) != a[13])){
erro +="Dígito verificador com problema!";
}
if (erro.length > 0){
	msgcnpj.innerHTML = '<font class=\'fonte_vermelha\'>CNPJ inválido</font>';
return false;
} else {
	msgcnpj.innerHTML = '<font class=\'fonte_verde\'>CNPJ válido</font>';
}
return true;
}

//-->
//-->
//-->


function valida(Fobj){
	return (
		avisoqnt(Fobj.username, 4, "O Login precisa ter no minimo 4 caracteres!")&&
		avisoqnt(Fobj.senha, 6, "A Senha precisa ter no minimo 6 caracteres!")&&
		checkmail(Fobj.email1, "Você deve informar um e-mail válido!")&&
		aviso(Fobj.nomefantasia, "Você deve informar o Nome Fantasia!")&&
		aviso(Fobj.frequencia, "Você deve informar a Frequencia!")&&
		aviso(Fobj.potencia, "Você deve informar a Potencia!")&&
		aviso(Fobj.endereco, "Você deve informar o Endereço!")&&
		aviso(Fobj.numero, "Você deve informar o Número do endereço!")&&
		avisoselect(Fobj.estado, "Você deve selecionar o Estado")&&
		avisoselect(Fobj.cidade, "Você deve selecionar a Cidade")&&
		avisoselect(Fobj.tipo, "Você deve informar o Tipo de Rádio")&&
		aviso(Fobj.responsavel, "Você deve informar o Responsável")&&
		cep(Fobj.cep, "Você deve informar o CEP.")
		)
}

//-->
//-->
//-->

function avisoqnt(formu,count,mensagem){
	campo = formu.value;
	tamanho = campo.length;

	if ((formu.value == "")||(tamanho < count)){
		alert(mensagem);
		formu.focus();
		return false;	
	}
	return true;
 }

//-->
//-->
//-->

 function aviso(formu,mensagem,focu){
 
  if (formu.value == ""){
    alert(mensagem);
    if (!focu){
		formu.focus();
	}
    return false;
  }
  return true;
 }

//-->
//-->
//-->

function avisoselect(formu,mensagem){
  if(formu.selectedIndex == 0){
  alert(mensagem);
  formu.focus();
  return false;
  }
  return true;
}

//-->
//-->
//-->

function comparacampos(formu1,formu2,mensagem){
 if(formu2.value != formu1.value){
alert(mensagem);
formu2.focus();
return false;
 }
return true;
}

//-->
//-->
//-->

function checkmail(obj,mensagem){
 if (!isEmail(obj.value)){
	alert(mensagem);
	obj.focus();
	return false;
 }
return true;
}

//-->
//-->
//-->

function isEmail(string) {
    if (string.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) != -1)
        return true;
    else
        return false;
}

//-->
//-->
//-->

function CheckValida(obj,Vazio){
var permitido = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.@-_";
var tamanho = obj.length;

if (Vazio == 'S'){
   if (obj != "" && (obj.indexOf('@')==-1 || obj.indexOf('.')==-1)){
	return false;
   }
} else {
   if (obj.indexOf('@')==-1 || obj.indexOf('.')==-1){
	return false;
   }
}

arroba = 0;
for (i=0;i<=tamanho+1;i++){
  if (permitido.indexOf(obj.charAt(i))==-1){
	return false;
  }
if(obj.charAt(i) == "@"){
	arroba = arroba + 1;
	if(arroba != 1){
	return false;
	}
}
}
return true;
}

//-->
//-->
//-->

function cep(obj,mensagem){
	if (!isCEP(obj.value)){
    	alert(mensagem);
        obj.focus();
        return false;
    }
    return true;
}
  
function isCEP (str) {
	digit = /^\d{5}-\d{3}$/;
	return digit.test(str);
}


//-->
//-->
//-->

function verificachecked(formu,mensagem){
conta = 0;
tamanho = formu.length;

if (tamanho > 1){
	  for (i=0;i<tamanho;i++){
		 if(formu[i].checked){
	conta = conta+1;
		 }
	  }     
	}else{
		 if(formu.checked){
	conta = conta+1;
	 }
}

if (conta == 0){
	 alert(mensagem);

  if (tamanho > 1){
	  formu[0].focus();
	  }
	  else{
	  formu.focus();
	  }
 return false;
}
return true;
}

//-->
//-->
//-->

function telefone(Fobj){
	if ((Fobj.telfixo.value == "") && (Fobj.telcel.value == "")){
		alert("Ao menos um telefone deve ser informado");
		Fobj.dddtelcom.focus();
		return false;	
	}
	if ((Fobj.dddtelfixo.value == "") && (Fobj.telfixo.value != "")){
		alert("Você deve informar o DDD do Telefone Fixo")
		Fobj.dddtelcom.focus();
		return false;	
	}
	if ((Fobj.dddtelcel.value == "") && (Fobj.telcel.value != "")){
		alert("Você deve informar o DDD do Celular")
		Fobj.dddtelcel.focus();
		return false;	
	}
	return true;
}
function ShowCep()
{
open('http://www.correios.com.br/servicos/cep/cep_default.cfm','ShowCep','location=no,resize=no, width=730,height=400,left=18,top=18,maximized=0,scrollbars=1');
}
//-->
//-->
//-->