function abreAtendimento() {
	var rand = Math.random() * 100000000000000000;
	
	openPopup("../../../livezilla/chat.php?rand="+rand,465,600,"AtendimentoOnline"+rand,"no");
}

function imprimirBoleto() {
	if (isIE) {
		document.ifr_boleto.focus();
		document.ifr_boleto.print();
	} else {
		window.ifr_boleto.imprimeBoleto();
	}
}

function preencheCampo(obj) {
	if (obj.value == '') {
		obj.value = obj.defaultValue;
	}
}

function limpaCampo(obj) {
	if (obj.value == obj.title) {
		obj.value = '';
	}
}



function displayShow(iddisplay,idshow) {
	if (document.getElementById(iddisplay)) {
		if (document.getElementById(iddisplay).style.display != 'none') {
			document.getElementById(iddisplay).style.display = 'none';
		} else {
			document.getElementById(iddisplay).style.display = '';
		}
	}
	
	if (document.getElementById(idshow)) {
		document.getElementById(idshow).style.display = '';
	}
}

function checkProfissao(valor) {
	if ((valor.trim() != 'OUTRO') & (valor.trim() != 'OUTROS')) {
		$('tr_outraprofissao').style.display = 'none';
	} else {
		$('tr_outraprofissao').style.display = '';
	}
}

function checkRamoAtividade(valor) {
	if ((valor.trim() != 'OUTRO') & (valor.trim() != 'OUTROS')) {
		$('tr_outroramoatividade').style.display = 'none';
	} else {
		$('tr_outroramoatividade').style.display = '';
	}
}

function checkCargo(valor) {
	if ((valor.trim() != 'OUTRO') & (valor.trim() != 'OUTROS')) {
		$('tr_outrocargo').style.display = 'none';
	} else {
		$('tr_outrocargo').style.display = '';
	}
}

function selecionarTipoPessoa(tmp_tipo) {
	if (tmp_tipo == 'fisica') {
		$('div_camposformulario2').innerHTML = $('div_formpessoafisica').innerHTML;
		$('lblNome').style.display = '';	
		$('lblEmpresa').style.display = 'none';
	}else{
		$('div_camposformulario2').innerHTML = $('div_formpessoajuridica').innerHTML;
		$('lblNome').style.display = 'none';			
		$('lblEmpresa').style.display = '';	
	}
}

function enderecozerado(entrega){
	
	if(entrega == 'entrega'){
		var entrega = 'entrega'
		var check = document.frmCadastro.checknumeroentrega.checked;
	}else{
		var entrega = '';
		var check = document.frmCadastro.checknumero.checked;
	}
	if (check == true){
		$('Número'+entrega+'_NUM1').value = '0';
		$('Número'+entrega+'_NUM1').style.display = 'none';
	}else{
		$('Número'+entrega+'_NUM1').value = '';
		$('Número'+entrega+'_NUM1').style.display = '';
	}
}



function selecionarTipoPessoaEsqueciSenha(tmp_tipo) {
	if (tmp_tipo == 'fisica') {
		$('div_formulariojuridica').style.display = 'none';	
		$('div_formulariofisica').style.display = '';	
	} else {
		$('div_formulariofisica').style.display = 'none';			
		$('div_formulariojuridica').style.display = '';	
	}
}
var buscandoendereco = false;
function buscaCep(entrega) {
	
	if(entrega == 'entrega'){
		entrega = 'entrega';
	}else{
		entrega = '';
	}
	var cep = $('CEP'+entrega+'_CEP1').value;
	
	if (cep != '') {
		buscandoendereco = true;
		$('Endereço'+entrega+'_TXT1').value = 'Aguarde...';
		$('Bairro'+entrega+'_TXT1').value = 'Aguarde...';
		$('Cidade'+entrega+'_TXT1').value = 'Aguarde...';
	
		var retorno;
		var arr_retorno = new Array();
		var a = new Ajax();
		
		a.onLoad = function() {
			retorno = this.html;
			if (retorno != '') {
				arr_retorno = retorno.split("#");
				
				if (arr_retorno[0] == null){
					$('Endereço'+entrega+'_TXT1').value = '';
				}else{
					$('Endereço'+entrega+'_TXT1').value = arr_retorno[0];
				}
				$('Bairro'+entrega+'_TXT1').value = arr_retorno[1];
				$('Cidade'+entrega+'_TXT1').value = arr_retorno[2];
				$('Estado'+entrega+'_CMB1').value = arr_retorno[3];
				$('Número'+entrega+'_NUM1').value = '';
				$('Complemento'+entrega+'_TXT0').value = '';
				
			} else {
				$('Endereço'+entrega+'_TXT1').value = '';
				$('Bairro'+entrega+'_TXT1').value = '';
				$('Cidade'+entrega+'_TXT1').value = '';
				$('Estado'+entrega+'_CMB1').value = '';
				
				$('Cidade'+entrega+'_TXT1').disabled = '';
				$('Estado'+entrega+'_CMB1').disabled = '';
				$('Complemento'+entrega+'_TXT0').value = '';
				alert("Cidade não encontrada pelo CEP. Verifique se está correto.")
				$('CEP'+entrega+'_CEP1').focus;
			}
			buscandoendereco = false;
		}
		
		a.get("../../inc/routines/routines.php?rotina=busca_endereco&cep="+cep);
	}
}

/************** CARRINHO  ***********************************/

function setEventoLocalizacao(tmp_valor,tmp_campo) {
	if (tmp_valor != '') {
		$(tmp_campo).disabled = true;
	} else {
		$(tmp_campo).disabled = false;
	}
}

