function tipoTransfer( op )
{
	if( op == 1 )
	{
		//document.getElementById('txtDtSaida').disabled = true;
		document.getElementById('divSaida').style.display = "none";
	}
	else
	{
		//document.getElementById('txtDtEntrada').disabled = false;
		//document.getElementById('txtDtSaida').disabled = false;
		document.getElementById('divSaida').style.display = "block";
	}
}

function exibePagina( pagina, destino, dados )
{
	chamaPagina(pagina, dados, destino, 'GET' );
}

function buscaEmpresa()
{
	window.location='cadastro.php?q=' + document.getElementById('txtEmpresa').value;
}

function adicionarTelefone()
{
	$("table").add("input").css("background", "yellow");
}

function cadastroPessoa( valor )
{
	var div_pessoaFisica = document.getElementById('dadosPessoaFisica');
	var div_pessoaJuridica = document.getElementById('dadosPessoaJuridica');
	
	if( valor == 1 )
	{
		div_pessoaFisica.style.display = "block";
		div_pessoaJuridica.style.display = "none";
		document.getElementById('labTipoPessoaFisica').style.fontSize = "18px";
		document.getElementById('labTipoPessoaJuridica').style.fontSize = "14px";
	}
	else
	{
		div_pessoaFisica.style.display = "none";
		div_pessoaJuridica.style.display = "block";
		document.getElementById('labTipoPessoaFisica').style.fontSize = "14px";
		document.getElementById('labTipoPessoaJuridica').style.fontSize = "18px";
	}
}

/*
	AJAX
*/

/**
 * @author Silas
 * @return {Object} xmlhttp XMLHTTPRequest
 */
function iniciaAjax()
{
	var xmlhttp = false;
	
	try 
	{
		xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); // IE's mais novos
	}
	catch( e )
	{
		try
		{
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); // IE's mais antigos
		}
		catch( E )
		{
			xmlhttp = false;
		}
	}
	
	if( !xmlhttp && ( typeof XMLHttpRequest != "undefined" ) )
	{
		xmlhttp = new XMLHttpRequest(); // Outros Navegadores
	}
	
	return xmlhttp;
}

/**
 * @author Silas
 * @param {String} caminhoPagina
 * @param {String} variaveisEnvia
 * @param {String} objId
 * @param {String} tipoEnvio
 * @depende iniciaAjax()
 */
var retornoAjax = null;
function chamaPagina( caminhoPagina, variaveisEnvia, objId, tipoEnvio )
{
	var ajax = iniciaAjax();
	var obj = document.getElementById(objId);
	
	//obj.innerHTML = "<img src='images/ajax-loader.gif' />carregando...";

	if( tipoEnvio == "GET" )
	{
		ajax.open("GET", caminhoPagina + "?" + variaveisEnvia);
		variaveisEnvia = "";
	}
	else
	{
		ajax.open("POST", caminhoPagina, true);
		ajax.setRequestHeader("Method", "POST " + caminhoPagina + " HTTP/1.1");
		ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	}
	
	ajax.onreadystatechange = function()
	{
		if( ajax.readyState == 4 && ajax.status == 200 )
		{
			obj.innerHTML = ajax.responseText;
			//alert(1);
			retornoAjax = ajax.responseText;
		}
		else if ( ajax.status == 304 )
		{
			obj.innerHTML = "Problema com o cache do seu navegador.";
		}
		else if( ajax.status == 401 )
		{
			obj.innerHTML = "O acesso a essa p&aacute;gina requer autentica&ccedil;&atilde;o.";
		}
		else if( ajax.status == 403 )
		{
			obj.innerHTML = "Essa p&aacute;gina n&atilde;o est&aacute; acess&iacute;vel, sem permiss&atilde;o de acesso.";
		}
		else if( ajax.status == 404 )
		{
			obj.innerHTML = "P&aacute;gina n&atilde;o existe.";
		}
		else if( ajax.status == 500 )
		{
			obj.innerHTML = "Erro interno no servidor.";
		}
		else if( ajax.status == 503 )
		{
			obj.innerHTML = "Servi&ccedil;o nao dispon&iacute;vel.";
		}
	}			
	ajax.send(variaveisEnvia);
}

