/*
function NOME_FUNCAO()
{
    try
    {
    }
    catch(err)
    {
        document.write('<!-- VerificaTipoPessoa() ' + err.description + '-->');
    }
}
*/



function VerificaTipoPessoa()
{
	try
	{
		var formcadastro_rdnPF		= document.getElementById('formcadastro_rdnPF');
		var formcadastro_rdnPJ		= document.getElementById('formcadastro_rdnPJ');
		
		var DadosPessoaFisica		= document.getElementById('DadosPessoaFisica');
		var DadosPessoaJuridica		= document.getElementById('DadosPessoaJuridica');
		
	    
	    if(formcadastro_rdnPF.checked)
	    {
			DadosPessoaFisica.style.display		= 'block';	
			DadosPessoaJuridica.style.display	= 'none';
	    }	
	    else
	    {
			DadosPessoaFisica.style.display		= 'none';	
			DadosPessoaJuridica.style.display	= 'block';	    

	    }
	}
	catch(err)
	{
		alert(err.description);
	}
}



function CamposPreenchidos(ParentForm)
{
	var retorno = true;
    
    try
    {
		var formcadastro_rdnPF					= document.getElementById('formcadastro_rdnPF');
		var formcadastro_rdnPJ					= document.getElementById('formcadastro_rdnPJ');
        
        var formcadastro_txtPFNome              = document.getElementById('formcadastro_txtPFNome');
        var formcadastro_txtPFCPF               = document.getElementById('formcadastro_txtPFCPF'); 
        var formcadastro_txtPFRG				= document.getElementById('formcadastro_txtPFRG');
        var formcadastro_txtPFNascDia           = document.getElementById('formcadastro_txtPFNascDia');
        var formcadastro_txtPFNascMes           = document.getElementById('formcadastro_txtPFNascMes');
        var formcadastro_txtPFNascAno           = document.getElementById('formcadastro_txtPFNascAno');
        
        var formcadastro_txtPJRazaoSocial       = document.getElementById('formcadastro_txtPJRazaoSocial');
        var formcadastro_txtPJCNPJ              = document.getElementById('formcadastro_txtPJCNPJ');
        var formcadastro_txtPJIE				= document.getElementById('formcadastro_txtPJIE');
        var formcadastro_txtPJNomeFantasia		= document.getElementById('formcadastro_txtPJNomeFantasia');
        
        var formcadastro_txtCep					= document.getElementById('formcadastro_txtCep');
        var formcadastro_txtEndereco			= document.getElementById('formcadastro_txtEndereco');
        var formcadastro_txtNumero				= document.getElementById('formcadastro_txtNumero');        
        var formcadastro_txtComplemento			= document.getElementById('formcadastro_txtComplemento');
        var formcadastro_txtBairro				= document.getElementById('formcadastro_txtBairro');
        var formcadastro_txtCidade				= document.getElementById('formcadastro_txtCidade');
        
        var formcadastro_txtTel1Ddd				= document.getElementById('formcadastro_txtTel1Ddd');
        var formcadastro_txtTel1				= document.getElementById('formcadastro_txtTel1');
        var formcadastro_txtRamal1				= document.getElementById('formcadastro_txtRamal1');
		
		        
        var formcadastro_txtTel2Ddd				= document.getElementById('formcadastro_txtTel2Ddd');
        var formcadastro_txtTel2				= document.getElementById('formcadastro_txtTel2');
        var formcadastro_txtRamal2				= document.getElementById('formcadastro_txtRamal2');
        
        
        var formcadastro_txtCelularDdd			= document.getElementById('formcadastro_txtCelularDdd');
        var formcadastro_txtCelular				= document.getElementById('formcadastro_txtCelular');
        
        var formcadastro_txtFaxDdd				= document.getElementById('formcadastro_txtFaxDdd');
        var formcadastro_txtFax					= document.getElementById('formcadastro_txtFax');
        
        var formcadastro_txtEmail				= document.getElementById('formcadastro_txtEmail');
        
        var formcadastro_txtSenha				= document.getElementById('formcadastro_txtSenha');
        var formcadastro_txtSenhaConfirmacao	= document.getElementById('formcadastro_txtSenhaConfirmacao'); 
        
        
       
        var Msg = '';
        
        if(formcadastro_rdnPF.checked)
        { 
            if(Trim(formcadastro_txtPFNome.value) == '')           {Msg += 'Preencha corretamente o campo Nome.\n';				retorno = false;} ;
            if(Trim(formcadastro_txtPFRG.value) == '')			   {Msg += 'Preencha corretamente o campo RG.\n';				retorno = false;} ;
            
            if(Trim(formcadastro_txtPFNascDia.value) == '')        {Msg += 'Preencha corretamente o campo Dia.\n';				retorno = false;} ;
            if(Trim(formcadastro_txtPFNascMes.value) == '')        {Msg += 'Preencha corretamente o campo Mes.\n';				retorno = false;} ;
            if(Trim(formcadastro_txtPFNascAno.value) == '')        {Msg += 'Preencha corretamente o campo Ano.\n';				retorno = false;} ;
            
            if(retorno)
            {
				retorno = ValidaData(Trim(formcadastro_txtPFNascDia.value), Trim(formcadastro_txtPFNascMes.value), Trim(formcadastro_txtPFNascAno.value));
				
				if(!retorno)
				{
					Msg += 'A data de nascimento é inválida.\n';
				}
            }
              
            
            if(Trim(formcadastro_txtPFCPF.value) == '' || !validaCPF(Trim(formcadastro_txtPFCPF.value)))            
            {
				Msg += 'Preencha corretamente o campo CPF.\n';
				retorno = false;
			} 
        }
        else if(formcadastro_rdnPJ.checked)
        {
            if(Trim(formcadastro_txtPJRazaoSocial.value) == '')		{Msg += 'Preencha corretamente o campo Razão Social.\n';	retorno = false;} ;
            if(Trim(formcadastro_txtPJIE.value) == '')				{Msg += 'Preencha corretamente o campo IE.\n';				retorno = false;} ;
            if(Trim(formcadastro_txtPJNomeFantasia.value) == '')    {Msg += 'Preencha corretamente o campo Nome Fantasia.\n';	retorno = false;} ;

            if(Trim(formcadastro_txtPJCNPJ.value) == '' || !validaCNPJ(Trim(formcadastro_txtPJCNPJ.value)))           
            {
				Msg += 'Preencha corretamente o campo CNPJ.\n';
				retorno = false;
			} 
        } 
        

        
        if(Trim(formcadastro_txtCep.value) == '')				{Msg += 'Preencha corretamente o campo CEP.\n';		retorno = false;} ;
        if(Trim(formcadastro_txtEndereco.value) == '')          {Msg += 'Preencha corretamente o campo Endereço.\n';	retorno = false;} ;
        if(Trim(formcadastro_txtNumero.value) == '')			{Msg += 'Preencha corretamente o campo Número.\n';	retorno = false;} ;
        if(Trim(formcadastro_txtBairro.value) == '')            {Msg += 'Preencha corretamente o campo Bairro.\n';	retorno = false;} ;
        if(Trim(formcadastro_txtCidade.value) == '')			{Msg += 'Preencha corretamente o campo Cidade.\n';	retorno = false;} ;
        
        if(Trim(formcadastro_txtTel1Ddd.value) == '')			{Msg += 'Preencha corretamente o campo DDD 1.\n';	retorno = false;} ;
        if(Trim(formcadastro_txtTel1.value) == '')				{Msg += 'Preencha corretamente o campo Telefone 1.\n';	retorno = false;} ;
        
        /*
        if(Trim(formcadastro_txtTel2Ddd.value) == '')			{retorno = false;} ;
        if(Trim(formcadastro_txtTel2.value) == '')				{retorno = false;} ;
        
        if(Trim(formcadastro_txtCelularDdd.value) == '')		{retorno = false;} ;
        if(Trim(formcadastro_txtCelular.value) == '')			{retorno = false;} ;
        
        if(Trim(formcadastro_txtFaxDdd.value) == '')			{retorno = false;} ;
        if(Trim(formcadastro_txtFax.value) == '')				{retorno = false;} ;
        */
        
        
        if(Trim(formcadastro_txtEmail.value) == '' || !ValidaEmail(Trim(formcadastro_txtEmail.value)))
        {
			Msg += 'Preencha corretamente o campo E-Mail.\n';
			retorno = false;
		} 
        
        if(ParentForm == 'FormInclusaoCadastro')
        {
			if(Trim(formcadastro_txtSenha.value) == '')				{Msg += 'Preencha corretamente o campo Senha.\n';			retorno = false;} ;
			if(Trim(formcadastro_txtSenhaConfirmacao.value) == '')  {Msg += 'Preencha corretamente o campo Confirme Senha.\n';	retorno = false;} ;
			
			if(formcadastro_txtSenha.value != formcadastro_txtSenhaConfirmacao.value)
			{
				Msg += 'Confirme corretamente a Senha.\n';
				retorno = false;
			} 
		}


        if(!retorno)
        {
            alert(Msg);
        }                                             
    }
    catch(err)
    {
        alert(err.description);
    }
    
    return retorno;          
}