function adicionarItem(tmp_iditem,tmp_tipo, tmp_confirmacao,tmp_renovcaminho) {
	if (!tmp_confirmacao) {
		tmp_confirmacao = 'false';
	}
	
	var valorparcelamento = '';
	var el = document.getElementsByName('box_pagamento');
	for (i_el=0; i_el < el.length; i_el++) {
		var tmp = el[i_el].checked;
		if (tmp) { valorparcelamento = el[i_el].value; }
	}
	
	var a = new Ajax();
	
	a.onLoad = function() {
		retorno = this.html.trim();
		switch(retorno) {
			case '1':
				if(tmp_renovcaminho == undefined || tmp_renovcaminho == ''){
					alert("Item inserido com sucesso no carrinho.");	
				}else{
					if(tmp_renovcaminho == 'confirmacao'){
						alert("Item inserido com sucesso no carrinho.");
						window.location = 'renovar.php';
					}
				}
				break;
				
			case '2':
					alert("Item já está no carrinho.");	
				break;
				
			case '3':
					alert("Item já está no carrinho.");	// Antes era usado a mensagem "Você só pode ter 1 tipo de evento por carrinho.". Foi mudado a regra
				break;
				
			case '4':
					alert("Você já está inscrito para este evento.");
				break;
				
			case '5':
					if (confirm("Já está inscrito em um evento no dia.\nDeseja inscrever-se em outro evento?")) {
						adicionarItem(tmp_iditem,tmp_tipo, 'true'); // Refaz o pedido, mas agora inscrevendo o usuário
					}
					
				break;
				
			case '6':
					alert("Não há mais vagas para o evento.");	
				break;

			case '7':
					alert("Você não pode comprar este item. Tipo de pessoa que está comprando não pode comprar este item.\nQualquer dúvida, entre em contato conosco.");	
				break;
		}
	}
	
	a.get('../../inc/routines/routines.php?rotina=add_carrinho&id='+tmp_iditem+'&tipo='+tmp_tipo+'&confirmacao='+tmp_confirmacao+'&parcelamento='+valorparcelamento);
}

function alterarQuantidade(tmp_indice,tmp_id) {
	var tmp_valor = $(tmp_id).value;
	
	if (tmp_valor != $(tmp_id).defaultValue) {
		$('div_fecharpedido').style.display = 'none';
		if ($('div_calcularfrete')) {
			$('div_calcularfrete').style.display = '';
		}
		
		if ($('span_subtotal')) {
			$('span_subtotal').innerHTML = 'Calculando...';
		}
		
		var a = new Ajax();
		
		a.onLoad = function() {
			if (this.html == 1) {
				window.location = '../carrinho/index.php';
			} else {
				$('div_fecharpedido').style.display = '';	
			}
		}

		a.get('../../inc/routines/routines.php?rotina=alter_carrinho&indice='+tmp_indice+'&dado=quantidade&valor='+tmp_valor);
	}
}

function excluirItem(tmp_indice) {
	var a = new Ajax();

	a.onLoad = function() {
		window.location = '../carrinho/index.php';
	}

	a.get('../../inc/routines/routines.php?rotina=delete_carrinho&indice='+tmp_indice);
}

/*
Adiciona item no carrinho.
Param:
	tmp_iditem = id do item selecionado
	tmp_tipo = tipo do item selecionado. Evento, Assinatura, Produtos, Promoção
	tmp_confirmacao = Para identificar se a pessoa quer realmente se inscrever. Isso acontece quando a pessoa já está cadastrada para outro evento no mesmo dia.
	
Retorno:
	1 = Item inserido com sucesso no carrinho.
	2 = Item já está no carrinho.
	3 = Você só pode ter 1 tipo de evento por carrinho.
	4 = Usuário já está inscrito no evento
	5 = Já está inscrito em um evento no dia. Deseja inscrever-se em outro evento?
	6 = Não há vagas no evento
*/
function comprarItem(tmp_iditem,tmp_tipo, tmp_confirmacao){
	if (!tmp_confirmacao) {
		tmp_confirmacao = 'false';
	}
	
	var valorparcelamento = '';
	var el = document.getElementsByName('box_pagamento');
	for (i_el=0; i_el < el.length; i_el++) {
		var tmp = el[i_el].checked;
		if (tmp) { valorparcelamento = el[i_el].value; }
	}
	
	var a = new Ajax();
	a.onLoad = function() {
		retorno = this.html.trim();
		
		switch(retorno) {
			case '1':
					alert("Item inserido com sucesso no carrinho.");	
					
					window.location = '../carrinho/index.php';
				break;
				
			case '2':
					alert("Item já está no carrinho.");	
					
					window.location = '../carrinho/index.php';
				break;
				
			case '3':
					alert("Você só pode ter 1 tipo de evento por carrinho.");	
					
					window.location = '../carrinho/index.php';
				break;
				
			case '4':
					alert("Você já está inscrito para este evento.");
				break;
				
			case '5':
					if (confirm("Já está inscrito em um evento no dia.\nDeseja inscrever-se em outro evento?")) {
						comprarItem(tmp_iditem,tmp_tipo, 'true'); // Refaz o pedido, mas agora inscrevendo o usuário
					}
					
				break;
				
			case '6':
					alert("Não há mais vagas para o evento.");	
				break;
				
			case '7':
					alert("Você não pode comprar este item. Tipo de pessoa que está comprando não pode comprar este item.\nQualquer dúvida, entre em contato conosco.");	
				break;
		}
	}

	a.get('../../inc/routines/routines.php?rotina=add_carrinho&id='+tmp_iditem+'&tipo='+tmp_tipo+'&confirmacao='+tmp_confirmacao+'&parcelamento='+valorparcelamento);
}

