/*
Funcoes:

FormataNumero
	  Recebe o numero com formato de Moeda e retira R$
	  
ConsisteNumero(valor)
      Recebe um valor e verifica se é numero ou nao

ConsisteEmail(valor)
      Recebe uma string e valida se é email ou não

ConsisteTelefone(valor)
      Recebe uma string no formato de telefone (XX [X]XXX-XXXX) e valida

ConsisteTelefone2(ddd,numero)
	Recebe um ddd de 3 digitos e um telefone de 4 digitos e valida

ConsisteData(dia,mes,ano)
      Recebe o dia, mes e ano e valida a data

ConsisteCPFCNPJ(valor)
      Recebe uma string e valida se é CPF ou CNPJ

ConsisteCEP(valor)
      Recebe um valor com 8 digitos e valida

FormataData(dia,mes,ano)
      Converte uma data para o formato do banco de dados

FormataDecimal(valor)
      Converte uma moeda para o formato do banco de dados

Arredonda(valor)
      Arredonda um valor no formato #####.##### para baixo e 2 casas

ComparaData(dia1,mes1,ano1,dia2,mes2,ano2)
      Verifica se a data 2 é maior (retorna 1), igual (retorna 0) ou menor (retorna -1) que a data 1

Formato Moeda: 0.000[,00]
Formato Data: dd/mm/yyyy
Formato Email: xxx@xxx.xxx[.xxx]
Formato Telefone: 00 [0]000-0000
Formato CPF: 000.000.000-00
Formato CNPJ: 00.000.000/0000-00
*/

function PISPASEP(numero) 

{ 		/***************************************************
   		 *                                                 *
   		 *         Função para validar PIS/PASEP		   *
   		 *		 			 		                       *
   		 ***************************************************/
         
         var ftap;
         var total;
         var i, resto;  

         if ((eval(numero)==0) || (numero.length !=11))
		 {
   		     return false;
         }
         
         ftap='3298765432';
         total=0;
     
         
         for (i=1;i<11;i++)
         {
		     total=total+eval(numero.substring(i-1,i))*eval(ftap.substring(i-1,i));
         }
		 
		 
         resto=(total % 11);
		
         
         if (resto!=0)
		 {
             resto = 11 - resto ;         
         }
         
         if (resto != numero.substring(10,11))
		 {
           return false;
         } 
		
		 
		  return true;
		   
}    

function VerificaETrocaCaracter(valor,tipo,caracter,trocarpor){
	var valorTemp = new String(valor);
	if ((valorTemp.indexOf(caracter) != -1)){
		valorTemp = valorTemp.replace(caracter,trocarpor);
		return VerificaETrocaCaracter(valorTemp,tipo,caracter,trocarpor);
	}else{
		if ((valorTemp == '') && (tipo == 'numero')){
			valorTemp = '0'
		}
	}
	return valorTemp;
}

function FormataNumero(valor){
	var s = new String(valor);
	if ((s.indexOf('.') != -1) && (s.indexOf(',') != -1))
	{
		s = s.replace('.','');
		s = s.replace('.','');
		s = s.replace('.','');
		s = s.replace('.','');
		s = s.replace('.','');
		s = s.replace('.','');
		s = s.replace(',','.');
	}else{	
		s = s.replace(',','.');
	}
	s = s.replace('R',''); 	
	s = s.replace('r',''); 	
	s = s.replace('$',''); 	
	s = s.replace(' ','');
	s = Arredonda(s)
	return s;	
}

function ConsisteNumero(valor) {
	var s = new String(valor);
    if (s == '') return false;
    s = s.replace('R','');
	s = s.replace('r','');
	s = s.replace('$','');
	s = s.replace(',','');
	s = s.replace('.','');
	s = s.replace('.','');
	s = s.replace('.','');
	s = s.replace('.','');
	s = s.replace('.','');
	s = s.replace('.','');
	s = s.replace(' ','');

	return !isNaN(s);
}

function ConsisteEmail(valor) {
    var reg = /[A-Za-z0-9_-]{1,}[@]\w{1,}[.]\w{1,}/
    return reg.test(valor);
}

function ConsisteTelefone(valor) {
    var reg = /\d{2}\s\d{6,8}/;
    return reg.test(valor);
}

