

//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');
			$("#lnk_"+i).addClass('bt-menos');
			$("#lnk_"+i).attr('title', 'Ocultar Detalhes');
			$("#div_"+i).show(2000);
		}
		else
		{
			$("#lnk_"+i).removeClass('bt-menos');
			$("#lnk_"+i).addClass('bt-mais');
			$("#lnk_"+i).attr('title', '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").keydown(
							function()
							{
								if( $("#cep1").val().length == 5 )
								{
									$("#cep2").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");

	//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 valida_cep12()
{
	//alert("teste");
	//verifica se os campos foram preenchidos corretamente
	if(document.getElementById('cep1').value == "" || document.getElementById('cep1').value.length < 5)
	{
		alert('Digite os 5 digítos do CEP.');
		document.getElementById('cep1').focus();
		segue = 2;
	}
	else if(document.getElementById('cep2').value == "" || document.getElementById('cep2').value.length < 3)
	{
		alert('Digite os 3 digítos do CEP.');
		document.getElementById('cep2').focus();
		segue = 2;
	}
	else
	{
		segue = 1;
	}

	if(segue == 1)
	{
		document.getElementById('f_scart').submit();

	}
}*/

function verifica()
{
	var url = 'includes/ajax/frete-ajax.php';
	//verifica se os campos foram preenchidos corretamente
	if(document.getElementById('cep1').value == "" || document.getElementById('cep1').value.length < 5)
	{
		alert('Digite os 5 digítos do CEP.');
		document.getElementById('cep1').focus();
		segue = 2;
	}
	else if(document.getElementById('cep2').value == "" || document.getElementById('cep2').value.length < 3)
	{
		alert('Digite os 3 digítos do CEP.');
		document.getElementById('cep2').focus();
		segue = 2;
	}
	else
	{
		segue = 1;
	}

	var cep	=	document.getElementById('cep1').value + '-'+ document.getElementById('cep2').value;
	//se foram preenchidos de modo correto segue para o ajax
	if(segue == 1)
	{
		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+'&nbsp;';
			}
			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(url, waitFunction, loadFunction,metodo);

		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 = "&nbsp; R$ "+vlrFrete+"&nbsp;";
			}
			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(url, waitFunction, loadFunction,metodo);


		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+'&nbsp;';
			}
			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(url, waitFunction, loadFunction,metodo);
	}


	segue_localidade = 2;
	//verifica pela localidade o valor do frete
	if(document.getElementById('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+'&nbsp;';
			}
			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(url, 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;
	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;
				default:
				  mensagemAjax = "Ocorreu um erro ao enviar sua mensagem!"
				  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] == 'xispacar' )
{
	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()
{
	$().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 = 'meus-pedidos.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 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)
		{
			//existe manda para página 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&atilde;o conferem.";
			}
			else if(returnvalue == '3')
			{
				   document.getElementById('status').innerHTML = "O e-mail é inv&aacute;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&atilde;o est&aacute 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: {
						required: true,
					 	minLength: 9
			          },
				ddd_res: {
							required: "#celular:blank",
						 	minLength: 2
				         },
				residencial: {
							required: "#celular:blank"
				         },
				ddd_cel: {
							required: "#residencial:blank",
						 	minLength: 2
				         },
				celular: {
							required: "#residencial:blank"
				         },
				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"
					      },
				profissao: "required"

			},
			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: "Digite os oito 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 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.",
				profissao: "Digite a sua profissão."
			}
		});

		//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() {
var campos = {
  validcep: document.getElementById("validcep"),
  cep: document.getElementById("cep_1"),
  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", ("includes/ajax/cep-ajax.php?cep="+campos.cep.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() {
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")
};

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_1"), "blur", buscarEndereco);}
	);
}

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



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",
				num: "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.",
				num: "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;
	}
}

