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

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

//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.timeout      = true;
	this.executaFuncao();
}

//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('mostrar-detalhe replacent');
			$("#lnk_"+i).addClass('ocultrar-detalhe replacent');
			$("#lnk_"+i).attr('title', 'Ocultar Detalhes');
			$("#lnk_"+i).html('Ocultar Detalhes');
			$("#div_"+i).show(2000);		
		}
		else
		{
			$("#lnk_"+i).removeClass('ocultrar-detalhe replacent');
			$("#lnk_"+i).addClass('mostrar-detalhe replacent');
			$("#lnk_"+i).attr('title', 'Mostrar Detalhes');
			$("#lnk_"+i).html('Mostrar Detalhes');
			$("#div_"+i).hide(2000);	
		}
	}
}

//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()
{
	$("#cep1").focus(
						function()
						{ 
							this.value = ''; 
						}
					);
					
	$("#cep1").keyup(
							function()
							{ 
								if( $("#cep1").val().length == 5 )
								{ 
									$("#cep2").focus();
								} 
							}
						);
	
	//cria mascara para os campos de cep
	$("#cep1").mask("99999", {placeholder:""});
	$("#cep2").mask("999", {placeholder:""});
	
	//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", "javascript:void(0);");
	$("#calcular_frete").click(
								  function ()
								  {
								  	verifica();							  	
								  }
							  )
}

function verifica()
{
	//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;
	}
		
	//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('cep1').style.display = 'none'; 
				  document.getElementById('cep2').style.display = 'none'; 
				  document.getElementById('localidade').style.display = ''; 
				  document.getElementById('status').style.display = 'none';
				  document.getElementById('descCep').style.display = ''; 
				  document.getElementById('calcular_frete').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: </strong> '+returnvalue+'<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 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('cep1').style.display = 'none'; 
				  document.getElementById('cep2').style.display = 'none'; 
				  document.getElementById('localidade').style.display = ''; 
				  document.getElementById('status').style.display = 'none';
				  document.getElementById('descCep').style.display = ''; 
				  document.getElementById('calcular_frete').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,",","");
				 // alert(returnvalue+' - '+vlrFrete);
				  document.getElementById('valorFrete').innerHTML = " <strong>&nbsp;Valor 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('cep1').style.display = 'none'; 
				  document.getElementById('cep2').style.display = 'none'; 
				  document.getElementById('localidade').style.display = ''; 
				  document.getElementById('descCep').style.display = '';
				  document.getElementById('status').style.display = '';
				  document.getElementById('calcular_frete').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);	
	}

}

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

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


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

function verificaFale()
{
	erro = 0;
	//assunto	    =	document.getElementById("assuntoFale");
	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(assunto.value == 0){
		alert('Selecione um assunto.');
		assunto.focus();
		erro = 1;
		return false;
	}*/
	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' :
					mensagem = "Aguarde...";
					break;				
				case 'completo' :
					mensagem = "Sucesso!";
					break;
				default : mensagem = "Aguarde...";
			}
			document.getElementById('statusFale').innerHTML=mensagem; 
		};
		var loadFunction = function(returnvalue) 
		{ 
			switch(returnvalue) {
			
				case '2': 
					mensagem = "Falha no envio da mensagem";
					break;
				case '1':
					mensagem = "Verificação Incorreta";
					break;
				case '0':
					mensagem = "Mensagem enviada com Sucesso!";
					nome.value = "";
					email.value = "";
					assunto.value = 0;
					estado.value = 0;
					cidade.value = "";
					mensagem.value = "";
					verificacao.value = "";
					break;
			}
			document.getElementById('statusFale').innerHTML= '<strong>'+mensagem+'</strong>';	
	
		}
		var metodo = 'POST';
	
		var ajx4 = new ajax();
		ajx4.setParams('ajax','1','assuntoFale','Mensagem Fale-Conosco','nomeFale',nome.value,'emailFale',email.value, 'telefoneFale', telefone, 'estadoFale',estado.value,'cidadeFale',cidade.value,'mensagemFale',mensagem.value,'gd_string',verificacao.value);
		ajx4.sendLoad('fale_conosco_ajax.php', waitFunction, loadFunction,metodo);
	} 
	else 
	{ 
		return false; 
	}
}