function ConsisteData(dia,mes,ano) {
    var dat = new Date();
    var vAnoLimite = dat.getFullYear() + 100;

    //Todos os valores devem ser numeros
    if (isNaN(dia) || isNaN(mes) || isNaN(ano)){
        return false;}
    //Dia deve ser maior que 1 e menor que 31
    if ((dia < 1) || (dia > 31)) {
        return false;}
    //Mes deve ser maior que 1 e menor que 12
    if ((mes < 1) || (mes > 12)) {
        return false;}
    //Ano deve ser maior que 1900 e menor que ano atual + 100
    if ((ano < 1900) || (ano > vAnoLimite)) {
        return false;}
    //Se mes = Fevereiro dia deve ser menor ou igual que 29
    if ((mes == 2) && (dia > 29)) {
        return false;}
    //Se mes = Fevereiro e ano e bissexto dia deve ser menor que 29
    if ((mes == 2) && (dia == 29) && ((ano/4) != parseInt(ano/4))) {
        return false;}
    //Se mes tiver 30 dias o dia deve ser menor que 31
    if (((mes == 4) || (mes == 6) || (mes == 9) || (mes == 11)) && (dia == 31)) {
        return false;}
    return true;
}

function AlertaCNPJ()
{
    if( ConsisteCPFCNPJ( document.getElementById( "txtCNPJ" ).value ) == false )
    {
       alert("CNPJ Invalido, digite-o novamente.");
       document.getElementById( "txtCNPJ" ).focus();
    }
}

function ConsisteCPFCNPJ(number)
{
   var digit, cgc, i, b, s, tipo;
   replicated= '';
   digit = '';
   tipo = '';

   if (ConsisteNumero(number) == false)
     return false; 

   if (number == '11111111111111') return false;
   if (number == '22222222222222') return false;
   if (number == '33333333333333') return false;
   if (number == '44444444444444') return false;
   if (number == '55555555555555') return false;
   if (number == '66666666666666') return false;
   if (number == '77777777777777') return false;
   if (number == '88888888888888') return false;
   if (number == '99999999999999') return false;
   if (number == '00000000000000') return false;
   
   if (number.length != 14 && number.length != 11)
   {
      return false;
   }
   else if (number.substr(0, number.length-2) == replicated)
   {
      return false;       
   }
   else
   {
      if (number.length == 14)
      {
         tipo = "CNPJ"; 
      }
      else
      {
         tipo = "CPF";
      }
      cgc = number.substr(0, number.length-2);
      while (digit.length <2)
      {
         s = 0;
         b = 2;
         for (i=cgc.length-1; i>=0; i--)
         {
             s = s + b * cgc.substr(i, 1); 
             b = b + 1;
             if (number.length == 14 && b > 9)
                b = 2;
         }
         s = 11 - (s % 11);
         if (s > 9) s = 0;
           digit = digit.concat(s);
         cgc = cgc.concat(s);
      }    
      //Recentemente modificado aqui, era um if comum, substitui por um ternário
      return (digit==number.substr(number.length-2, 2))?true:false;
   }
}

function ConsisteCEP(valor) {
    if (ConsisteNumero(valor) == false) {
        return false;
    } else if (valor.length != 8) {
        return false;
    } else {
        return true;
    }
}

function FormataMoeda(valor) {
    var r = new String(valor);
    r = r.replace('.','');
    r = r.replace(',','.');
    r = Arredonda(r);
    return r;
}

function FormataData(dia,mes,ano) {
    var vDia = new String(dia);
    var vMes = new String(mes);
    var vAno = new String(ano);
    var result;

    if (vDia.length < 2) {vDia = '0' + vDia}
    if (vMes.length < 2) {vMes = '0' + vMes}
    result = vAno + '/' + vMes + '/' + vDia;
    return result;
}

