function mostraDados(idEsconder,idMostrar)
{
	if( idEsconder == 'juridica' )
	{
		document.getElementById('cadastro-subtitulo-pessoa-fisica').style.display = '';
		document.getElementById('cadastro-campo2').style.display = '';
		document.getElementById('cadastro-subtitulo-pessoa-juridica').style.display = 'none';
		document.getElementById('cadastro-campo3').style.display = 'none';
	}
	else if( idEsconder == 'fisica' )
	{
		document.getElementById('cadastro-subtitulo-pessoa-fisica').style.display = 'none';
		document.getElementById('cadastro-campo2').style.display = 'none';
		document.getElementById('cadastro-subtitulo-pessoa-juridica').style.display = '';
		document.getElementById('cadastro-campo3').style.display = '';
	}
}

//objeto sugestão
objSugestao = new Sugestao(1);

//carrega o documento e executa function
$(document).ready(function()
{
	objSugestao.executaFuncao();					
});




//troca a categoria
function trocaCategoria( intCat )
{
	this.intCategoria = intCat;	
	this.time         = true;
	this.executaFuncao();
}

//executa sugesto
function executaFuncao()
{
	jQuery("#busca").suggest(
	"includes/ajax/ajax-sugestao.php",{
	    onSelect: function() {
	        $("#busca").val(this.value);
	    },
	    data: '&categoria='+this.intCategoria,
	    timeout: this.time,
	    clearCache: true
	}
	);
}

//sugere o resultado
function Sugestao(intCat)
{
	this.intCategoria   = intCat;
	this.trocaCategoria = trocaCategoria;
	this.executaFuncao  = executaFuncao;
	this.time           = true;
}

//fecha div com slow
function mostraEsconteElemento(id)
{
	var objElemento = $('#'+id);
	if( document.getElementById(id).style.display == 'none' )
		objElemento.show(3000);
	else
		objElemento.hide(3000);
}

//mostra elemento com slow
function mostraElemento(id)
{
	var objElemento = $('#'+id);
	objElemento.show(3000);
}

//esconde elemento com slow
function escondeElemento(id)
{
	var objElemento = $('#'+id);
	objElemento.hide(3000);
}

//trocar o texto e o alt de link
function trocaNomeLink(idTrocarLink, idValidar )
{
	var objElemento = $('#'+idTrocarLink);
	var strAcao     = null;
	
	if( document.getElementById(idValidar).style.display == '' || document.getElementById(idValidar).style.display == 'block' )
	{
		objElemento.html('MOSTRAR<br />CARRINHO');
		objElemento.attr('title', 'MOSTRAR CARRINHO');
		strAcao = 'ocultar';
	}
	else
	{
		objElemento.html('OCULTAR<br />CARRINHO');
		objElemento.attr('title', 'OCULTAR CARRINHO');
		strAcao = 'mostrar';
	}	
	
	//chama o ajax para trocar a varivel da sesso
	$.post("ajax_ocultar_carrinho.php", { acao: strAcao } );
}


//troca o texto e esconde ou mostra o elemento
function trocaVisibilidadeLink(idTrocarLink, idValidar, idCampoExtra)
{
	trocaNomeLink(idTrocarLink, idValidar );
	mostraEsconteElemento(idValidar);
	mostraEsconteElemento(idCampoExtra);
}

//function usada no mini-carrinho do topo
function ocultaCarrinho()
{
	escondeElemento('tituloCarrinho');
	escondeElemento('carrinho-produtos');
	escondeElemento('abreFechaCarrinho');
	escondeElemento('fecharCompra');
	
	//chama o ajax para trocar a varivel da sesso
	$.post("ajax_ocultar_carrinho.php", { acao: 'ocultar' } );
}

//function usada no mini-carrinho do topo
function mostraCarrinho()
{
	mostraElemento('tituloCarrinho');
	mostraElemento('carrinho-produtos');
	mostraElemento('abreFechaCarrinho');
	mostraElemento('fecharCompra');
	
	//chama o ajax para trocar a varivel da sesso
	$.post("ajax_ocultar_carrinho.php", { acao: 'mostrar' } );
}

//troca class de um elemento
function trocaClass(idElemento, strClass)
{
	$("#"+idElemento).addClass(strClass);	
}

//seleciona uma class e retira esta class dos outros componentes
function verificaFormaPagamento(idElemento, intQuantidade)
{
	var strNomeElemento       = 'tr'+idElemento;
	var strValidaNomeElemento = null;
	for( i = 1; i <= intQuantidade; i++ )
	{
		strValidaNomeElemento = 'tr'+i;
		if( strNomeElemento == strValidaNomeElemento )
		{
			$("#rdb_"+i).attr('checked', true);
			$("#tr"+i).addClass('ativo');	
			$("#spn"+i).show();		
		}
		else
		{
			$("#rdb_"+i).attr('checked', false);
			$("#tr"+i).removeClass('ativo');
			$("#spn"+i).hide();	
		}
	}
}

//acompanha pedido
//seleciona uma class e retira esta class dos outros componentes
function verificaDetalheDoPedido(idElemento, intQuantidade)
{
	var strNomeElemento       = 'div_'+idElemento;
	var strValidaNome         = null; 
	for( i = 0; i < intQuantidade; i++ )
	{
		strValidaNome = 'div_'+i;
		if( strValidaNome == strNomeElemento && document.getElementById(strNomeElemento).style.display == 'none' )
		{
			$("#lnk_"+i).removeClass('bt-mais replacent');
			$("#lnk_"+i).addClass('bt-menos replacent');
			$("#lnk_"+i).attr('title', 'Ocultar Detalhes');
		//	$("#lnk_"+i).html="";			
		//	$("#div_"+i).show(200);	
			document.getElementById("div_"+i).style.display="";
		}
		else
		{
			$("#lnk_"+i).removeClass('bt-menos replacent');
			$("#lnk_"+i).addClass('bt-mais replacent');
			$("#lnk_"+i).attr('title', 'Mostrar Detalhes');
		//	$("#lnk_"+i).html="";						
		//	$("#div_"+i).hide(200);	
			document.getElementById("div_"+i).style.display="none";
		}
	}
}