function buscaCep()
{
	var div_1 = document.getElementById('txtEnderecoCep1');
	var div_2 = document.getElementById('txtEnderecoCep2');
	var cidade = document.getElementById('CIDADE_');
	
	if( div_1.value != "" && div_2.value != "")
	{
		var cep = div_1.value + div_2.value;
		
		chamaPagina('buscaCep.php', 'cep='+cep+'&formato=string', 'CIDADE_', 'GET' );
		
		document.getElementById('sts_cep').innerHTML = "buscando...";
		//setTimeout('alert(retornoAjax);', 900);
		//alert(cidade.innerHTML.length);
		
		document.getElementById('txtEnderecoLogradouro').value = "";
		document.getElementById('txtEnderecoBairro').value = "";
		document.getElementById('txtEnderecoCidade').value = "";
		document.getElementById('CIDADE').innerHTML = "";
		document.getElementById('CIDADE_').innerHTML = "";
		document.getElementById('ESTADO').innerHTML = "";
		
		if( cidade.innerHTML.length < 10 )
		{
			xxx();
		}
	}
	else
	{
		document.getElementById('sts_cep').innerHTML = '<span style="color : red;">Informe o CEP primeiro.</span>';
	}
}
var dadosEndereco = null;

function xxx()
{
	var cidade = document.getElementById('CIDADE_');
	//alert(cidade.innerHTML.length);
	if( cidade.innerHTML.length < 10 )
	{
		//alert(1);
		setTimeout('xxx();', 50);
	}
	else
	{
		trataDadosEndereco();
	}
}