function MudaCorBorda(obj, cor)
{
    try
    {        
        var Borda               = '1px';
        var BordaEstilo         = 'solid';
        
        obj.style.border        = Borda;
        obj.style.borderStyle   = BordaEstilo;
        obj.style.borderColor   = cor;        
    }
    catch(err)
    {
        document.write(err.description);
    }    
}

/* CADASTRO */
function validaCPF(cpf) 
{
	var retorno = true;
	

	if(cpf == "")
	{
		retorno = false;
	}
	else
	{
		cpf = cpf.replace(".", "");
		cpf = cpf.replace(".", "");
		cpf = cpf.replace(".", "");
		cpf = cpf.replace(",", "");
		cpf = cpf.replace("-", "");
		cpf = cpf.replace(" ", "");

		erro = new String;
		if (cpf.length < 11) erro += "Sao necessarios 11 digitos para verificacao do CPF! \n\n"; 
		var nonNumbers = /\D/;
		if (nonNumbers.test(cpf)) erro += "A verificacao de CPF suporta apenas numeros! \n\n"; 
		
		if(cpf == "00000000000" || cpf == "11111111111" || cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" || cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" || cpf == "88888888888" || cpf == "99999999999")
		{
				erro += "Numero de CPF invalido!"
		}
	
		var a = [];
		var b = new Number;
		var c = 11;
		
		for (i=0; i<11; i++)
		{
				a[i] = cpf.charAt(i);
				if (i < 9) b += (a[i] * --c);
		}
		
		if ((x = b % 11) < 2) { a[9] = 0 } else { a[9] = 11-x }
		
		b = 0;
		c = 11;
		
		for (y=0; y<10; y++) b += (a[y] * c--); 
		
		if ((x = b % 11) < 2) { a[10] = 0; } else { a[10] = 11-x; }
		
		if ((cpf.charAt(9) != a[9]) || (cpf.charAt(10) != a[10]))
		{
				erro +="Digito verificador com problema!";
		}
		
		if (erro.length > 0)
		{
			//alert("Numero de CPF invalido!");
			retorno = false;
		}
	}    

	return retorno;
}