//menu trocar as class
function trocaClassMenu(strId, intTotal)
{
	//verifica se já estava aberto
	var bolAberto = $("#"+strId).hasClass('ativo');
	var arrTemp = strId.split('_');
	
	//verifica qual link está ativo
	if( $("#"+strId) && !bolAberto )
	{
		$("#"+strId).addClass('ativo');
		$("#"+strId+' > ul li a').show(500);
		$("#ul_"+arrTemp[1]).show(500);
	}
	else
	{
		$("#"+strId).removeClass('ativo');
		$("#"+strId+' > ul li a').hide(500);
		$("#ul_"+arrTemp[1]).hide(500);
	}
}

/*****************************************************
*	Funções do carrinho de compras                   *
******************************************************/

//carrinho links mostrar configuração
function mostraEsconteElementoTrocaLink(idMostraEsconde, idLink)
{
	var objElementoMostraEsconde = $('#'+idMostraEsconde);
	var objElementoLink = $('#'+idLink);
	var strMensagem = null;
	
	if( document.getElementById(idMostraEsconde).style.display == 'none' )
	{
		objElementoMostraEsconde.show(2000);
		strMensagem = 'Ocultar Configuração';
	}
	else
	{
		objElementoMostraEsconde.hide(2000);
		strMensagem = 'Ver Configuração';
	}
	objElementoLink.html(strMensagem);
	objElementoLink.attr('title', strMensagem);
}

//carrega funções referentes ao cep do carrinho de compras de forma dinâmica
function facilitaCep(usaAjax, bolExecuta)
{
	$("#cep1").focus(
						function()
						{ 
							this.value = ''; 
						}
					);
	
					
	$("#cep1").keydown(
							function()
							{ 
								if( $("#cep1").val().length == 5 )
								{ 
									$("#cep2").focus();
								} 
							}
						);


	
	//máscara
	Mascaras.carregar();
	
	//monta o link não sei meu cep
	$("#nao_sei_cep").attr("href", "http://www.correios.com.br/servicos/cep/cep_loc_log.cfm");
	$("#nao_sei_cep").attr("target", "_blank");
	
	//valida form e coloca o link na botão para submeter o form
//	$("#calcular_frete").attr("href", "#");
	$("#calcular_frete").click(
								  function ()
								  {
								  	verifica(usaAjax, bolExecuta);							  	
								  }
							  )
}