function Arredonda(valor) {
	var s = parseFloat(valor) * 100
	s = Math.round(s)
	s = s / 100
    return s;
	

/*	var s = new String(valor);
    var a,b,c,result;
    if (s.indexOf('.') >= 0)
	{
        a = parseInt(s.substring(0,s.indexOf('.')));
	}
    else
        return s;
    b = s.substr(s.indexOf('.') + 1,2);
    c = parseInt(s.substr(s.indexOf('.') + 3));
    if (!isNaN(b) && !isNaN(c)) {
        if ((parseInt(b) + 1) >= 100) {
            a = a + 1;
            b = 0;
            c = 0;
        } else {
            b = b + 1;
            c = 0;
        }
    }
    result = a;
    if (b != 0) result = result + '.' + b;   */

}

/*
Retorna:
	1 se a data 1 for menor que a data 2
	0 se a data 1 for igual a data 2
	-1 se a data 1 for maior que a data 2
*/

function ComparaData(dia1,mes1,ano1,dia2,mes2,ano2) {
    var vdia1 = parseFloat(dia1);
    var vmes1 = parseFloat(mes1);
    var vano1 = parseInt(ano1);
    var vdia2 = parseFloat(dia2);
    var vmes2 = parseFloat(mes2);
    var vano2 = parseInt(ano2);
    var result1,result2,result3,result;

    if (vano1 < vano2) {
        return 1;
    } else {
        if (vano1 == vano2) {
            result1 = 0;
        } else {
            if (vano1 > vano2) {
                return -1;
            }
        }
    }
    if (vmes1 < vmes2) {
        return 1;
    } else {
        if (vmes1 == vmes2) {
            result2 = 0;
        } else {
            if (vmes1 > vmes2) {
                return -1;
            }
        }
    }
    if (vdia1 < vdia2) {
        return 1;
    } else {
        if (vdia1 == vdia2) {
            result3 = 0;
        } else {
            if (vdia1 > vdia2) {
                return -1;
            }
        }
    }
    if ((result1 == 0) && (result2 == 0) && (result3 == 0)) {
        return 0;
    }
}
function Campo(nome,descricao,obrigatorio,tipo,tamanho,proximocampo) {
	this.nome = nome;
	this.descricao = descricao;
	this.obrigatorio = obrigatorio;
	this.tamanho = tamanho;
	this.dia = '';
	this.mes = '';
	this.ano = '';
	this.tipo = tipo;
	//document.onkeypress = OnKeyPress;
	this.proximocampo = proximocampo;
	this.Valida = ValidaCampo;
}

function CampoData(descricao,dia,mes,ano) {
	this.descricao = descricao;
	this.dia = dia;
	this.mes = mes;
	this.ano = ano;
	this.Valida = ValidaCampoData;
}

/*function OnKeyPress() {
	var validou = false;
	var variavel = event.srcElement.name;
	if ((event.keyCode == 13) && (new String(variavel) != "undefined")) {
		eval('validou = ' + variavel + '.Valida()');
		var car; var funcao;
		car = "'()'"
		funcao = eval(variavel + '.proximocampo')
		if (validou == true) {
			eval('if (new String(' + variavel + '.proximocampo) == "undefined") {ValidaPagina()} else if (' + variavel + '.proximocampo.indexOf(' + car + ') != -1){' + funcao + '} else {document.form1.all(' + variavel + '.proximocampo).focus()}');
			return false;
		}
	}
}*/

function ValidaCampoData() {
	if ((this.dia.obrigatorio == true) || ((document.form1.all(this.dia.nome).value != '') || (document.form1.all(this.mes.nome).value != '') || (document.form1.all(this.ano.nome).value != ''))) {
		if (ConsisteData(document.form1.all(this.dia.nome).value,document.form1.all(this.mes.nome).value,document.form1.all(this.ano.nome).value) == false) {
			alert('Campo ' + this.descricao + ' deve conter uma data válida.');
			document.form1.all(this.dia.nome).focus();
			return false;
		}
	}
	return true;
}