function validaCNPJ(cnpj)
{
	var retorno = true;
	
	CNPJ = Trim(cnpj);
	
	erro = new String;
	
	/*
	if (CNPJ.length < 18) erro += "É necessario preencher corretamente o número do CNPJ! "; 
	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! ";
	}
	//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 ("/","");
	}
	*/
	
	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! "; 
	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)
	{
		//alert("Numero de CNPJ invalido!");
		retorno = false;
	}
				
    return retorno;				
}

function ValidaEmail(email)
{
	var retorno = true;

	var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i 
	  
	 if (!filter.test(email)) 
	 {
		retorno = false;
	 }
	
	return retorno;
}

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);
     }
}

function ValidaData(dia, mes, ano)
{
	retorno = true;
		
	/* foi encontrado um bug no javascript (IE 6 e Firefox 2) na execucção
	   de parseInt com a string '08' retornando 0.   */
    
	dia = Number(dia);
	mes = Number(mes);
	ano = Number(ano);    
	
	if(ano < 1900)
	{
		return false;
	}
	
	
	switch (mes) 
    {
        case '01':
        case '03':
        case '05':
        case '07':
        case '08':
        case '10':
        case '12':
        {
            if  (dia > 31) 
            {
                retorno = false;
            }
            break
        }
        
        case '04':        
        case '06':
        case '09':
        case '11':
        {
            if  (dia > 30) 
            {
                retorno = false;
            }
            break
        }
        case '02':
        {
            /* Validando ano Bissexto / fevereiro / dia */
            if ((ano % 4 == 0) || (ano % 100 == 0) || (ano % 400 == 0)) 
            { 
                bissexto = 1; 
            } 
            if ((bissexto == 1) && (dia > 29)) 
            { 
                retorno = false;;                 
            } 
            if ((bissexto != 1) && (dia > 28)) 
            { 
                retorno = false; 
            }            
            break                        
    }
    }
	
	
	/*switch(mes)
	{
	    case 1: case 3: case 5: case 10: case 12:	              
	    {
	        if(dia > 31)
	        {   
	            retorno = false;
	        }
	        break;
	    }
	    case 4: case 6: case 9: case 11:
	    {
	        if(dia > 30)
	        {   	                
	            retorno = false;
	        }
	        break;
	    }
	    case 2:
	    {
	        bissexto = (((ano%4 == 0) && (ano%100 != 0)) || (ano%400 == 0));
    	    
	        if(bissexto)
	        {
	            if(dia > 29)
	            {	                    
	                retorno = false;
	            }
				break;
	        }
	        else
	        {
	            if(dia > 28)
	            {                        
	                retorno = false;
	            }	  
				break;
	        }
	    }  
		default:
	    {
	        if(mes==7 || mes==8)
	        {
	            if(dia > 31)
	            {  	                  
	                retorno = false;
	            }
	        }   
	        else
	        {  	               
	            retorno = false;
	        }  
	    }
	}*/
   	return retorno;
}