function verifica(usaAjax, bolExecuta)
{
	//verifica se os campos foram preenchidos corretamente
	if(document.f_scart.cep1.value == "" || document.f_scart.cep1.value.length < 5)
	{
		alert('Digite os 5 digítos do CEP.');
		document.f_scart.cep1.focus(); 
		segue = 2;
	}
	else if(document.f_scart.cep2.value == "" || document.f_scart.cep2.value.length < 3)
	{
		alert('Digite os 3 digítos do CEP.');
		document.f_scart.cep2.focus(); 
		segue = 2;
	}
	else
	{
		segue = 1;
	}
	
	if( usaAjax == true )
	{
			
		//se foram preenchidos de modo correto segue para o ajax
		if(segue == 1)
		{
			cep	=	document.f_scart.cep1.value + '-'+ document.f_scart.cep2.value;
			mostra_local = 1;
			
			//local do frete
			var waitFunction = function(status) 
			{ 
				//mostra quando estiver carregando
				document.getElementById('status').innerHTML=status; 
			};
			var loadFunction = function(returnvalue) 
			{ 
				//existe mostra valor do frete
				if(returnvalue == 'notlocalidade')
				{
					  document.getElementById('descCep').style.display = 'none'; 
					  document.getElementById('cep1').style.display = 'none'; 
					  document.getElementById('cep2').style.display = 'none'; 
					  document.getElementById('localidade').style.display = ''; 
					  document.getElementById('status').style.display = 'none';
				}
				if(returnvalue != 'notlocalidade')
				{
					  document.getElementById('status').innerHTML = ''; 
					  if(document.getElementById('localidade'))
					  {
					  	document.getElementById('localidade').style.display = 'none'; 
					  }
					  document.getElementById('cep1').style.display = ''; 
					  document.getElementById('cep2').style.display = ''; 
					  document.getElementById('localFrete').style.display = ''; 
					  document.getElementById('valorFrete').style.display = ''; 
					  document.getElementById('localFrete').innerHTML = 'Local do frete: '+returnvalue; 
				}
				else
				{
					  document.getElementById('localFrete').style.display = 'none'; 
					  document.getElementById('valorFrete').style.display = 'none'; 
					  document.getElementById('localFrete').innerHTML = ''; 
					  document.getElementById('valorFrete').innerHTML = ''; 
				}
		
			}
			var metodo = 'POST';
		
			var ajx = new ajax();
			ajx.setParams('cep',cep,'mostra_local',mostra_local);
			ajx.sendLoad('ajax_frete.php', waitFunction, loadFunction,metodo);
			
			//valor do frete
			cep	=	document.f_scart.cep1.value + '-'+ document.f_scart.cep2.value;
			mostra_valor = 1;
			var waitFunction = function(status) 
			{ 
				//mostra quando estiver carregando
				document.getElementById('status').innerHTML = status; 
			};
			var loadFunction = function(returnvalue) 
			{ 
				//existe mostra valor do frete
				if(returnvalue == 'notlocalidade')
				{
					  document.getElementById('descCep').style.display = 'none'; 
					  document.getElementById('cep1').style.display = 'none'; 
					  document.getElementById('cep2').style.display = 'none'; 
					  document.getElementById('localidade').style.display = ''; 
					  document.getElementById('status').style.display = 'none';
				}
				if(returnvalue != 'notlocalidade')
				{
					  document.getElementById('status').innerHTML = ''; 
					  if(document.getElementById('localidade'))
					  {
					  	document.getElementById('localidade').style.display = 'none'; 
					  }
					  document.getElementById('cep1').style.display = ''; 
					  document.getElementById('cep2').style.display = '';
					  document.getElementById('localFrete').style.display = ''; 
					  document.getElementById('valorFrete').style.display = ''; 
					  document.getElementById('valorFrete').style.bgcolor = "#414141"; 
					  var vlrFrete = parseFloat(returnvalue).format(2,",","");
					  document.getElementById('valorFrete').innerHTML = " Sedex:<strong>&nbsp; R$ "+vlrFrete+"</strong>";  
				}
				else
				{
					  document.getElementById('localFrete').style.display = 'none'; 
					  document.getElementById('valorFrete').style.display = 'none'; 
					  document.getElementById('localFrete').innerHTML = ''; 
					  document.getElementById('valorFrete').innerHTML = ''; 
				}
		
			}
			var metodo = 'POST';
		
			var ajx1 = new ajax();
			ajx1.setParams('cep',cep,'mostra_valor',mostra_valor);
			ajx1.sendLoad('ajax_frete.php', waitFunction, loadFunction,metodo);
			
			
			//valor da compra total
			cep	=	document.f_scart.cep1.value + '-'+ document.f_scart.cep2.value;
			mostraValorTotal = 1;
			valorSemFrete = valorTotalAVista;
			var waitFunction = function(status) 
			{ 
				//mostra quando estiver carregando
				document.getElementById('valorTotal').innerHTML = status; 
			};
			var loadFunction = function(returnvalue) 
			{ 
				//existe mostra o preo total
				if(returnvalue == 'notlocalidade')
				{
					  document.getElementById('descCep').style.display = 'none'; 
					  document.getElementById('cep1').style.display = 'none'; 
					  document.getElementById('cep2').style.display = 'none'; 
					  document.getElementById('localidade').style.display = ''; 
					  document.getElementById('status').style.display = 'none';
				}
				if(returnvalue != 'notlocalidade')
				{
					  document.getElementById('valorFrete').style.display = '';
					  document.getElementById('valorTotal').innerHTML = ''; 
					  document.getElementById('valorTotal').innerHTML = " R$ "+returnvalue;  
				}
				else
				{
					  document.getElementById('localFrete').style.display = 'none'; 
					  document.getElementById('valorFrete').style.display = 'none'; 
					  document.getElementById('localFrete').innerHTML = ''; 
					  document.getElementById('valorFrete').innerHTML = ''; 
				}
		
			}
			var metodo = 'POST';
		
			var ajx2 = new ajax();
			ajx2.setParams('cep',cep,'valorSemFrete',valorSemFrete,'mostraValorTotal',mostraValorTotal);
			ajx2.sendLoad('ajax_frete.php', waitFunction, loadFunction,metodo);
		}
		
		
		segue_localidade = 2;
		//verifica pela localidade o valor do frete
		if(document.f_scart.localidade.style.display == '')
		{
			segue_localidade = 1;
		}
		if(segue_localidade === '1')
		{
			//valor da compra total
			localidade	=	document.f_scart.localidade.value;
			mostraLocalidade = 1;
			var waitFunction = function(status) 
			{ 
				//mostra quando estiver carregando
				document.getElementById('valorTotal').innerHTML = status; 
			};
			var loadFunction = function(returnvalue) 
			{ 
				//existe mostra o preo total
				if(returnvalue)
				{
					  document.getElementById('valorFrete').style.display = '';
					  document.getElementById('valorTotal').innerHTML = ''; 
					  document.getElementById('valorTotal').innerHTML = " R$ "+returnvalue;  
				}
				else
				{
					  document.getElementById('localFrete').style.display = 'none'; 
					  document.getElementById('valorFrete').style.display = 'none'; 
					  document.getElementById('localFrete').innerHTML = ''; 
					  document.getElementById('valorFrete').innerHTML = ''; 
				}
		
			}
			var metodo = 'POST';
		
			var ajx3 = new ajax();
			ajx3.setParams('localidade',localidade,'mostraLocalidade',mostraLocalidade);
			ajx3.sendLoad('ajax_frete.php', waitFunction, loadFunction,metodo);	
		}
	}
	else
	{
		if( bolExecuta && segue == 1 )
			document.f_scart.submit();
	}
}

//submete form
function submitForm(strNome)
{
	document.getElementById(strNome).submit();
}

//atualiza o frete
function atualiza_frete(val, valorCarrinho)
{
	var vt;
	document.getElementById("valorFrete").innerHTML = "Valor do Frete: R$ "+(Number(val)).format(2,",",".");
	vt = Number(val) + Number(valorCarrinho);
  	document.getElementById("valorTotal").innerHTML = "R$ "+vt.format(2,",",".");
}

//limpa valor do frete
function reset_valor(valorCarrinho)
{
	document.getElementById("valorTotal").innerHTML = "R$ "+formataValorPreco(Number(valorCarrinho));
	document.getElementById("valorFrete").innerHTML = " Selecione ";
}
//submete form
function submitForm(strNome)
{
	document.getElementById(strNome).submit();
}

/*****************************************************
*	// Funções do carrinho de compras                *
******************************************************/


/*****************************************************
*	Funções do fale conosco                          *
******************************************************/