function calculaValorFinal() {
	var tmp_subtotal = $('span_subtotal').innerHTML;
	var tmp_frete = $('span_frete').innerHTML;
	var tmp_valortotal = 0.0;
	
	tmp_subtotal = tmp_subtotal.replace('.','');
	tmp_frete = tmp_frete.replace('.','');

	tmp_subtotal = tmp_subtotal.replace(',','.');
	tmp_frete = tmp_frete.replace(',','.');
	tmp_subtotal++;tmp_subtotal--;
	tmp_frete++;tmp_frete--;

	tmp_valortotal = tmp_subtotal + tmp_frete;
	tmp_valortotal += '';
	$('span_valortotal').innerHTML = formatPreco(tmp_valortotal);
	
	
}


function renovarAssinatura() {
	var input = document.getElementsByTagName('input');
	var total = input.length;
	var inseridos = 0;
	
	for(x=0;x<total;x++) {
		if ((input[x].type == 'checkbox') && (input[x].id == 'Renovar assinatura_CHK0')) {
			if (input[x].checked) {
				adicionarItem(input[x].value,'renovacao');
				inseridos++;
			}
		}
	}
	
	if (inseridos > 0) {
		setTimeout(redirecinaParaCarrinho,3000);
	} else {
		alert('Nenhuma renovação inserida no carrinho.');	
	}
}

var redirecinaParaCarrinho = function () {
	window.location = '../carrinho/index.php';
}

function selectFormaPagamento(tmp_tipo) {
	if (document.getElementById('Forma de pagamento Boleto Bancário Banco do Brasil_RDO1')) {
		if (document.getElementById('Forma de pagamento Boleto Bancário Banco do Brasil_RDO1').checked) {
			document.getElementById('table_parcelas').style.display = 'none';	
		} else {
			document.getElementById('table_parcelas').style.display = '';	
		}		
	} else {
		document.getElementById('table_parcelas').style.display = '';	
	}
	
}

function sendFormEndereco(tmp_tipo) {
	if (tmp_tipo == 'cadastro') {
		$('Estado Cadastro_CMB1').disabled = '';
		$('Cidade Cadastro_TXT1').disabled = '';
		$('CEP Cadastro_CEP1').disabled = '';

		document.forms.frmEnderecoCadastro.action = 'pagamento.php';
		f.send('frmEnderecoCadastro'); 
	} else {
		$('Estado_CMB1').disabled = '';
		$('Cidade_TXT1').disabled = '';
		$('CEP_CEP1').disabled = '';

		document.forms.frmEndereco.action = 'pagamento.php';
		f.send('frmEndereco');
	}
}

function selecionarEnderecoEntrega(tmp_tipo) {
	if (tmp_tipo == 'cadastro') {
		$('div_outroendereco').style.display = 'none';
		$('div_enderecocadastro').style.display = '';
	} else {
		$('div_enderecocadastro').style.display = 'none';
		$('div_outroendereco').style.display = '';
	}
}


/************** / CARRINHO  ***********************************/


/************** PARTICIPANTES  ***********************************/
// Abre a popup para inserir participantes
function abrePoupParticipante(idevento) {
	var popup = new Popup(585,300);
	popup.template = 3;
	popup.bg_alpha = 80;
	
	popup.open('../carrinho/inserir_participante.php?idevento='+idevento);
}

// Busca os participantes pelo nome, e gerar o resultado
function buscaParticipante(idevento) {
	var nome = $('Nome do Participante_TXT1').value;
	var a = new Ajax();

	$('div_resultadobusca'+idevento).innerHTML = '';	
	$('div_aguarderesultadobusca'+idevento).style.display = '';

	a.onLoad = function() {
		$('div_aguarderesultadobusca'+idevento).style.display = 'none';
		$('div_resultadobusca'+idevento).innerHTML = this.html;	
	}
	
	a.get('../../inc/routines/routines.php?rotina=buscaParticipante&idevento='+idevento+'&nome='+nome);
}

// Adiciona um cliente que já esta vinculado com a empresa no banco mas inscrição do evento
function adicionaParticipanteById(idcliente,idevento) {
	if (idcliente != '') {
		var a = new Ajax();
		
		a.onLoad = function() {
			// Retorna: 1 = OK
			//			2 = Usuario já esta no carrinho
			//			3 = Não há mais espaço no carrinho, deve comprar mais ingressos.
			retorno = this.html;
			if (retorno == 1) {
				listaParticipante(idevento);
			} else {
				if (retorno == 2) {
					alert('Cliente já está na lista.');
				} else {
					if (retorno == 3) {
						alert('Quantidade de ingressos alcançado. Compre mais ingressos, ou retire algum usuário da lista para adicionar este usuário.');
					} else {
						alert('Algum erro ocorreu.');
					}
				}
			}
		}
		
		a.get('../../inc/routines/routines.php?rotina=adicionaParticipante&idevento='+idevento+'&idcliente='+idcliente);
	}
}

