//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');
			$("#div_"+i).show(2000);
		}
		else
		{
			$("#lnk_"+i).removeClass('bt-menos replacent');
			$("#lnk_"+i).addClass('bt-mais replacent');
			$("#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 verificaLogin()
{
		//verifica se os campos foram preenchidos corretamente
	if(document.getElementById('email').value == "")
	{
		alert("Digite seu e-mail.");
		document.getElementById('email').focus(); 
		segue = 2;
	}
	else if(document.getElementById('email').value.indexOf('@')==-1 || document.getElementById('email').value.indexOf('.')==-1) 
	{ 
		alert("E-mail inválido. Verifique se não esqueceu '.' e '@' no seu e-mail."); 
		document.getElementById('email').focus(); 
		segue = 2; 
	} 
	else if(document.getElementById('senha').value == "")
	{
		alert("Digite sua senha.")
		document.getElementById('senha').focus(); 
		segue = 2;
	}
	else if(document.getElementById('senha').value.length < 6 || document.getElementById('senha').value.length > 10)
	{
		alert("Senha inválida. A senha deve ter de 6 a 10 caracteres.")
		document.getElementById('senha').focus(); 
		segue = 2;
	}
	else
	{
		segue = 1;
	}
	
	//se foram preenchidos de modo correto segue para o ajax
	if(segue == 1)
	{
		var email_form	=	document.getElementById('email').value;
		var senha_form	=	document.getElementById('senha').value;
		var statusLogin = document.getElementById('status');
		var waitFunction = function(status) 
		{ 
			//mostra quando estiver carregando
			statusLogin.innerHTML=status; 
		};
		var loadFunction = function(returnvalue) 
		{ 
			//existe manda para página de central do cliente
			if(returnvalue == '1')
			{
				  statusLogin.innerHTML = ''; 
				  window.location = strPaginaEnviar;
			}
			else if(returnvalue == '2')
			{
				   statusLogin.innerHTML = "O e-mail e senha não conferem.";
			}
			else if(returnvalue == '3')
			{
				   statusLogin.innerHTML = "O e-mail é inválido.";
			}
			else if(returnvalue == '4')
			{
				   statusLogin.innerHTML = "A senha deve ter entre 6 e 10 caracteres.";
			}
			else if(returnvalue == '5')
			{
				   statusLogin.innerHTML = "O cliente não está ativo";
			}
			else 
			{
				   statusLogin.innerHTML = 'Algum Digbrin';
			}
	
		}
		var metodo = 'POST';
	
		var ajx = new ajax();
		ajx.setParams('email',email_form,'senha',senha_form);
		ajx.sendLoad('ajax_login.php', waitFunction, loadFunction,metodo);
	}
}



/*****************************************************
*	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] == 'toptrade' )
{
	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 verifica() {
	var campos = {
		  imgcalcular: document.getElementById("calcular_frete"),
		  valor: document.getElementById("valorFrete"),
		  localidade: document.getElementById("localidade"),
		  cep1: document.getElementById("cep1"),
		  cep2: document.getElementById("cep2")
		};
	
	var ajax = XMLHTTPRequest();
	
	  ajax.open("GET", 
	  ("/includes/ajax/frete-ajax.php?mostra_valor=1&cep="+document.getElementById("cep1").value+"-"+document.getElementById("cep2").value), true);
	  ajax.onreadystatechange = function() {
	  if (ajax.readyState == 1) {
	  campos.valor.disabled = true;
	  campos.valor.innerHTML = "calculando...";
	  
	  } else if (ajax.readyState == 4) {
		  if(ajax.responseText == false){
			campos.valor.disabled = false;
			campos.valor.innerHTML = "";
			
		  }else{
			var r = ajax.responseText, valor;
			valor = r;
			if(r == 'notlocalidade')
			{
				campos.localidade.style.display = '';
				campos.cep1.style.display = 'none';
				campos.cep2.style.display = 'none';
				campos.imgcalcular.style.display = 'none';
			}
			else
			{
				campos.valor.disabled = false;
				campos.valor.innerHTML = valor;
				campos.localidade.style.display = 'none';
				campos.cep1.style.disabled = '';
				campos.cep2.style.disabled = '';
				campos.imgcalcular.style.display = '';
			}
		  }
	  }
	};
	ajax.send(null);
	}


/*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";
				 // alert(returnvalue);
				  var vlrFrete = parseFloat(returnvalue).format(2,",","");
				alert(vlrFrete)
				  
				  document.getElementById('valorFrete').innerHTML = "<strong>&nbsp; R$ "+vlrFrete+"</strong>&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;
			}
			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 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
			          },
			    pessoa1: {
								required: "#pessoa1:unchecked"
			    		 },
			   	pessoa2: {
								required: "#pessoa2:unchecked"
			    		 },
				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: 4
				},
				cpf: {
					  	required: "#pessoa1:checked",
					  	minLength: 12
					  },
				cnpj: {
					  	required: "#pessoa2:checked",
					  	minLength: 14
					  },
				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: "Digite os oito números do CEP.",
				pessoa1: "Selecione o tipo de Pessoa.",
				pessoa2: "Selecione o tipo de Pessoa.",
				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.",
				data_nasc: "Digite a data de nascimento.",
				pessoa1: "Selecione o tipo de pessoa.",
				pessoa2: "Selecione o tipo de pessoa.",
				data_nasc_dia: "Digite o seu dia de nascimento.",
				data_nasc_mes: "Digite o seu mês de nascimento.",
				data_nasc_ano: "Digite o seu ano de nascimento.",
				rg: "Digite o RG.",
				cpf: "Digite os 11 dígitos do CPF.",
				cnpj: "Digite o seu CNPJ.",
				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() {
var url = 'includes/ajax/cep-ajax.php?';
var campos = {
  validcep: document.getElementById("validcep"),
  cep: document.getElementById("cep-completo"),
  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", (url+'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 url = 'includes/ajax/cep-ajax.php?';
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")
};

var ajax = XMLHTTPRequest();
  ajax.open("GET", (url+'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-completo"), "blur", buscarEndereco);}
	);
}

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

function mostraDados(idEsconder,idMostrar)
{
	if( idEsconder == 'juridica' )
	{
		document.getElementById('cadastro-subtitulo-fisica').style.display = '';
		document.getElementById('cadastro-campo2').style.display = '';
		document.getElementById('cadastro-subtitulo-juridica').style.display = 'none';
		document.getElementById('cadastro-campo3').style.display = 'none';
	}
	else if( idEsconder == 'fisica' )
	{
		document.getElementById('cadastro-subtitulo-fisica').style.display = 'none';
		document.getElementById('cadastro-campo2').style.display = 'none';
		document.getElementById('cadastro-subtitulo-juridica').style.display = '';
		document.getElementById('cadastro-campo3').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
					  },
				cep1: {
					   	required: true,
					  	minLength:3
					  },
				endereco: "required",
				numero: "required",
				cidade: "required",
				estado: "required",
				bairro: "required"
			},
			messages: {
				cep1: "Digite os cinco primeiros números do CEP.",
				cep1: "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);
}