function verificaFale()
{
	erro = 0;
	nome	    =	document.getElementById("nomeFale");
	email	    =	document.getElementById("emailFale");
	telefone    =   document.getElementById("telefoneFale");
	cidade	    =	document.getElementById("cidadeFale");
	estado	    =	document.getElementById("estadoFale");
	mensagem    =	document.getElementById("mensagemFale");
	verificacao	=	document.getElementById("gd_string");
	if(nome.value == ''){
		alert('Informe seu nome.');
		nome.focus();
		erro = 1;
		return false;
	}
	if(email.value == '' || email.value.indexOf('.') == -1 || email.value.indexOf('@') == -1 || email.value.length < 6 ){
		alert('Informe seu endereço de e-mail.');
		email.focus();
		erro = 1;
		return false;
	}
	if(estado.value == 0){
		alert('Selecione seu estado.');
		estado.focus();
		erro = 1;
		return false;
	}
	if(cidade.value == ''){
		alert('Informe sua cidade.');
		cidade.focus();
		erro = 1;
		return false;
	}
	if(mensagem.value == ''){
		alert('Campo Mensagem não pode ser enviado em branco.');
		mensagem.focus();
		erro = 1;
		return false;
	}
	if(verificacao.value == ''){
		alert('Campo Verificação não pode ser enviado em branco.');
		verificacao.focus();
		erro = 1;
		return false;
	}
	//alert(erro);
	if(erro==0){
		 // liberar soh quando funcionar o ajax
	    // passou na validação
		//alert("passou");
		var waitFunction = function(status) 
		{ 
			//mostra quando estiver carregando
			switch (status) {
				case 'inicializando' : ;
				case 'carregando...' : ;
				case 'carregado' : ;
				case 'interação' :
					mensagemAjax = "Aguarde...";
					break;				
				case 'completo' :
					mensagemAjax = "Sucesso!";
					break;
				default : mensagemAjax = "Aguarde...";
			}
			document.getElementById('statusFale').innerHTML=mensagemAjax; 
		};
		var loadFunction = function(returnvalue) 
		{ 
			switch(returnvalue) {
			
				case '2': 
					mensagemAjax = "Falha no envio da mensagem";
					break;
				case '1':
					mensagemAjax = "Verificação Incorreta";
					break;
				case '3':
					nome.value = "";
					email.value = "";
					telefone.value = "";
					estado.value = "";
					cidade.value = "";
					mensagem.value = "";
					verificacao.value = "";
					mensagemAjax = "Mensagem enviada com Sucesso!";
					break;
			}
			document.getElementById('statusFale').innerHTML= '<strong>'+mensagemAjax+'</strong>';	
	
		}
		var metodo = 'POST';
	
		var ajx4 = new ajax();
		ajx4.setParams('ajax','1','nomeFale',nome.value,'emailFale',email.value, 'telefoneFale', telefone.value, 'estadoFale',estado.value,'cidadeFale',cidade.value,'mensagemFale',mensagem.value,'gd_string',verificacao.value);
		ajx4.sendLoad('includes/ajax/fale-conosco-ajax.php', waitFunction, loadFunction,metodo);
	} 
	else 
	{ 
		return false; 
	}
}

//valida o form sem alert
//somente mensagem
function carregaValidacoesFaleConosco()
{
	$.validator.setDefaults({
		submitHandler: function() { 
			verificaFale(); 
		}
	});
	
	$().ready(function() {
		//carrega as validações do form
		$("#frmFaleConosco").validate({
			rules: {
				nomeFale: "required",
				emailFale: "required email",
				telefoneFale: "required",
				cidadeFale: "required",
				estadoFale: "required",
				mensagemFale: "required",
				gd_string: "required"
			},
			messages: {
				nomeFale: "Digite seu nome.",
				emailFale: "Digite corretamente seu e-mail.",
				telefoneFale: "Digite seu telefone.",
				cidadeFale: "Digite sua cidade.",
				estadoFale: "Selecione seu estado.",
				mensagemFale: "Digite sua mensagem.",
				gd_string: "Digite a verificação."
			}
		});
		
		//coloca o foco no primeiro campo
		$("#nomeFale").focus();
	});	
}
/*****************************************************
*	// Funções do fale conosco                       *
******************************************************/

/*****************************************************
*	Funções do login                                 *
******************************************************/
//variáveis globais usadas
var strEndereco   = new String(window.location);
var arrTemp       = strEndereco.split("/");
var strPagina     = null;
var strPaginaEnviar = null;

//localhost
if( arrTemp[3] == 'bazar-navegantes' )
{
	strPagina = arrTemp[4];
}
else
{
	strPagina = arrTemp[3];
}

//valida o form sem alert
//somente mensagem
//essa função é usada para o login e para a central do cliente
//a única diferença é a variável global strPaginaEnviar que delega para onde será remetida a página 
//por javascript
function carregaValidacoesLogin(ret)
{
	
	
	$().ready(function() {
		$.validator.setDefaults({
			submitHandler: function() { 
				//seta a página para ser remetida por javascript
				if( strPagina.indexOf('login.php') != -1 )
					strPaginaEnviar = 'entrega.php';
				else if( strPagina.indexOf('central-cliente.php') != -1 )
				   {
					 if(ret.length==0)  
    					strPaginaEnviar = 'acompanha_pedido.php';
					else 
    					strPaginaEnviar = ret;
}
				
				
				
				verificaLogin(); 	
			}
		});
		
		//carrega as validações do form
		$("#frmLogin").validate({
			rules: {
				email: "required email",
				senha: {
						  required: true,
						  minLength: 6					
					   }
			},
			messages: {
				email: "Digite corretamente seu e-mail.",
				senha: "Digite sua senha com 6 ou mais caracteres."
			}
		});
		
		//coloca o foco no primeiro campo
		$("#email").focus();
	});	
}

function carregaValidacaoNaoCadastrado()
{
	$("#frmNovoCadastro").validate({
			rules: {
				cep1: {
						  required: true,
						  minLength: 5					
					   },
				cep2: {
						  required: true,
						  minLength: 3					
					   }
			},
			messages: {
				cep1: "Digite os primeiros 5 dígitos do CEP.",
				cep2: "Digite os 3 últimos dígitos do CEP."
			}
		});
}