// Adiciona um nome cliente, que ainda não esta vinculado com a empresa
function adicionaParticipante(idevento) {
	var nome = document.getElementById('Nome_TXT1').value;
	var profissao = document.getElementById('Profissão_CMB1').value;
	var outraprofissao = document.getElementById('Outra profissão_TXT0').value;
	var email = document.getElementById('E-mail_EML1').value;
	var cpf = document.getElementById('CPF_CPF1').value;

	if ((nome != '') && (profissao != '') && (email != '') && (cpf != '')) {
		var a = new Ajax();
		
		a.onLoad = function() {
			// Retorna: 1 = OK
			//			2 = Usuario já esta no carrinho
			//			3 = Não há mais espaço no carrinho, deve comprar mais ingressos.
			retorno = this.html;
			retorno++;retorno--;
			
			switch(retorno) {
				case 1:
						listaParticipante(idevento);
						Popup_atual.close();
					break;
			
				case 2:
						alert('Cliente já está na lista.');
					break;
				
				case 3:
						alert('Quantidade de ingressos alcançado. Compre mais ingressos, ou retire algum usuário da lista para adicionar este usuário.');
					break;
	
				case 4:
						alert('O usuário já está inscrito para este evento.');
					break;
	
				case 5:
						alert('O usuário já está inscrito para um evento no mesmo dia. Certifique-se de que deseja realmente finalizar esta inscrição para este participante.Caso não queira inscrever o participante, exclua ele da lista.');
						listaParticipante(idevento);
						Popup_atual.close();
					break;
			}
		}
		
		a.get('../../inc/routines/routines.php?rotina=adicionaParticipante&idevento='+idevento+'&nome='+nome+'&profissao='+profissao+'&outraprofissao='+outraprofissao+'&email='+email+'&cpfcnpj='+cpf);
	} else {
		alert('Preencha todos os campos.');
	}
}

// Exclui o vinculo com o participante
function excluirParticipanteById(tmp_idcliente) {
	var a = new Ajax();
	
	a.onLoad = function() {
		if (this.html == '1') {
			alert('Sua solicitação foi enviada com sucesso.\nNosso suporte ao cliente desvinculará o usuário assim que possivel.');
		} else {
			alert('Algum erro aconteceu no servidor e sua solicitação não foi enviada. Tente novamente mais tarde.');	
		}
	}
	
	a.get('../../inc/routines/routines.php?rotina=desvincular_usuario&idcliente='+tmp_idcliente);
}


// Retira o participante da lista dos selecionados para o evento
function retirarParticipanteLista(indice,idevento) {
	var a = new Ajax();

	$('div_aguarde'+idevento).style.display = '';
	
	a.onLoad = function() {
		listaParticipante(idevento);
	}
	
	a.get('../../inc/routines/routines.php?rotina=retirarParticipante&idevento='+idevento+'&indice='+indice);
}

// Lista os participantes selecionados para o evento
function listaParticipante(idevento) {
	var a = new Ajax();
	
	$('div_aguarde'+idevento).style.display = '';
	
	a.onLoad = function() {
		$('div_aguarde'+idevento).style.display = 'none';
		$('div_participantesinscritos'+idevento).innerHTML = this.html;
	}
	
	a.get('../../inc/routines/routines.php?rotina=listaParticipante&idevento='+idevento);
}

function proximoPasso(idevento) {
	if (!idevento) {
		idevento = '';
	}
	
	var a = new Ajax();
	
	a.onLoad = function() {
		retorno = this.html;
		
		if (idevento == '') {
			if (retorno == 1) {
				window.location = 'endereco.php';
			} else {
				alert('Você deve preencher todas as vagas.');	
			}
		} else {
			if (retorno == 0) {
				window.location = 'endereco.php';
			} else {
				alert('Você deve preencher todas as vagas no '+retorno+'° evento.');	
			}
		}
	}
	
	a.get('../../inc/routines/routines.php?rotina=verificaQuantidadeLista&idevento='+idevento);
	
}

/************** / PARTICIPANTES  ***********************************/



/**************  FRETE  ***********************************/

function calculaFrete(tmp_cepOrigem,tmp_pesoFrete,tmp_volumeFrete) {
	var tmp_cepDestino = $('CEP_CEP1').value;
	var tmp_codigoFrete = $('Forma entrega_CMB1').value;
	if (tmp_pesoFrete > 30.000){
		alert('Seu pedido excedeu o peso máximo de 30 quilos. Para continuar, diminua seu pedido ou divida em mais compras.')
		tmp_pesoFrete = 30.000;
		peso30 = 'sim';
	}else{
		peso30 = 'nao';
	}
	$('span_frete').innerHTML = "Calculando...";
//	$('span_prazofrete').innerHTML = '';
	
	var a = new Ajax();
	a.onLoad = function() {
		retorno = this.html;

		
		if (retorno.length <= 6) {			
			$('span_frete').innerHTML = formatPreco(retorno);
	
			calculaValorFinal();
			/*
			var a2 = new Ajax();
			
			a2.onLoad = function() {
				
				if (this.html != '') {
					$('span_prazofrete').innerHTML = '(' + this.html + ' dia'+((this.html > 1)?'s':'')+')';
				} else {
					$('span_prazofrete').innerHTML = '';
				}
			} 
			
			a2.get('../../inc/routines/routines.php?rotina=busca_prazo');
			*/
			
//			alert($('span_frete').innerHTML);
			if (tmp_codigoFrete == 40010 && $('span_frete').innerHTML == '0,00'){
				alert('CEP não encontrado. Verifique seu CEP')
			}
			if (tmp_codigoFrete == 40010 && $('span_frete').innerHTML == '0,00' || peso30 == 'sim'){
				
				
			
			$('div_calcularfrete').style.display = ''; 
			$('div_fecharpedido').style.display = 'none'; 
			}else{
				
				$('div_calcularfrete').style.display = 'none'; 
				$('div_fecharpedido').style.display = ''; 
			}
			
			
			
		} else {
			$('span_frete').innerHTML = '0,00';
			$('div_fecharpedido').style.display = 'none'; 
			$('div_calcularfrete').style.display = ''; 

			calculaValorFinal();
			
			alert(this.html);
		}		
	}
	
	a.get('../../inc/routines/calculaFrete.php?cepOrigem='+tmp_cepOrigem+'&cepDestino='+tmp_cepDestino+'&pesoFrete='+tmp_pesoFrete+'&volumeFrete='+tmp_volumeFrete+'&codigoFrete='+tmp_codigoFrete);
}