function Trim(STRING)
{
    STRING = LTrim(STRING);
    
    return RTrim(STRING);
}   

function RTrim(STRING)
{
    while(STRING.charAt((STRING.length -1))==" ")
    {
        STRING = STRING.substring(0,STRING.length-1);
    }
    
    return STRING;
}


function LTrim(STRING)
{
    while(STRING.charAt(0)==" ")
    {
        STRING = STRING.replace(STRING.charAt(0),"");
    }
    
    return STRING;
}

function ColocaFocoEm(NomeObj, e) 
{ 
	try
	{
		var key; 
		if(window.event) 
		{ 
			key = event.keyCode; 
		}
		else
		{ 
			key = e.which; 
		}
		if(key == 13)
		{
			document.getElementById(NomeObj).focus();
			event.keyCode = 0;
		}
	} 
	catch(err)
	{
		alert(err.description);
	}
	
	return false;
} 

/* Ajax */
function CarregaEndereco(campo)
{
	var CEP = campo.replace("-","");
	
	if(CEP.length == 8)
	{
		TrocaImagem("loading", "visible");
		formcadastro.CarregaEndereco(CEP, CarregaEndereco_CallBack);
	}
}

function CarregaEndereco_CallBack(response)
{
	if(!response.error)
	{
		var retorno = response.value;
		
		if(retorno[0])
		{
			var Cep = document.getElementById(retorno[5] + "txtCep").value;
			
			if(Cep.indexOf("-") == -1)
			{
				Cep = Cep.substr(0,5) + "-" + Cep.substr(5,3);
			}
			
			document.getElementById(retorno[5] + "txtCep").value		= Cep;
			document.getElementById(retorno[5] + "txtEndereco").value	= retorno[1];
			document.getElementById(retorno[5] + "txtBairro").value		= retorno[2];
			document.getElementById(retorno[5] + "txtCidade").value		= retorno[3];
			
			document.getElementById(retorno[5] + "ddlEstado").value		= retorno[4];
		}
		else
		{
			document.getElementById(retorno[2] + "txtEndereco").value	= "";
			document.getElementById(retorno[2] + "txtBairro").value		= "";
			document.getElementById(retorno[2] + "txtCidade").value		= "";
			document.getElementById(retorno[2] + "ddlEstado").value		= "SP";
		}
	}
	else
	{
		alert(response.error);
	}
		
	TrocaImagem("loading", "hidden");
}