function verificaLogin()
{
	
	
	//verifica se os campos foram preenchidos corretamente
	if(document.frmLogin.email.value == "" )
	{
		alert("Digite seu e-mail.");
		document.frmLogin.email.focus(); 
		segue = 2;
	}
	else if(document.frmLogin.email.value.indexOf('@')==-1 || document.frmLogin.email.value.indexOf('.')==-1) 
	{ 
		alert("E-mail inválido. Verifique se no esqueceu '.' e '@' no seu e-mail."); 
		document.frmLogin.email.focus(); 
		segue = 2; 
	} 
	else if(document.frmLogin.senha.value == "")
	{
		alert("Digite sua senha.")
		document.frmLogin.senha.focus(); 
		segue = 2;
	}
	else if(document.frmLogin.senha.value.length < 6 || document.frmLogin.senha.value.length > 10)
	{
		alert("Senha inválida. A senha deve ter de 6 a 10 caracteres.");
		document.frmLogin.senha.focus(); 
		segue = 2;
	}
	else
	{
		segue = 1;
	}
	
	//se foram preenchidos de modo correto segue para o ajax
	if(segue == 1)
	{
		email_form	=	document.frmLogin.email.value;
		senha_form	=	document.frmLogin.senha.value;
		var waitFunction = function(status) 
		{ 
			//mostra quando estiver carregando
			document.getElementById('status').innerHTML=status; 
		};
		var loadFunction = function(returnvalue) 
		{ 
			
			//alert("valor retornado= "+returnvalue);
			
			//existe manda para página de entrega
			if(returnvalue == 1)
			{
				  
				  //alert("entrou");
				  
				  //document.getElementById('status').innerHTML = ''; 
				  window.location = strPaginaEnviar;

			}
			else if(returnvalue == 2)
			{
				   //document.getElementById('status').innerHTML = "O e-mail e senha não conferem.";
				   alert("O e-mail e senha não conferem.");
			}
			else if(returnvalue == 3)
			{
				   //document.getElementById('status').innerHTML = "O e-mail é inválido.";
				   alert("O e-mail é inválido.");
			}
			else if(returnvalue == 4)
			{
				   //document.getElementById('status').innerHTML = "A senha deve ter entre 6 e 10 caracteres.";
				   alert("A senha deve ter entre 6 e 10 caracteres.");
			}
			else if(returnvalue == 5)
			{
				   //document.getElementById('status').innerHTML = "O cliente não está ativo.";
				   alert("O cliente não está ativo.");
			}
			else 
			{
				   //document.getElementById('status').innerHTML = '';
			}
	
		}
		var metodo = 'POST';
	
		var ajx = new ajax();
		ajx.setParams('email',email_form,'senha',senha_form);
		ajx.sendLoad('includes/ajax/login-ajax.php', waitFunction, loadFunction,metodo);
	}
}

function esqueciSenha()
{
	var erro = 0;
	var email	=	document.getElementById("email");
	
	if(email.value == '' || email.value == 'Seu E-mail' )
	{
		alert('Informe seu endereço de e-mail.');
		email.focus();
		erro = 1;
		return false;
	}
	else if( document.frmLogin.email.value.indexOf('@')==-1 || document.frmLogin.email.value.indexOf('.')==-1 )
	{
		alert('E-mail inválido. Verifique se esqueceu @ ou . no endereço de e-mail');
		email.focus();
		erro = 1;
		return false;
	}
	
	//alert(erro);
	if(erro==0)
	{
		// liberar soh quando funcionar o ajax
		// passou na validação
		var waitFunctionLogin = function(status) 
		{ 
			//mostra quando estiver carregando
			switch (status) {
				case 'inicializando' : ;
				case 'carregando...' : ;
				case 'carregado' : ;
				case 'interação' :
					mensagem = "Aguarde, verificando senha...";
					break;				
				case 'completo' :
					mensagem = "Completo";
					break;
				default : mensagem = "Aguarde...";
			}
			document.getElementById('status').innerHTML=mensagem; 
		};
		var loadFunctionLogin = function(returnvalue) 
		{ 
			switch(returnvalue) {
				case '1':
					mensagem = "Erro";
					break;
				case '2': 
					mensagem = "Informação de login inexistente"
					break;
				case '3': 
					mensagem = "E-mail inválido";
					break;
				case '4':
					mensagem = "Verificação inválida";
					break;
				case '5':
					mensagem = "Falha no envio da mensagem";
					break
				case '0':
					mensagem = "Senha enviada com sucesso para "+email.value;
					break;
			}
			alert(mensagem);
		}
		var metodo = 'POST';
	
		var ajx8 = new ajax();
		ajx8.setParams('ajax','1','email',email.value);
		ajx8.sendLoad('esqueci_minha_senha_ajax.php', waitFunctionLogin, loadFunctionLogin,metodo);
	} 
	else 
	{ 
		return false; 
	}	
}
/*****************************************************
*	// Funções do login                              *
******************************************************/

/*****************************************************
*	Funções do cadastro                              *
******************************************************/
//valida o form sem alert
//somente mensagem

function carregaValidacoesCadastro()
{
	$.validator.setDefaults({
		submitHandler: function() { 
			var bolEnviaForm = validaFormulario();
			if( bolEnviaForm )
			{
				$("#frmCadastro").validate();
				$("#frmCadastro").submit();
			}
		}
	});
	
	$().ready(function() {
		//carrega as validações do form
		$("#frmCadastro").validate({
			rules: {
				nome: { 
						required: true,
					 	minLength: 4
			          },
				email: "required email",
				endereco: "required",
				numero: "required",
				bairro: "required",
				cidade: "required",
				estado: "required",
				pais: "required",
     			cep_1: { 
						required: true,
					 	minLength: 5
			          },
				cep_2: { 
						required: true,
					 	minLength: 3
			          },
				ddd_tel: { 
							required: true,
						 	minLength: 2
							},
				telefone: { 
							required: true,
						 	maxLength: 10							
				         },
				ddd_cel: { 
							required: true,
						 	minLength: 2
				         },
				celular: { 
							required: true,
						 	maxLength: 10							
				         },
				sexo: "required",
				data_nasc: {
								required: "#pessoa1:checked",
								minLength: 10						
						   },
				rg: {
					  	required: "#pessoa1:checked",
					  	minLength: 2						
					  },
				cpf: {
					  	required: "#pessoa1:checked",
					  	minLength: 12						
					  },	
				cnpj: {
					  	required: "#pessoa2:checked",
					  	minLength: 10						
					  },	
				inscricao: {
					required: "#pessoa2:checked",
					minLength: 4	
						   },
				confirma: {
					        required: "#senha:filled",
					   		equalTo: "#senha"
					      }
					   
			},
			messages: {
				nome: "Digite seu nome.",
				email: "Digite corretamente seu email.",
				endereco: "Digite seu endereço.",
				numero: "Digite seu número.",
				bairro: "Digite seu bairro.",
				cidade: "Digite sua cidade.",
				estado: "Selecione seu estado.",
				pais: "Digite seu país.",
				cep_1: "Digite os cinco primeiros números do CEP.",
				cep_2: "Digite os três últimos números do CEP.",
				ddd_tel: "Digite o número ddd do telefone.",
				telefone: "Digite o número do telefone.",
				ddd_cel: "Digite número ddd do celular.",
				celular: "Digite o número do celular.",
				profissao: "Digite a profissão.",
				sexo: "Selecione o sexo.",
				pessoa1: "Selecione o tipo de pessoa.",
				data_nasc: "Digite a sua data de nascimento.",
				rg: "Digite o seu RG.",
				cpf: "Digite os 11 dígitos do CPF.",
				cnpj: "Digite o CNPJ.",
				inscricao: "Digite a inscrição.",
				confirma: "Senha e confirmação de senha diferentes."
				
			}
		});
		
		//coloca o foco no primeiro campo
		$("#nome").focus();
	});	
}