/************** / FRETE  ***********************************/


function formatPreco(tmp_number) {
	var r = "";
	var n = String((Math.round(tmp_number * 100) / 100));
	var c, i2;
	var offset = 0;
	
	if (n.indexOf(".") > -1) {
		var arr = n.split(".");
		
		offset = 3;
		r = "," + arr[1];
		if (arr[1].length == 1) {
			offset = 2;
			r = r + "0";
		}
	} else {
		r = ",00";
	}
	
	i2 = 0;
	for (var i = (n.length - offset - 1); i >= 0; i--) {
		c = n.charAt(i);

		if (c == ".") {
			break;
		}
		
		i2++;
		if (i2 > 3) {
			r =  c + "." + r;	
			i2 = 1;
		} else {
			r = c + r;
		}
		
	}
	
	return r;
}

/**************  IMAGENS PRODUTOS  ***********************************/

function trocaImagem(tmp_imagem,tmp_iditem,tmp_tipo,tmp_indice,tmp_width,tmp_height) {
	var conteudo;
	var pasta;
	
	switch (tmp_tipo) {
		case 'A':
				pasta = 'loja_assinatura';
			break;
			
		case 'E':
				pasta = 'loja_evento';
			break;
			
		case 'P':
				pasta = 'loja_produto';
			break;
	
		case 'D':
				pasta = 'loja_promocao';
			break;
	}
	
	conteudo = '<p>';
	if (tmp_width > 0) {
		conteudo += "<a href=\"javascript:abreZoom('../../../upload/"+pasta+"/grande/"+tmp_iditem+"_"+tmp_indice+".jpg',"+tmp_width+","+tmp_height+");\">";
	}
	conteudo += "<img src=\""+tmp_imagem+"\" />";
	if (tmp_width > 0) {
		conteudo += "</a>";
	}
	conteudo += '</p>';
	
	$('td_imagemprincipal').innerHTML = conteudo;
}

function abreZoom(tmp_imagem,tmp_width,tmp_height) {
	var popup = new Popup(tmp_width,tmp_height);
	popup.template = 3;
	popup.open('../../inc/structure/zoomproduto.php?imagem='+tmp_imagem);
}

/************** / IMAGENS PRODUTOS  ***********************************/

/**************  CADASTRO  ***********************************/
/*
// Antes funcionava colocando o email no campo email de buscando no banco.
function recuperarSenha() {
	if ($('E-mail_EML1').value == '') {
		alert('Preencha o campo E-mail.');
		$('E-mail_EML1').focus();
	} else {
		var a = new Ajax();
		
		a.onLoad = function() {
			alert(this.html);	
		}
		
		a.get('../../inc/routines/routines.php?rotina=recuperar_senha&email='+$('E-mail_EML1').value);
	}
}
*/
//../../inc/routines/routines.php?rotina=gerar_senha
function recuperarSenha(tipoformulario) {
	var enviar = false;
	var cpf_cnpj = '';
	var data = '';
	var tipopessoa = '';
	var codigoassinante = '';
	var email = '';
	
	switch(tipoformulario) {
		case 'pessoafisica':
				tipopessoa = 'F';
				
					enviar = true;
					cpf_cnpj = $('CPF_CPF0').value;
					email = $('E-mail Pessoa Física_EML0').value;
			break;
			
		case 'pessoajuridica':
				tipopessoa = 'J';

					enviar = true;
					cpf_cnpj = $('CNPJ_CNP0').value;
					email = $('E-mail Pessoa Jurídica_EML0').value;
			break;
			
		case 'assinante':
				if ($('Código de assinante_NUM1').value != '') {
					enviar = true;
					codigoassinante = $('Código de assinante_NUM1').value;
					email = $('E-mail Assinante_EML1').value;
				} else {
					alert('Por favor complete o campo "Código de assinante"');
				}
			break;
	}
	
	
	if (enviar) {
		var a = new Ajax();
		
		a.onLoad = function() {
			alert(this.html);	
			document.forms.frmEsqueciSenhaPessoaFisica.reset();
			document.forms.frmEsqueciSenhaPessoaJuridica.reset();
			document.forms.frmEsqueciSenhaAssinante.reset();
		}
		
		a.get('../../inc/routines/routines.php?rotina=recuperar_senha&email='+email+'&tipopessoa='+tipopessoa+'&cpf_cnpj='+cpf_cnpj+'&codigoassinatura='+codigoassinante);
	}
//	if ($('E-mail_EML1').value == '') {
//		alert('Preencha o campo E-mail.');
//		$('E-mail_EML1').focus();
//	} else {
//		var a = new Ajax();
//		
//		a.onLoad = function() {
//			alert(this.html);	
//		}
//		
//		a.get('../../inc/routines/routines.php?rotina=recuperar_senha&email='+$('E-mail_EML1').value);
//	}
}