function trataDadosEndereco()
{
	var dadosEndereco = retornoAjax.split("&");
	//alert(dadosEndereco);
	//alert(dadosEndereco);
	var logradouro = document.getElementById('txtEnderecoLogradouro');
	var bairro = document.getElementById('txtEnderecoBairro');
	var cidade = document.getElementById('txtEnderecoCidade');
	var CIDADE_ = document.getElementById('CIDADE');
	var ESTADO = document.getElementById('ESTADO');
	
	logradouro.value = dadosEndereco[5].replace('tipo_logradouro=', '') + " " + dadosEndereco[6].replace('logradouro=', '');
	bairro.value = dadosEndereco[4].replace('bairro=', '');
	cidade.value = dadosEndereco[3].replace('cidade=', '');
	CIDADE_.innerHTML = dadosEndereco[3].replace('cidade=', '');
	ESTADO.innerHTML = dadosEndereco[2].replace('uf=', '');
	document.getElementById('sts_cep').innerHTML = "";
	
	//alert(cidade.value);
}
/*
function validaCPF(cpf) 
{
  erro = new String;

	if (cpf.value.length == 11)
	{	
			cpf.value = cpf.value.replace('.', '');
			cpf.value = cpf.value.replace('.', '');
			cpf.value = cpf.value.replace('-', '');

			var nonNumbers = /\D/;
	
			if (nonNumbers.test(cpf.value)) 
			{
					erro = "A verificacao de CPF suporta apenas numeros!"; 
			}
			else
			{
					if (cpf.value == "00000000000" || 
							cpf.value == "11111111111" || 
							cpf.value == "22222222222" || 
							cpf.value == "33333333333" || 
							cpf.value == "44444444444" || 
							cpf.value == "55555555555" || 
							cpf.value == "66666666666" || 
							cpf.value == "77777777777" || 
							cpf.value == "88888888888" || 
							cpf.value == "99999999999") {
							
							erro = "Numero de CPF invalido!"
					}
	
					var a = [];
					var b = new Number;
					var c = 11;

					for (i=0; i<11; i++){
							a[i] = cpf.value.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.value.charAt(9) != a[9]) || (cpf.value.charAt(10) != a[10])) {
						erro = "Numero de CPF invalido.";
					}
			}
	}
	else
	{
		if(cpf.value.length == 0)
			return false
		else
			erro = "Numero de CPF invalido.";
	}
	if (erro.length > 0) {
			alert(erro);
			cpf.focus();
			return false;
	} 	
	return true;	
}

//envento onkeyup
function maskCPF(CPF) {
	var evt = window.event;
	kcode=evt.keyCode;
	if (kcode == 8) return;
	if (CPF.value.length == 3) { CPF.value = CPF.value + '.'; }
	if (CPF.value.length == 7) { CPF.value = CPF.value + '.'; }
	if (CPF.value.length == 11) { CPF.value = CPF.value + '-'; }
}

// evento onBlur
function formataCPF(CPF)
{
	with (CPF)
	{
		value = value.substr(0, 3) + '.' + 
				value.substr(3, 3) + '.' + 
				value.substr(6, 3) + '-' +
				value.substr(9, 2);
	}
}
function retiraFormatacao(CPF)
{
	with (CPF)
	{
		value = value.replace (".","");
		value = value.replace (".","");
		value = value.replace ("-","");
		value = value.replace ("/","");
	}
}

function valida_cnpj(cnpj)
{
	var numeros, digitos, soma, i, resultado, pos, tamanho, digitos_iguais;
	digitos_iguais = 1;
	if (cnpj.length < 14 && cnpj.length < 15)
	{
		return false;
	}
	
	for (i = 0; i < cnpj.length - 1; i++)
	{
		if (cnpj.charAt(i) != cnpj.charAt(i + 1))
        {
            digitos_iguais = 0;
            break;
        }
	}
	
	if (!digitos_iguais)
   	{
      	tamanho = cnpj.length - 2
      	numeros = cnpj.substring(0,tamanho);
      	digitos = cnpj.substring(tamanho);
      	soma = 0;
      	pos = tamanho - 7;
      	
      	for (i = tamanho; i >= 1; i--)
        {
            soma += numeros.charAt(tamanho - i) * pos--;
            if (pos < 2)
			{
				pos = 9;
			}
        }
      	
      	resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
      	if (resultado != digitos.charAt(0))
		{
			return false;
		}
      	
      	tamanho = tamanho + 1;
      	numeros = cnpj.substring(0,tamanho);
      	soma = 0;
      	pos = tamanho - 7;
      
      	for (i = tamanho; i >= 1; i--)
        {
            soma += numeros.charAt(tamanho - i) * pos--;
            if (pos < 2)
			{
				pos = 9;
			}
        }
      
      	resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
      	
      	if (resultado != digitos.charAt(1))
		{
			return false;
		}
      	
      	return true;
	}
	else
      	return false;
}
*/

// JavaScript Document
//adiciona mascara de cnpj

function MascaraCNPJ(cnpj){
    if(mascaraInteiro(cnpj)==false){
        event.returnValue = false;
    }    
    return formataCampo(cnpj, '00.000.000/0000-00', event);
}

//adiciona mascara de cep
function MascaraCep(cep){
        if(mascaraInteiro(cep)==false){
        event.returnValue = false;
    }    
    return formataCampo(cep, '00.000-000', event);
}

//adiciona mascara de data
function MascaraData(data){
    if(mascaraInteiro(data)==false){
        event.returnValue = false;
    }    
    return formataCampo(data, '00/00/0000', event);
}

//adiciona mascara ao telefone
function MascaraTelefone(tel){    
    if(mascaraInteiro(tel)==false){
        event.returnValue = false;
    }    
    return formataCampo(tel, '(00) 0000-0000', event);
}

//adiciona mascara ao CPF
function MascaraCPF(cpf){
    if(mascaraInteiro(cpf)==false){
        event.returnValue = false;
    }    
    return formataCampo(cpf, '000.000.000-00', event);
}

//valida telefone
function ValidaTelefone(tel){
    exp = /\(\d{2}\)\ \d{4}\-\d{4}/
    if(!exp.test(tel.value))
        alert('Numero de Telefone Invalido!');
}

//valida CEP
function ValidaCep(cep){
    exp = /\d{2}\.\d{3}\-\d{3}/
    if(!exp.test(cep.value))
        alert('Numero de Cep Invalido!');        
}