function validaFormulario()
{
	if(document.frmCadastro.nome.value == '')
	{
		alert('Nome inválido.');
		document.frmCadastro.nome.focus();
		return false;
	}
	if(document.frmCadastro.email.value == '' || document.frmCadastro.email.value.indexOf('@') == -1 || document.frmCadastro.email.value.indexOf('.') == -1 )
	{
		alert('E-mail inválido.');
		document.frmCadastro.email.focus();
		return false;
	}
	if(document.frmCadastro.cep1.value == '' || document.frmCadastro.cep1.value.length < 5 || document.frmCadastro.cep2.value == '' || document.frmCadastro.cep2.value.length < 3)
	{
		alert('CEP inválido.');
		document.frmCadastro.cep1.focus();
		return false;
	}
	if(document.frmCadastro.endereco.value == '')
	{
		alert('Endereço inválido.');
		document.frmCadastro.endereco.focus();
		return false;
	}
	if(document.frmCadastro.numero.value == '')
	{
		alert('Número inválido.');
		document.frmCadastro.numero.focus();
		return false;
	}
    if(document.frmCadastro.bairro.value == '')
	{
		alert('Bairro inválido.');
		document.frmCadastro.bairro.focus();
		return false;
	}
	if(document.frmCadastro.cidade.value == '')
	{
		alert('Cidade inválida.');
		document.frmCadastro.cidade.focus();
		return false;
	}
	if(document.frmCadastro.estado.value == '')
	{
		alert('Estado inválido.');
		document.frmCadastro.estado.focus();
		return false;
	}
	if(document.frmCadastro.pais.value == '')
	{
		alert('País inválido.');
		document.frmCadastro.pais.focus();
		return false;
	}
	if(document.frmCadastro.residencial.value == '' && document.frmCadastro.celular.value == '')
	{
		alert('Informe um telefone para contato.')
		return false;
	}
	if(document.frmCadastro.residencial.value != '')
	{
		if(document.frmCadastro.ddd_res.value == '')
		{
			alert('Informe o DDD de seu telefone residencial');
			document.frmCadastro.ddd_res.focus();
			return false;
		}
	}
	if(document.frmCadastro.celular.value != '')
	{
		if(document.frmCadastro.ddd_cel.value == '')
		{
			alert('Informe o DDD de seu telefone celular');
			document.frmCadastro.ddd_cel.focus();
			return false;
		}
	}
	if( !document.frmCadastro.tipoPessoa[0].checked && !document.frmCadastro.tipoPessoa[1].checked )
	{
		alert('Selecione o tipo de pessoa.');
		return false;
	}
	if( document.frmCadastro.tipoPessoa[0].checked )
	{
		if( document.frmCadastro.data_nasc.value == '' || document.frmCadastro.data_nasc.value.length != 10 )
		{ 
			alert('Data de Nascimento inválido.');
			document.frmCadastro.data_nasc.focus();
			return false;
		}
		if( document.frmCadastro.rg.value == '' ) 
		{
			alert('RG inválido.');
			document.frmCadastro.rg.focus();
			return false;
		}
		if( document.frmCadastro.cpf1.value == '' || document.frmCadastro.cpf1.value.length < 9 || document.frmCadastro.cpf2.value == '' || document.frmCadastro.cpf2.value.length < 2 ) 
		{
			alert('CPF inválido.');
			document.frmCadastro.cpf1.focus();
			return false;
		}
	}
	if( document.frmCadastro.tipoPessoa[1].checked )
	{
		if( document.frmCadastro.cnpj.value == '' ||  document.frmCadastro.cnpj.value.length < 18 )
		{ 
			alert('CNPJ inválido.');
			document.frmCadastro.cnpj.focus();
			return false;
		}
		if( document.frmCadastro.inscricao.value == '' ) 
		{
			alert('Inscrição inválida.');
			document.frmCadastro.inscricao.focus();
			return false;
		}
	}

	return true;
}

function addEvent(obj, evt, func) {
  if (obj.attachEvent) {
    return obj.attachEvent(("on"+evt), func);
  } else if (obj.addEventListener) {
    obj.addEventListener(evt, func, true);
    return true;
  }
  return false;
}

function XMLHTTPRequest() {
  try {
    return new XMLHttpRequest(); // FF, Safari, Konqueror, Opera, ...
  } catch(ee) {
    try {
      return new ActiveXObject("Msxml2.XMLHTTP"); // activeX (IE5.5+/MSXML2+)
    } catch(e) {
      try {
        return new ActiveXObject("Microsoft.XMLHTTP"); // activeX (IE5+/MSXML1)
      } catch(E) {
        return false; // doesn't support
      }
    }
  }
}