checkTxt = function (tmp_show,tmp_display,tmp_redir){
	var a = new Ajax();

	a.onLoad = function() {
		retorno = this.html;

		if (retorno == 1) {			
			document.getElementById('text_' + tmp_display).innerHTML = 'Verificando o cadastro...';
			checkTxtLog(tmp_show,tmp_display,tmp_redir);
		} else {
			if (retorno == 2) {
				document.getElementById(tmp_display).innerHTML = 'Ocorreu algum erro no servidor. Entre em contato, ou tente novamente mais tarde.';
				alert('Ocorreu algum erro no servidor. Entre em contato, ou tente novamente mais tarde.');
			}
		}	
	}
	
	a.get('../../inc/routines/routines.php?rotina=checkTXT');
}

checkTxtLog = function (tmp_show,tmp_display,tmp_redir){
	var a = new Ajax();
	
	a.onLoad = function() {
		retorno = this.html;
		if (retorno == 1) {
			if (tmp_redir != '') {
				window.location = tmp_redir;
			} else {
				document.getElementById(tmp_display).style.display = 'none';
				document.getElementById(tmp_show).style.display = '';
			}
		} else {
			if (retorno == 2) {
				document.getElementById(tmp_display).innerHTML = 'Ocorreu algum erro no servidor. Entre em contato, ou tente novamente mais tarde.';
				alert('Ocorreu algum erro no servidor. Entre em contato, ou tente novamente mais tarde.');
			} else {
				document.getElementById(tmp_display).innerHTML = retorno;
			}
		}	
	}
	
	a.get('../../inc/routines/routines.php?rotina=checkTxtLog');
}

function prePost(tmp_idform,tmp_rotina) {
	if (document.getElementById('Data de Nascimento_DAT1').value.length > '1'){
	var verifano = document.getElementById('Data de Nascimento_DAT1').value.split("/");
	if (verifano[2].length == '1'){
		verifano[2] = "197"+verifano[2];
		document.getElementById('Data de Nascimento_DAT1').value = ""+verifano[0]+"/"+verifano[1]+"/"+verifano[2]+"";
	}
	
	if (verifano[2].length == '2'){
		verifano[2] = "19"+verifano[2];
		document.getElementById('Data de Nascimento_DAT1').value = ""+verifano[0]+"/"+verifano[1]+"/"+verifano[2]+"";
	}
	if (verifano[2].length == '3'){
		verifano[2] = "1"+verifano[2];
		document.getElementById('Data de Nascimento_DAT1').value = ""+verifano[0]+"/"+verifano[1]+"/"+verifano[2]+"";
	}
	}

	
	var nonNumbers = /\D/;
	if (!nonNumbers.test(document.getElementById('Número_NUM1').value)) {
		var send = true;
		
		if ((document.getElementById('Profissao_CMB1').value == ' OUTROS') && (document.getElementById('Profissão_TXT0').value == '')) {
			alert('Por favor complete o campo "Profissão"');	
			document.getElementById('Profissão_TXT0').focus();
			
			send = false;
		}
		
		if ((document.getElementById('Cargo_CMB1').value == ' OUTROS') && (document.getElementById('Cargo_CMB1').value == '')) {
			alert('Por favor complete o campo "Cargo"');
			document.getElementById('Cargo_TXT0').focus();
			
			send = false;
		}
		
		
		// Verifica se ainda esta procurando o endereço
		if (buscandoendereco) {
			alert('Aguarde a busca do endereço.');
			
			send = false;
		} else {
			if ((document.getElementById('Endereço_TXT1').value == 'Aguarde...') || (document.getElementById('Bairro_TXT1').value == 'Aguarde...') || (document.getElementById('Cidade_TXT1').value == 'Aguarde...') || (document.getElementById('Estado_CMB1').value == 'Aguarde...')) {
				alert('Aguarde a busca do endereço.');
				
				send = false;
			}
		}
		
		if (send) {
			if (tmp_rotina == 'alterar_usuario') {
				prePostAlteracao(tmp_idform,tmp_rotina);
			} else {
				sendForm(tmp_idform,tmp_rotina);
			}
		}
	} else {
		alert('Número da casa deve ser apenas número.');	
		$('Número_NUM1').focus();
	}
}