//valida data
function ValidaData(data){
    exp = /\d{2}\/\d{2}\/\d{4}/
    if(!exp.test(data.value))
        alert('Data Invalida!');            
}

//valida o CPF digitado
function ValidarCPF(Objcpf){
    var cpf = Objcpf.value;
    exp = /\.|\-/g
    cpf = cpf.toString().replace( exp, "" );
    var digitoDigitado = eval(cpf.charAt(9)+cpf.charAt(10));
    var soma1=0, soma2=0;
    var vlr =11;
    
    for(i=0;i<9;i++){
        soma1+=eval(cpf.charAt(i)*(vlr-1));
        soma2+=eval(cpf.charAt(i)*vlr);
        vlr--;
    }    
    soma1 = (((soma1*10)%11)==10 ? 0:((soma1*10)%11));
    soma2=(((soma2+(2*soma1))*10)%11);
    
    var digitoGerado=(soma1*10)+soma2;
    if(digitoGerado!=digitoDigitado)    
        alert('CPF Invalido!');        
}

//valida numero inteiro com mascara
function mascaraInteiro(){
/*    if (event.keyCode < 48 || event.keyCode > 57){
        event.returnValue = false;
        return false;
    }*/	
    return true;
}

//valida o CNPJ digitado
function ValidarCNPJ(ObjCnpj){
    var cnpj = ObjCnpj.value;
    var valida = new Array(6,5,4,3,2,9,8,7,6,5,4,3,2);
    var dig1= new Number;
    var dig2= new Number;
    
    exp = /\.|\-|\//g
    cnpj = cnpj.toString().replace( exp, "" );
    var digito = new Number(eval(cnpj.charAt(12)+cnpj.charAt(13)));
        
    for(i = 0; i<valida.length; i++){
        dig1 += (i>0? (cnpj.charAt(i-1)*valida[i]):0);    
        dig2 += cnpj.charAt(i)*valida[i];    
    }
    dig1 = (((dig1%11)<2)? 0:(11-(dig1%11)));
    dig2 = (((dig2%11)<2)? 0:(11-(dig2%11)));
    
    if(((dig1*10)+dig2) != digito)    
    {
        alert('CNPJ Invalido!');
        //ObjCnpj.focus();
    }   
}

//formata de forma generica os campos
function formataCampo(campo, Mascara, evento) {
    var boleanoMascara;
    
    var Digitato = evento.keyCode;
    exp = /\-|\.|\/|\(|\)| /g
    campoSoNumeros = campo.value.toString().replace( exp, "" );
  
    var posicaoCampo = 0;    
    var NovoValorCampo="";
    var TamanhoMascara = campoSoNumeros.length;;
    
    if (Digitato != 8) { // backspace
        for(i=0; i<= TamanhoMascara; i++) {
            boleanoMascara  = ((Mascara.charAt(i) == "-") || (Mascara.charAt(i) == ".")
                                || (Mascara.charAt(i) == "/"))
            boleanoMascara  = boleanoMascara || ((Mascara.charAt(i) == "(")
                                || (Mascara.charAt(i) == ")") || (Mascara.charAt(i) == " "))
            if (boleanoMascara) {
                NovoValorCampo += Mascara.charAt(i);
                  TamanhoMascara++;
            }else {
                NovoValorCampo += campoSoNumeros.charAt(posicaoCampo);
                posicaoCampo++;
              }           
          }    
        campo.value = NovoValorCampo;
          return true;
    }else {
        return true;
    }
}

function IEIsento( obj )
{
	if( obj.checked == true )
	{
		document.getElementById('txtInscricaoEstadual').disabled = true;
	}
	else
	{
		document.getElementById('txtInscricaoEstadual').disabled = false;
	}
}

/***/

function mostraPagamento(id)
{
	document.getElementById('formaBradesco').style.display = "none";
	
	if( document.getElementById('formaAFaturar') )
	{
		document.getElementById('formaAFaturar').style.display = "none";
	}
	
	if( document.getElementById(id).style.display == "block"  || document.getElementById(id).style.display == "" )
	{
		document.getElementById(id).style.display = "none";
	}
	else
	{
		document.getElementById(id).style.display = "block";
	}
}