function buscarEndereco(op) {
    if(op==1)
	{
			var campos = {
			  validcep: document.getElementById("validcep"),
			  cep1: document.getElementById("cep_1"),
			  cep2: document.getElementById("cep_2"),
			  endereco: document.getElementById("endereco"),
			  numero: document.getElementById("numero"),
			  bairro: document.getElementById("bairro"),
			  cidade: document.getElementById("cidade"),
			  estado: document.getElementById("estado")
			};
	    }
		else     if(op==2)
        {
			var campos = {
			  validcep: document.getElementById("validcep"),
			  cep1: document.getElementById("cep_12"),
			  cep2: document.getElementById("cep_22"),
			  endereco: document.getElementById("endereco2"),
			  numero: document.getElementById("numero2"),
			  bairro: document.getElementById("bairro2"),
			  cidade: document.getElementById("cidade2"),
			  estado: document.getElementById("estado2")
			};		
		}
        if(op==3)
        {
              var campos = {
			  validcep: document.getElementById("validcep"),
			  cep1: document.getElementById("cep_13"),
			  cep2: document.getElementById("cep_23"),
			  endereco: document.getElementById("endereco3"),
			  numero: document.getElementById("numero3"),
			  bairro: document.getElementById("bairro3"),
			  cidade: document.getElementById("cidade3"),
			  estado: document.getElementById("estado3")
			};	       
	     }
var ajax = XMLHTTPRequest();
  ajax.open("GET", ("includes/ajax/cep-ajax.php?cep="+campos.cep1.value+"-"+campos.cep2.value), true);
  ajax.onreadystatechange = function() {
  if (ajax.readyState == 1) {
  campos.endereco.disabled = true;
  campos.endereco.value = "carregando...";
  campos.bairro.disabled = true;
  campos.cidade.disabled = true;
  campos.bairro.value = "carregando...";
  campos.estado.disabled = true;
  campos.cidade.value = "carregando...";
  } else if (ajax.readyState == 4) {
  if(ajax.responseText == false){
    campos.validcep.innerHTML = "Cep inválido!!!";
    campos.endereco.disabled = false;
    campos.endereco.value = "";
    campos.bairro.disabled = false;
    campos.cidade.disabled = false;
    campos.bairro.value = "";
    campos.estado.disabled = false;
    campos.cidade.value = "";
  }else{
    campos.validcep.innerHTML = "";
    var r = ajax.responseText, i, endereco, numero, bairro, cidade, estado;

    endereco = r.substring(0, (i = r.indexOf(':')));
    campos.endereco.disabled = false;
    campos.endereco.value = unescape(endereco.replace(/\+/g," "));
    r = r.substring(++i);
    bairro = r.substring(0, (i = r.indexOf(':')));
    campos.bairro.disabled = false;
    campos.bairro.value = unescape(bairro.replace(/\+/g," "));
    r = r.substring(++i);
    cidade = r.substring(0, (i = r.indexOf(':')));
    campos.cidade.disabled = false;
    campos.cidade.value = unescape(cidade.replace(/\+/g," "));
    r = r.substring(++i);
    estado = r.substring(0, (i = r.indexOf(';')));
    campos.estado.disabled = false;
    campos.estado.value = estado;
    
    i = campos.estado.options.length;
    while (i--) {
      if (campos.estado.options[i].getAttribute("value") == estado) {
      break;
      }
    }
    campos.estado.selectedIndex = i;
    
  }
  }
};
ajax.send(null);
}

function buscarEnderecoEntrega(op) {
if(op==1)
{
var campos = {
  validcep: document.getElementById("validcep"),
  cep1: document.getElementById("cep_1"),
  cep2: document.getElementById("cep_2"),
  endereco: document.getElementById("endereco"),
  numero: document.getElementById("num"),
  bairro: document.getElementById("bairro"),
  cidade: document.getElementById("cidade"),
  estado: document.getElementById("estado")
};
}
else
if(op==2)
{
var campos = {
  validcep: document.getElementById("validcep"),
  cep1: document.getElementById("cep_12"),
  cep2: document.getElementById("cep_22"),
  endereco: document.getElementById("endereco2"),
  numero: document.getElementById("num2"),
  bairro: document.getElementById("bairro2"),
  cidade: document.getElementById("cidade2"),
  estado: document.getElementById("estado2")
};	
}else if(op==3)
{
var campos = {
  validcep: document.getElementById("validcep"),
  cep1: document.getElementById("cep_13"),
  cep2: document.getElementById("cep_23"),
  endereco: document.getElementById("endereco3"),
  numero: document.getElementById("num3"),
  bairro: document.getElementById("bairro3"),
  cidade: document.getElementById("cidade3"),
  estado: document.getElementById("estado3")
};	
}
var ajax = XMLHTTPRequest();
  ajax.open("GET", "includes/ajax/cep-ajax.php?cep="+campos.cep1.value+"-"+campos.cep2.value, true);
  ajax.onreadystatechange = function() {
  if (ajax.readyState == 1) {
  campos.endereco.disabled = true;
  campos.endereco.value = "carregando...";
  campos.bairro.disabled = true;
  campos.cidade.disabled = true;
  campos.bairro.value = "carregando...";
  campos.estado.disabled = true;
  campos.cidade.value = "carregando...";
  } else if (ajax.readyState == 4) {
  if(ajax.responseText == false){
    campos.validcep.innerHTML = "Cep inválido!!!";
    campos.endereco.disabled = false;
    campos.endereco.value = "";
    campos.bairro.disabled = false;
    campos.cidade.disabled = false;
    campos.bairro.value = "";
    campos.estado.disabled = false;
    campos.cidade.value = "";
  }else{
    campos.validcep.innerHTML = "";
    var r = ajax.responseText, i, endereco, numero, bairro, cidade, estado;
    endereco = r.substring(0, (i = r.indexOf(':')));
    campos.endereco.disabled = false;
    campos.endereco.value = unescape(endereco.replace(/\+/g," "));
    r = r.substring(++i);
    bairro = r.substring(0, (i = r.indexOf(':')));
    campos.bairro.disabled = false;
    campos.bairro.value = unescape(bairro.replace(/\+/g," "));
    r = r.substring(++i);
    cidade = r.substring(0, (i = r.indexOf(':')));
    campos.cidade.disabled = false;
    campos.cidade.value = unescape(cidade.replace(/\+/g," "));
    r = r.substring(++i);
    estado = r.substring(0, (i = r.indexOf(';')));
    campos.estado.disabled = false;
    i = campos.estado.options.length;
    while (i--) {
      if (campos.estado.options[i].getAttribute("value") == estado) {
      break;
      }
    }
    campos.estado.selectedIndex = i;
  }
  }

};
ajax.send(null);
}