function mostrarDadosProduto(id)
{
  switch(id)
  {
    case 'menu-detalhe-texto':
      document.getElementById(id).style.display = '';
      document.getElementById('menu-especificacao-texto').style.display = 'none';
      document.getElementById('menu-opniao-texto').style.display = 'none';
      document.getElementById('menu-garantia-texto').style.display = 'none';
    break;
    case 'menu-especificacao-texto':
      document.getElementById('menu-detalhe-texto').style.display = 'none';
      document.getElementById(id).style.display = '';
      document.getElementById('menu-opniao-texto').style.display = 'none';
      document.getElementById('menu-garantia-texto').style.display = 'none';
    break;
    case 'menu-opniao-texto':
      document.getElementById('menu-detalhe-texto').style.display = 'none';
      document.getElementById('menu-especificacao-texto').style.display = 'none';
      document.getElementById(id).style.display = '';
      document.getElementById('menu-garantia-texto').style.display = 'none';
    break;
    case 'menu-garantia-texto':
      document.getElementById('menu-detalhe-texto').style.display = 'none';
      document.getElementById('menu-especificacao-texto').style.display = 'none';
      document.getElementById('menu-opniao-texto').style.display = 'none';
      document.getElementById(id).style.display = '';
    break;
  }
}

function faleConoscoRapido()
{
  var nome      = $('#txNomeFale').val();
  var email     = $('#txEmailFale').val();
  var descricao = $('#txDescricaoFale').val();
  var sucesso   = true;

  if( nome.length == 0 || nome == 'Nome' )
  {
    alert("Digite seu nome.")
    document.getElementById('txNomeFale').focus();
    sucesso = false;
  }
  else if( email.length == 0 || email.indexOf('.') == -1 || email.indexOf('@') == -1 || email == 'E-mail' )
  {
    alert("Digite seu e-mail corretamente.")
    document.getElementById('txEmailFale').focus();
    sucesso = false;
  }
  else if( descricao.length == 0 || descricao == 'Deixe seu recado aqui' )
  {
    alert("Digite seu recado.")
    document.getElementById('txDescricaoFale').focus();
    sucesso = false;
  }

  if( sucesso )
  {
    $.ajax({
     type: "POST",
     url: "includes/ajax/cadastro-rapido-faleconosco.php",
     data: "nome="+nome+"&email="+email+"&descricao="+descricao,
     success: function(msg){
       $('#mensagem-fale').html(msg);
     }
   });
  }
}

function cadastroRapido()
{
  var nome  = $('#txNomeCadastro').val();
  var email = $('#txEmailCadastro').val();
  var sucesso = true;

  if( nome.length == 0 || nome == 'Nome' )
  {
    alert("Digite seu nome.")
    document.getElementById('txNomeCadastro').focus();
    sucesso = false;
  }
  else if( email.length == 0 || email.indexOf('.') == -1 || email.indexOf('@') == -1 || email == 'E-mail' )
  {
    alert("Digite seu e-mail corretamente.")
    document.getElementById('txEmailCadastro').focus();
    sucesso = false;
  }

  if( sucesso )
  {
    $.ajax({
     type: "POST",
     url: "includes/ajax/cadastro-rapido-ajax.php",
     data: "nome="+nome+"&email="+email,
     success: function(msg){
       $('#mensagem').html(msg);
     }
   });
  }
}



// Início do código de Aumentar/ Diminuir a letra

// Para usar coloque o comando: "javascript:mudaTamanho('tag_ou_id_alvo', -1);" para diminuir
// e o comando "javascript:mudaTamanho('tag_ou_id_alvo', +1);" para aumentar

var tagAlvo = new Array('p'); //pega todas as tags p//

// Especificando os possíveis tamanhos de fontes, poderia ser: x-small, small...
var tamanhos = new Array( '9px','10px','11px','12px','13px','14px','15px' );
var tamanhoInicial = 2;

function mudaTamanho( idAlvo,acao ){
  if (!document.getElementById) return
  var selecionados = null,tamanho = tamanhoInicial,i,j,tagsAlvo;
  tamanho += acao;
  if ( tamanho < 0 ) tamanho = 0;
  if ( tamanho > 6 ) tamanho = 6;
  tamanhoInicial = tamanho;
  if ( !( selecionados = document.getElementById( idAlvo ) ) ) selecionados = document.getElementsByTagName( idAlvo )[ 0 ];

  selecionados.style.fontSize = tamanhos[ tamanho ];

  for ( i = 0; i < tagAlvo.length; i++ ){
    tagsAlvo = selecionados.getElementsByTagName( tagAlvo[ i ] );
    for ( j = 0; j < tagsAlvo.length; j++ ) tagsAlvo[ j ].style.fontSize = tamanhos[ tamanho ];
  }
}
// Fim do código de Aumentar/ Diminuir a letra