function prePostAlteracao(tmp_idform,tmp_rotina) {
	$('span_aguarde').style.display = '';
	
	var endereco = $('Endereço_TXT1').value;
	var numero = $('Número_NUM1').value;
	var complemento = $('Complemento_TXT0').value;
	var cep = $('CEP_CEP1').value;
	var estado = $('Estado_CMB1').value;
	var cidade = $('Cidade_TXT1').value;
	var bairro = $('Bairro_TXT1').value;
	
	var a1 = new Ajax();
	
	a1.onLoad = function() {
		if (this.html > 0) {
			var a = new Ajax();
			
			a.onLoad = function() {
				retorno = this.html;
	
				if (retorno == 'true') {
					if (confirm('Você possui assinatura para este endereço.\nVocê deseja alterar o endereço do cadastro do site?\n\nObs.: alterando o endereço no site, você não alterará o endereço de entrega da assinatura. Entraremos em contato para verificar se você gostaria de mudar o endereço de entrega da assinatura ou se preferir, entre em contato fone 51-2131-0466 ou atendimento@protecao.com.br.')) {
						if (confirm('Deseja enviar uma notificação para nossa equipe informando que deseja alterar o endereço de entrega de assinatura?\n\nOK = Sim, quero que seja enviado uma notificação para a equipe de Proteção entrar em contato comigo para alterar meu endereço de entrega da assinatura.\nCancelar = Quero apenas mudar meu endereço de cadastro do site, não quero mudar meu endereço de entrega da assinatura.')) {
							document.getElementById('enderecoassinante_HDN0').value = 'true';
							sendForm(tmp_idform,tmp_rotina);
						} else {
							sendForm(tmp_idform,tmp_rotina);
						}
					} else {
						$('span_aguarde').style.display = 'none';	
					}
				} else {
					sendForm(tmp_idform,tmp_rotina);
				}
			}
			
			a.get('../../inc/routines/routines.php?rotina=verificaenderecoalteradoassinante&endereco='+endereco+'&numero='+numero+'&complemento='+complemento+'&cep='+cep+'&estado='+estado+'&cidade='+cidade+'&bairro='+bairro);
		} else {
			totalvezesrepetir++;	
			if (totalvezesrepetir < 15) {
				setTimeout("prePostAlteracao('"+tmp_idform+"','"+tmp_rotina+"')",5000);
				//prePostAlteracao(tmp_idform,tmp_rotina);
			} else {
				totalvezesrepetir = 0;
				$('span_aguarde').innerHTML = 'Erro para alterar o cadastro. Tente novamente mais tarde.';
			}
		}
	}
	
	a1.get('../../inc/routines/routines.php?rotina=verificaidusuario');
}
function sendForm(tmp_idform,tmp_rotina) {
	
	$('Estado_CMB1').disabled = '';
	$('Cidade_TXT1').disabled = '';

	document.forms.frmCadastro.action = '../../inc/routines/routines.php?rotina='+tmp_rotina;
	f.send(tmp_idform);
}


// Verifica se o CPF já esta cadastrado no momento que a pessoa digita ele no cadastro.
function checkCPFCNPJ(tmp_cpf,tmp_id,tmp_tipopessoa) {
	if (tmp_cpf != '') {
		var a = new Ajax();
		
		a.onLoad = function() {
			if (this.html != '') {
				alert(this.html);
				$(tmp_id).value = '';
				$(tmp_id).focus();
			}	
		}
		
		a.get('../../inc/routines/routines.php?rotina=check_cpf&cpf='+tmp_cpf+'&tipopessoa='+tmp_tipopessoa);
	}
}

function dddObrigatorio(idCampo){
	if(idCampo == 'Telefone_TLN0'){
		if (document.getElementById('DDD Telefone_NUM0')){
			document.getElementById('DDD Telefone_NUM0').id = 'DDD Telefone_NUM1';
		}					
	}
	
	if(idCampo == 'Telefone Comercial_TLN0'){
		if (document.getElementById('DDD Telefone Comercial_NUM0')){
			document.getElementById('DDD Telefone Comercial_NUM0').id = 'DDD Telefone Comercial_NUM1';
		}					
	}
	
	if(idCampo == 'Celular_TLN0'){
		if (document.getElementById('DDD Celular_NUM0')){
			document.getElementById('DDD Celular_NUM0').id = 'DDD Celular_NUM1';
		}					
	}
	
	if(idCampo == 'Fax_TLN0'){
		if (document.getElementById('DDD Fax_NUM0')){
			document.getElementById('DDD Fax_NUM0').id = 'DDD Fax_NUM1';
		}					
	}
	
	if(idCampo == 'Telefone Comercial_TLN0'){
		if (document.getElementById('DDD Telefone Comercial_NUM0')){
			document.getElementById('DDD Telefone Comercial_NUM0').id = 'DDD Telefone Comercial_NUM1';
		}					
	}
	
	if(idCampo == 'Telefone Comercial 2_TLN0'){
		if (document.getElementById('DDD Telefone Comercial 2_NUM0')){
			document.getElementById('DDD Telefone Comercial 2_NUM0').id = 'DDD Telefone Comercial 2_NUM1';
		}					
	}
}
/************** / CADASTRO  ***********************************/

/**************   RENOVACAO  ***********************************/


function prePostRenovacao(tmp_idform,tmp_rotina,idass,patch) {
	if(tmp_idform != '' && tmp_rotina != ''){
		if (document.getElementById('Data de Nascimento_DAT1').value.length > '1'){
			var verifano = document.getElementById('Data de Nascimento_DAT1').value.split("/");
			if (verifano[2].length == '1'){
				verifano[2] = "197"+verifano[2];
				document.getElementById('Data de Nascimento_DAT1').value = ""+verifano[0]+"/"+verifano[1]+"/"+verifano[2]+"";
			}
			
			if (verifano[2].length == '2'){
				verifano[2] = "19"+verifano[2];
				document.getElementById('Data de Nascimento_DAT1').value = ""+verifano[0]+"/"+verifano[1]+"/"+verifano[2]+"";
			}
			if (verifano[2].length == '3'){
				verifano[2] = "1"+verifano[2];
				document.getElementById('Data de Nascimento_DAT1').value = ""+verifano[0]+"/"+verifano[1]+"/"+verifano[2]+"";
			}
			}

			
			var nonNumbers = /\D/;
			if (!nonNumbers.test(document.getElementById('Número_NUM1').value)) {
				var send = true;
				
				if ((document.getElementById('Profissao_CMB1').value == ' OUTROS') && (document.getElementById('Profissão_TXT0').value == '')) {
					alert('Por favor complete o campo "Profissão"');	
					document.getElementById('Profissão_TXT0').focus();
					
					send = false;
				}
				
				if ((document.getElementById('Cargo_CMB1').value == ' OUTROS') && (document.getElementById('Cargo_CMB1').value == '')) {
					alert('Por favor complete o campo "Cargo"');
					document.getElementById('Cargo_TXT0').focus();
					
					send = false;
				}
				
				
				// Verifica se ainda esta procurando o endereço
				if (buscandoendereco) {
					alert('Aguarde a busca do endereço.');
					
					send = false;
				} else {
					if ((document.getElementById('Endereço_TXT1').value == 'Aguarde...') || (document.getElementById('Bairro_TXT1').value == 'Aguarde...') || (document.getElementById('Cidade_TXT1').value == 'Aguarde...') || (document.getElementById('Estado_CMB1').value == 'Aguarde...')) {
						alert('Aguarde a busca do endereço.');
						
						send = false;
					}
				}
			}
		
		prePostAlteracaoRenovacao(tmp_idform,tmp_rotina,idass,patch);
	}else{
		addrenov(idass,patch);
	}
}