function carregaCepAjax(){
	window.addEvent(
	  window,
	  "load",
	  function() {window.addEvent(document.getElementById("cep_2"), "blur",  function() { buscarEndereco(1);}  );
 if(document.getElementById("cep_22"))	window.addEvent(document.getElementById("cep_22"), "blur", function() { buscarEndereco(2);} );
if(document.getElementById("cep_23")) window.addEvent(document.getElementById("cep_23"), "blur",  function() {buscarEndereco(3);} );	
	  
	  }
	);
	
	$("#cep_1").focus(
						function()
						{ 
							this.value = ''; 
						}
					);
					
	$("#cep_1").keyup(
							function()
							{ 
								if( $("#cep_1").val().length == 5 )
								{ 
									$("#cep_2").focus();
								} 
							}
						);
	
	$("#cep_12").focus(
						function()
						{ 
							this.value = ''; 
						}
					);
					
	$("#cep_12").keyup(
							function()
							{ 
								if( $("#cep_12").val().length == 5 )
								{ 
									$("#cep_22").focus();
								} 
							}
						);	
	$("#cep_13").focus(
						function()
						{ 
							this.value = ''; 
						}
					);
					
	$("#cep_13").keyup(
							function()
							{ 
								if( $("#cep_13").val().length == 5 )
								{ 
									$("#cep_23").focus();
								} 
							}
						);		
	
	
}

function carregaCepEntregaAjax(){
	window.addEvent(
	  window,
	  "load",
	  function() {window.addEvent(document.getElementById("cep_2"), "blur",  function() { buscarEnderecoEntrega(1);}  );
 if(document.getElementById("cep_22"))	window.addEvent(document.getElementById("cep_22"), "blur", function() { buscarEnderecoEntrega(2);} );
if(document.getElementById("cep_23")) window.addEvent(document.getElementById("cep_23"), "blur",  function() {buscarEnderecoEntrega(3);} );	
	  
	  }
	);	
}



function abreConf_detProd(id){
	var doc = document.getElementById(id);		
	if(doc.className == "confDet_carrinho")
		doc.className = "confDetAb_carrinho";
	else
		doc.className = "confDet_carrinho";
}
function AbreDescricao()
{
	if (document.getElementById("abre_descricao").style.display == 'none'){
		document.getElementById("abre_descricao").style.display = 'block';
	}
	else {
		document.getElementById("abre_descricao").style.display = 'none';
	}
}

/*****************************************************
*	// Funções do cadastro                           *
******************************************************/

/*****************************************************
*	Funções do entrega                               *
******************************************************/
//valida o form sem alert
//somente mensagem
function carregaValidacoesEntrega()
{
	$().ready(function() {
		//carrega as validações do form
		$("#formEntrega").validate({
			rules: {
				cep1: {
					  	required:true,
					  	minLength:5 
					  },
				cep2: {
					   	required:true,
					  	minLength:3
					  },
				endereco: "required",
				numero: "required",
				cidade: "required",
				estado: "required",
				bairro: "required"
			},
			messages: {
				cep1: "Digite os cinco primeiros números do CEP.",
				cep2: "Digite os três últimos números do CEP.",
				endereco: "Digite seu endereço.",
				numero: "Digite seu número.",
				cidade: "Digite sua cidade.",
				estado: "Selecione seu estado.",
				bairro: "Digite seu bairro."
			}
		});
	});	
}

//entrega trocar as class
function trocaClassEntrega(strId)
{
	//ao executar tira a class ativo
	$("#entregaOutro").removeClass('endereco ativo');
	$("#entregaMesmo").removeClass('endereco ativo');
	
	//verifica qual endereço está ativo
	if( $("#"+strId).attr("id") == 'entregaMesmo' )
	{
		trocaClass(strId, 'endereco ativo');
		trocaClass('entregaOutro', 'endereco');
	}
	else
	{
		trocaClass(strId, 'endereco ativo');
		trocaClass('entregaMesmo', 'endereco');
	}
}

/*****************************************************
*	// Funções do entrega                            *
******************************************************/
function formataValor(num) {
	var strn = eval(Math.round(num*100)/100).toString().replace('.',',');
	var ind = strn.lastIndexOf(',')+1;
	var cents = '';
	var final2 = '';
	if (ind > 0) {
		final2 = strn.substr(ind,strn.length);
	}
	if (final2.length == 0) {
		cents = ',00';		
	}
	if (final2.length == 1) {
		cents = '0';
	}
	var ret = strn+''+cents;
	return ret;
}

//Função do financiamento aymoré
function abreSimFinanciamentoABN()
{
	var preco  = formataValor(valorProduto);
	var url    = endereco+preco;
	var wleft  = (screen.width - 500) / 2; 
	var wtop   = (screen.height - 300) / 5; 
	var janela = window.open(url,'janela','width=500,height=500,toolbar=no,copyhistory=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=no,left='+wleft+',top='+wtop);
	janela.focus();
}

function MM_openBrWindow(theURL,winName,features) 
{ //v2.0
  window.open(theURL,winName,features);
}

function limpar( id, valor )
{
	var obPadrao = document.getElementById(id);
	if( obPadrao.value == valor )
	{
		obPadrao.value = '';
	}
}

function completar( id, valor )
{
	var obPadrao = document.getElementById(id);
	if( obPadrao.value == '' )
	{
		obPadrao.value = valor;
	}
}