function ValidaCampo() {
	if (this.tamanho != 0) {
		if (this.tipo == 'moeda') {
			var a; var qtdcasasdecimais = 0;
			a = document.form1.all(this.nome).value
			if (a.indexOf(',') != -1){
				qtdcasasdecimais = (parseInt(a.substring(a.indexOf(','))) - 1)
			}
			a = VerificaETrocaCaracter(a,'numero','R','')
			a = VerificaETrocaCaracter(a,'numero','r','')
			a = VerificaETrocaCaracter(a,'numero','$','')
			a = VerificaETrocaCaracter(a,'numero','.','')
			a = VerificaETrocaCaracter(a,'numero',',','')				
			a = VerificaETrocaCaracter(a,'numero',' ','')				
			if ((parseInt(a.length) - qtdcasasdecimais) > this.tamanho) {
				alert('Campo ' + this.descricao + ' deve conter no maximo ' + this.tamanho + ' numeros após a virgula.');
				document.form1.all(this.nome).focus();
				return false
			}
		}else{
			if (document.form1.all(this.nome).value.length > this.tamanho) {
				alert('Campo ' + this.descricao + ' deve conter no maximo ' + this.tamanho + ' caracteres (numeros, letras e espaços)');
				document.form1.all(this.nome).focus();
				return false
			}
		}
	}
	if ((this.obrigatorio == true) && ((document.form1.all(this.nome).value == '') || (document.form1.all(this.nome).value == '0'))) {
		alert('Informe o campo ' + this.descricao);
		document.form1.all(this.nome).focus();
		return false;
	}
	if (document.form1.all(this.nome).value != ''){
		if (this.tipo == 'moeda') {
			var a;
			a = document.form1.all(this.nome).value
			a = VerificaETrocaCaracter(a,'numero','R','')
			a = VerificaETrocaCaracter(a,'numero','r','')
			a = VerificaETrocaCaracter(a,'numero','$','')
			a = VerificaETrocaCaracter(a,'numero','.','')
			a = VerificaETrocaCaracter(a,'numero',',','')				
			a = VerificaETrocaCaracter(a,'numero',' ','')				
			if (ConsisteNumero(a) == false) {
				alert('Campo ' + this.descricao + ' deve ser numérico.');
				document.form1.all(this.nome).focus();
				return false;
			}
		}
		if (this.tipo == 'numero') {
			if (ConsisteNumero(document.form1.all(this.nome).value) == false) {
				alert('Campo ' + this.descricao + ' deve ser numérico.');
				document.form1.all(this.nome).focus();
				return false;
			}
		}
		if (this.tipo == 'email') {
			if (ConsisteEmail(document.form1.all(this.nome).value) == false) {
				alert('Campo ' + this.descricao + ' inválido. Verifique o email Digitado.');
				document.form1.all(this.nome).focus();
				return false;
			}
		}
		if (this.tipo == 'cnpj') {
			if (ConsisteCPFCNPJ(document.form1.all(this.nome).value) == false) {
				alert("Campo " + this.descricao + " inválido. Verifique se constam somente números.");
				document.form1.all(this.nome).focus();
				return false;
			}
		}
	}		
	return true;
}

function validaCPF()
{            
	if( !checacpf( document.getElementById("txtCPF").value ) )
	{
		errors="1";
		if (errors)
		{
			alert('CPF invalido, por favor digite-o novamente.');  
			document.getElementById("txtCPF").focus();			
		}
		document.retorno = (errors == '');
	}
}




function checacpf(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"  )
        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)))
            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)))
            return false;
                
        return true;
}        
	
function IsNumTel(obj,event)
{
    var str = obj.value;
    var Tecla = event.which;
    if(Tecla == null)
      Tecla = event.keyCode;

    if ( Tecla < 48 || Tecla > 59 )
    {
        event.returnValue = false;
	    alert("Somente Numeros!");
        return false;
    }
    event.returnValue = true;
    return true;
}