function prePostAlteracaoRenovacao(tmp_idform,tmp_rotina,idass,patch) {
	
	var endereco = $('Endereço_TXT1').value;
	var numero = $('Número_NUM1').value;
	var complemento = $('Complemento_TXT0').value;
	var cep = $('CEP_CEP1').value;
	var estado = $('Estado_CMB1').value;
	var cidade = $('Cidade_TXT1').value;
	var bairro = $('Bairro_TXT1').value;
	
	var enderecoentrega = $('Endereçoentrega_TXT1').value;
	var numeroentrega = $('Númeroentrega_NUM1').value;
	var complementoentrega = $('Complementoentrega_TXT0').value;
	var cepentrega = $('CEPentrega_CEP1').value;
	var estadoentrega = $('Estadoentrega_CMB1').value;
	var cidadeentrega = $('Cidadeentrega_TXT1').value;
	var bairroentrega = $('Bairroentrega_TXT1').value;
	
	var a1 = new Ajax();
	
	a1.onLoad = function() {
		if (this.html > 0) {
			var a = new Ajax();
			
			a.onLoad = function() {
				retorno = this.html;
				
				var a2 = new Ajax();
				adicionarItem(idass,'renovacao','',patch);
				a2.onLoad = function() {
					retorno = this.html;
		
					if (retorno == 'true') {
						if (confirm('Você possui assinatura para este endereço.\nVocê deseja alterar o endereço do cadastro do site?\n\nObs.: alterando o endereço no site, você não alterará o endereço de entrega da assinatura. Entraremos em contato para verificar se você gostaria de mudar o endereço de entrega da assinatura ou se preferir, entre em contato fone 51-2131-0466 ou atendimento@protecao.com.br.')) {
							if (confirm('Deseja enviar uma notificação para nossa equipe informando que deseja alterar o endereço de entrega de assinatura?\n\nOK = Sim, quero que seja enviado uma notificação para a equipe de Proteção entrar em contato comigo para alterar meu endereço de entrega da assinatura.\nCancelar = Quero apenas mudar meu endereço de cadastro do site, não quero mudar meu endereço de entrega da assinatura.')) {
								document.getElementById('enderecoassinante_HDN0').value = 'true';
								sendForm(tmp_idform,tmp_rotina);
							} else {
								sendForm(tmp_idform,tmp_rotina);
							}
						} else {
							sendForm(tmp_idform,tmp_rotina);
						}
					} else {
						sendForm(tmp_idform,tmp_rotina);
					}
				}
				
				a2.get('../../inc/routines/routines.php?rotina=verificaenderecoalteradoassinante&endereco='+endereco+'&numero='+numero+'&complemento='+complemento+'&cep='+cep+'&estado='+estado+'&cidade='+cidade+'&bairro='+bairro);
			}
			a.get('../../inc/routines/routines.php?rotina=alteraentregarenovacao&endereco='+enderecoentrega+'&numero='+numeroentrega+'&complemento='+complementoentrega+'&cep='+cepentrega+'&estado='+estadoentrega+'&cidade='+cidadeentrega+'&bairro='+bairroentrega);
		} else {
			totalvezesrepetir++;	
			if (totalvezesrepetir < 15) {
				setTimeout("prePostAlteracao('"+tmp_idform+"','"+tmp_rotina+"')",5000);
				//prePostAlteracao(tmp_idform,tmp_rotina);
			} else {
				totalvezesrepetir = 0;
			}
		}
	}
	
	a1.get('../../inc/routines/routines.php?rotina=verificaidusuario');
}

function addrenov(idass,patch){
	var a1 = new Ajax();
	a1.onLoad = function() {
		if (this.html > 0) {
			var a = new Ajax();
			
			a.onLoad = function() {
				adicionarItem(idass,'renovacao','',patch);
			}
			
			a.get('../../inc/routines/routines.php?rotina=carrinhorenew');
		}
	}
	a1.get('../../inc/routines/routines.php?rotina=verificaidusuario');
}

/************** / RENOVACAO  ***********************************/

function mudaBoxPreco(tmp_tabela) {
	if (tabelaatual != tmp_tabela) {
		if ($('div_boxpreco_'+tabelaatual)) {
			$('div_boxpreco_'+tabelaatual).style.display = 'none';
			if ($('div_botaoativo_boxpreco_'+tabelaatual)) {
				$('div_botaoativo_boxpreco_'+tabelaatual).style.display = 'none';
			}
		}
		tabelaatual = tmp_tabela;					
		if ($('div_boxpreco_'+tabelaatual)) {
			$('div_boxpreco_'+tabelaatual).style.display = '';
			if ($('div_botaoativo_boxpreco_'+tabelaatual)) {
				$('div_botaoativo_boxpreco_'+tabelaatual).style.display = '';
			}
		}
	}
}