//valida o form sem alert
//somente mensagem
function carregaValidacoesFaleConosco()
{
	$.validator.setDefaults({
		submitHandler: function() { 
			verificaFale(); 
			alert('Dados enviados com sucesso!');
			//$("#assuntoFale").val('');
			$("#nomeFale").val('');
			$("#emailFale").val('');
			$("#telefoneFale").val('');
			$("#cidadeFale").val('');
			$("#mensagemFale").val('');
			$("#gd_string").val('');
		}
	});
	
	$().ready(function() {
		//carrega as validações do form
		$("#frmFaleConosco").validate({
			rules: {
				//assuntoFale: "required",
				nomeFale: "required",
				emailFale: "required email",
				telefoneFale: "required",
				cidadeFale: "required",
				estadoFale: "required",
				mensagemFale: "required",
				gd_string: "required"
			},
			messages: {
				//assuntoFale: "Digite o assunto.",
				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] == 'itotal' )
{
	strPagina = arrTemp[4];
}
else
{
	strPagina = arrTemp[3];
}

//seta a página
if( strPagina == null )
{
	strPagina = arrTemp[4];
	
}
//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()
{
	$().ready(function() {
		$.validator.setDefaults({
			submitHandler: function() { 
				
				//seta a página para ser remetida por javascript
				if( strPagina.indexOf('login.php') != -1 )
					strPaginaEnviar = 'cadastro.php';
				else if( strPagina.indexOf('central-cliente.php') != -1 )
					strPaginaEnviar = 'acompanha_pedido.php';
				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 os 6 caracteres."
			}
		});
		
		//coloca o foco no primeiro campo
		$("#email").focus();
	});	
}

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) 
		{ 
			//existe manda para pgina de entrega
			if(returnvalue == '1')
			{
				  document.getElementById('status').innerHTML = ''; 
				  window.location = strPaginaEnviar;
			}
			else if(returnvalue == '2')
			{
				   document.getElementById('status').innerHTML = "O e-mail e senha não conferem.";
			}
			else if(returnvalue == '3')
			{
				   document.getElementById('status').innerHTML = "O e-mail é inválido.";
			}
			else if(returnvalue == '4')
			{
				   document.getElementById('status').innerHTML = "A senha deve ter entre 6 e 10 caracteres.";
			}
			else if(returnvalue == '5')
			{
				   document.getElementById('status').innerHTML = "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('ajax_login.php', waitFunction, loadFunction,metodo);
	}
}

function esqueciSenha()
{
	erro = 0;
	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",
				cep1: { 
						required: true,
					 	minLength: 5
			          },
				cep2: { 
						required: true,
					 	minLength: 3
			          },
				ddd_res: { 
							required: "#celular:blank",
						 	minLength: 2
				         },
				residencial: { 
							required: "#celular:blank"
				         },
				ddd_cel: { 
							required: "#residencial:blank",
						 	minLength: 2
				         },
				celular: { 
							required: "#residencial:blank"
				         },
				pessoa1: { 
							required: "#pessoa2:unchecked"
				         },
				sexo: { 
							required: "#pessoa1:checked"
				         },
				data_nasc: {
								required: "#pessoa1:checked",
								minLength: 10						
						   },
				rg: {
						required: "#pessoa1:checked"						
					},
				cpf: {
					  	required: "#pessoa1:checked",
					  	minLength: 12						
					  },
				pessoa2: { 
						 	required: "#pessoa1:unchecked"
				         },
				cnpj: {
				  	   	 required: "#pessoa2:checked",
				  	   	 minLength: 14						
				       },
				inscricao: {
					  	   	 required: "#pessoa2:checked"						
					       },
				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.",
				cep1: "Digite os cinco primeiros números do CEP.",
				cep2: "Digite os três últimos números do CEP.",
				ddd_res: "Digite o número ddd do telefone.",
				residencial: "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 sua data de nascimento.",
				rg: "Digite seu RG.",
				cpf: "Digite o seu CPF.",
				pessoa2: "Selecione o tipo de pessoa.",
				cnpj: "Digite o CNPJ.",
				inscricao: "Digite a inscrição estadual",
				confirma: "Senha e confirmação de senha diferentes."
			}
		});
		
		//coloca o foco no primeiro campo
		$("#nome").focus();
		
		//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");
	});	
}

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() {
var campos = {
  validcep: document.getElementById("validcep"),
  cep1: document.getElementById("cep1"),
  cep2: document.getElementById("cep2"),
  endereco: document.getElementById("endereco"),
  numero: document.getElementById("numero"),
  bairro: document.getElementById("bairro"),
  cidade: document.getElementById("cidade"),
  estado: document.getElementById("estado")
};

var ajax = XMLHTTPRequest();
  ajax.open("GET", ("ajax_cep.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("cep2"), "blur", buscarEndereco);}
	);
}

function mostraDados(idEsconder,idMostrar)
{
	if( idEsconder == 'fisica' )
	{
		//esconde
		for( i = 1; i <= 3; i++ )
		{
			document.getElementById(idEsconder+i).style.display = 'none';
		}
		
		//mostra
		for( i = 1; i <= 2; i++ )
		{
			document.getElementById(idMostrar+i).style.display = '';
		}
	}
	else if( idEsconder == 'juridica' )
	{
		//esconde
		for( i = 1; i <= 2; i++ )
		{
			document.getElementById(idEsconder+i).style.display = 'none';
		}
		
		//mostra
		for( i = 1; i <= 3; i++ )
		{
			document.getElementById(idMostrar+i).style.display = '';
		}
	}
}


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');
	}
}

function carregaCepEntregaAjax(){
	window.addEvent(
	  window,
	  "load",
	  function() {window.addEvent(document.getElementById("cep2"), "blur", buscarEnderecoEntrega);}
	);
}


function buscarEnderecoEntrega() {
var campos = {
  validcep: document.getElementById("validcep"),
  cep1: document.getElementById("cep1"),
  cep2: document.getElementById("cep2"),
  endereco: document.getElementById("endereco"),
  numero: document.getElementById("numero"),
  bairro: document.getElementById("bairro"),
  cidade: document.getElementById("cidade"),
  estado: document.getElementById("estado")
};

var ajax = XMLHTTPRequest();
  ajax.open("GET", ("ajax_cep.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);
}

/*****************************************************
*	// 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 abreDivFoto(id)
{
	var el = document.getElementById(id);
	var idpai = id.replace("inf_","");
	// var c = 0;

	if(navigator.appName.indexOf('Internet Explorer')>0)
	{
		var c = parseInt(el.style.height);
	}
	else
	{
		var c = parseInt(el.style.height) + 15;
	}

	//alert(el.style.top = getPosicaoElemento(idpai).top+" "+(getPosicaoElemento(idpai).top - c));
	el.style.left = getPosicaoElemento(idpai).left;
	el.style.top = getPosicaoElemento(idpai).top - c;
	el.style.display = "block";
}
function fechaDivFoto(id) {
	document.getElementById(id).style.display = "none";
}