function PesquisarMunicipio()
{
	if( document.getElementById('CadastroPessoaFisica_txtCidadeEstado') != null )
	{
	    window.open("/geral/municipio_pesquisar.aspx?txtMunicipio=" + document.getElementById('CadastroPessoaFisica_txtCidadeEstado').value,"y",'width=395,height=330');			
	}
	else if( document.getElementById('CadastroPessoaJuridica_txtCidadeEstado') != null )
	{
		window.open("/geral/municipio_pesquisar.aspx?txtMunicipio=" + document.getElementById('CadastroPessoaJuridica_txtCidadeEstado').value,"y",'width=395,height=330');					
	}
	else if( document.getElementById('CadastroOngCondominio_txtCidadeEstado') != null )
	{
		window.open("/geral/municipio_pesquisar.aspx?txtMunicipio=" + document.getElementById('CadastroOngCondominio_txtCidadeEstado').value,"y",'width=395,height=330');							
	}
	else
	{
		document.getElementById('txtCidadeEstado').value = municipio + " - " + estado ;
		document.getElementById('hidCodMunicipio').value = codmunicipio;	
	}	
}

	
function ProcurarMunicipio()
{
	window.open("/geral/municipio_pesquisar.aspx?txtMunicipio=" + event.srcElement.value,"y",'width=395,height=330');	
}
function BuscaMunicipio(Estado)
{
	window.open("/geral/municipio_pesquisar.aspx?txtMunicipio=" + document.getElementById("txtCidadeEstado").value,"y",'width=395,height=330');	
}

function BuscaMunicipioNull()
{
	window.open("/geral/municipio_pesquisar.aspx?txtMunicipio= ","y",'width=395,height=330');
}

function ReceberMunicipio(municipio, estado, codmunicipio)
{
	if( document.getElementById('CadastroPessoaFisica_txtCidadeEstado') != null && document.getElementById('CadastroPessoaFisica_hidCodMunicipio') != null )
	{
		document.getElementById('CadastroPessoaFisica_txtCidadeEstado').value = municipio + " - " + estado ;
		document.getElementById('CadastroPessoaFisica_hidCodMunicipio').value = codmunicipio;	
	}
	else if( document.getElementById('CadastroPessoaJuridica_txtCidadeEstado') != null && document.getElementById('CadastroPessoaJuridica_hidCodMunicipio') != null )
	{
		document.getElementById('CadastroPessoaJuridica_txtCidadeEstado').value = municipio + " - " + estado ;
		document.getElementById('CadastroPessoaJuridica_hidCodMunicipio').value = codmunicipio;	
	}
	else if( document.getElementById('CadastroOngCondominio_txtCidadeEstado') != null && document.getElementById('CadastroOngCondominio_hidCodMunicipio') != null )
	{
		document.getElementById('CadastroOngCondominio_txtCidadeEstado').value = municipio + " - " + estado ;
		document.getElementById('CadastroOngCondominio_hidCodMunicipio').value = codmunicipio;	
	}
	else
	{
		document.getElementById('txtCidadeEstado').value = municipio + " - " + estado ;
		document.getElementById('hidCodMunicipio').value = codmunicipio;	
	}
	
}

function BuscaCBO()
{
    window.open("cbo_buscar.aspx?DescricaoCBO=" + document.getElementById("txtDescCBO").value + "&CodCBO=" + document.getElementById("txtNumCBO").value,"CBO",'width=500,height=375');
}

function BuscaCNAE()
{
    window.open("cnae_buscar.aspx?CodCNAE=" + document.getElementById("txtNumCnae").value + "&DescCNAE=" + document.getElementById("txtDescCNAE").value,"CNAE",'width=500,height=345');   
}

function ReceberCNAE(CodCNAE, DescCNAE)
{
    document.getElementById('ddlEmailNoticias').focus();
	document.getElementById('txtDescCNAE').value = DescCNAE ;
	document.getElementById('txtNumCnae').value = CodCNAE ;	
	document.getElementById('hidCodCnae').value = CodCNAE ;		
}

function ReceberCBO(CodCBO, DescCBO)
{    
	document.getElementById('txtDescCBO').value = DescCBO ;
	document.getElementById('txtNumCBO').value = CodCBO ;	
	document.getElementById('hidCodCBO').value = CodCBO ;		
}
function AbrePesquisa()
{
     window.open("popup_pesquisa.aspx", "pesquisa", 'width=240,height=250');
}

function ValidaCEP(objeto, args)
{
	var obj = document.getElementById(document.getElementById(objeto.controltovalidate).complemento);
	if(args.Value.length < 5 || obj.value.length <3)
	{
		args.IsValid = false;
	}
}

function ValidaTelefone(objeto, args)
{
	var obj = document.getElementById(document.getElementById(objeto.controltovalidate).complemento);
	if(args.Value.length < 7  || obj.value.length <2)
	{
		args.IsValid = false;
	}
}		

