//objSugestao = new Sugestao(1);
//carrega o documento e executa function

$(document).ready(function()
{
	//objeto sugesto
	//objSugestao.executaFuncao();					
});

function redirect(pg){ window.location.href=pg; }

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

function limpaFiltroBusca(pais,tipo,subtipo,valor)
{
	
	var waitFunction = function(status) 
	{ 
		// mostra quando estiver carregando
		mensagem = 'carregando..';
	//	document.getElementById('statusLista').innerHTML=mensagem; 
	};
	var loadFunction = function(returnvalue) 
	{ 
		// imprime retorno
	//	document.getElementById('statusLista').innerHTML= returnvalue;
		window.location.reload();
	}
	var metodo = 'POST';

	var ajx4 = new ajax();
	ajx4.setParams('ajax','1','pais',pais,'tipo',tipo,'subtipo',subtipo,'valor',valor);
	ajx4.sendLoad('includes/ajax-limpa-filtros.php', waitFunction, loadFunction,metodo);
	
	//ajx.sendForm(document.getElementById('form4'));		
}

//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;
}

//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(usaAjax, bolExecuta)
{
	$("#cep1").focus(
						function()
						{ 
							this.value = ''; 
						}
					);
					
	$("#cep1").keydown(
							function()
							{ 
								if( $("#cep1").val().length == 5 )
								{ 
									$("#cep2").focus();
								} 
							}
						);
	
	//máscara
	Mascaras.carregar();
	
	//monta o link não sei meu cep
	$("#nao_sei_cep").attr("href", "http://www.correios.com.br/servicos/cep/cep_loc_log.cfm");
	$("#nao_sei_cep").attr("target", "_blank");
	
	//valida form e coloca o link na botão para submeter o form
	$("#calcular_frete").attr("href", "#");
	$("#calcular_frete").click(
								  function ()
								  {
								  	verifica(usaAjax, bolExecuta);							  	
								  }
							  )
}

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

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

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

//limpa valor do frete
function reset_valor(valorCarrinho)
{
	document.getElementById("valorTotal").innerHTML = "R$ "+formataValorPreco(Number(valorCarrinho));
	document.getElementById("valorFrete").innerHTML = " Selecione ";
}
/*****************************************************
*	// Funções do carrinho de compras                *
******************************************************/


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

function verificaFaleNew()
{
	erro = 0;
	assunto	    =	document.getElementById("assunto");
	nome	    =	document.getElementById("nome");
	ddd			=	document.getElementById("ddd");
	telefone	=	document.getElementById("telefone");
	email	    =	document.getElementById("email");
	mensagem    =	document.getElementById("mensagem");

	if(assunto.value == ''){
		alert('Informe o assunto.');
		assunto.focus();
		erro = 1;
		return false;
	}
	if(nome.value == ''){
		alert('Informe seu nome.');
		nome.focus();
		erro = 1;
		return false;
	}
	if(ddd.value == ''){
		alert('Informe o ddd .');
		ddd.focus();
		erro = 1;
		return false;
	}
	if(telefone.value == ''){
		alert('Informe seu telefone.');
		telefone.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(mensagem.value == ''){
		alert('Campo Mensagem não pode ser enviado em branco.');
		mensagem.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 = "";
					break;
				default : mensagem = "Aguarde...";
			}
			document.getElementById('statusFale').innerHTML=mensagem; 
		};
		var loadFunction = function(returnvalue) 
		{ 
			var retorno = new String(returnvalue);
			var msg = '';
			if(retorno == 1 ) 
				msg = "Verificação Incorreta.";
			else if(retorno == 2 ) 
				msg = "Falha no envio da mensagem.";
			else if(retorno == 3 ) 
			{
					msg = "Mensagem enviada com Sucesso!";
					nome.value = "";
					email.value = "";
					mensagem.value = "";
			}
			else if(retorno == 5 )  
				msg = "Falha no envio da mensagem.";
			else 
				msg = "Mensagem enviada com Sucesso!";
				
			//assunto.value = nome.value = ddd.value = telefone.value = email.value = mensagem.value = "";
			document.getElementById('frmFaleConosco').reset();
			document.getElementById('statusFale').innerHTML= '<strong>'+msg+'</strong>';	
			alert(msg);

		}
		var metodo = 'POST';
	
		var ajx4 = new ajax();
		ajx4.setParams('ajax','1','assunto',assunto.value,'nome',nome.value,'ddd',ddd.value,'telefone',telefone.value,'email',email.value,'mensagem',mensagem.value);
		ajx4.sendLoad('fale_conosco_ajax.php', waitFunction, loadFunction,metodo);
	} 
	else 
	{ 
		return false; 
	}
}

function verificaContatoVinhoNew()
{
	erro = 0;
	nome	    =	document.getElementById("nome");
	ddd			=	document.getElementById("ddd");
	telefone	=	document.getElementById("telefone");
	email	    =	document.getElementById("email");
	mensagem    =	document.getElementById("mensagem");

	if(nome.value == ''){
		alert('Informe seu nome.');
		nome.focus();
		erro = 1;
		return false;
	}
	if(ddd.value == ''){
		alert('Informe o ddd .');
		ddd.focus();
		erro = 1;
		return false;
	}
	if(telefone.value == ''){
		alert('Informe seu telefone.');
		telefone.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(mensagem.value == ''){
		alert('Campo Mensagem não pode ser enviado em branco.');
		mensagem.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 = "";
					break;
				default : mensagem = "Aguarde...";
			}
			document.getElementById('statusContatoVinho').innerHTML=mensagem; 
		};
		var loadFunction = function(returnvalue) 
		{ 
			var retorno = new String(returnvalue);
			var msg = '';
			if(retorno == 1 ) 
				msg = "Verificação Incorreta.";
			else if(retorno == 2 ) 
				msg = "Falha no envio da mensagem.";
			else if(retorno == 3 ) 
			{
					msg = "Mensagem enviada com Sucesso!";
					nome.value = "";
					email.value = "";
					mensagem.value = "";
			}
			else if(retorno == 5 )  
				msg = "Falha no envio da mensagem.";
			else 
				msg = "Mensagem enviada com Sucesso!";
				
			//assunto.value = nome.value = ddd.value = telefone.value = email.value = mensagem.value = "";
			document.getElementById('frmContatoVinho').reset();
			document.getElementById('statusContatoVinho').innerHTML= '<strong>'+msg+'</strong>';	
			alert(msg);

		}
		var metodo = 'POST';
	
		var ajx4 = new ajax();
		ajx4.setParams('ajax','1','nome',nome.value,'ddd',ddd.value,'telefone',telefone.value,'email',email.value,'mensagem',mensagem.value);
		ajx4.sendLoad('duvida_vinhos_ajax.php', waitFunction, loadFunction,metodo);
	} 
	else 
	{ 
		return false; 
	}
}

function verificaFale()
{
	erro = 0;
	nome	    =	document.getElementById("nomeFale");
	email	    =	document.getElementById("emailFale");
	mensagem    =	document.getElementById("mensagemFale");

	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(mensagem.value == ''){
		alert('Campo Mensagem não pode ser enviado em branco.');
		mensagem.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 = "";
					break;
				default : mensagem = "Aguarde...";
			}
			document.getElementById('statusFale').innerHTML=mensagem; 
		};
		var loadFunction = function(returnvalue) 
		{ 
			var retorno = new String(returnvalue);
			var msg = '';
			if(retorno == 1 ) 
				msg = "Verificação Incorreta.";
			else if(retorno == 2 ) 
				msg = "Falha no envio da mensagem.";
			else if(retorno == 3 ) 
			{
					msg = "Mensagem enviada com Sucesso!";
					nome.value = "";
					email.value = "";
					mensagem.value = "";
			}
			else if(retorno == 5 )  
				msg = "Falha no envio da mensagem.";
			else 
				msg = "Mensagem enviada com Sucesso!";
				
			document.getElementById('statusFale').innerHTML= '<strong>'+msg+'</strong>';	
			alert(msg);
		}
		var metodo = 'POST';
	
		var ajx4 = new ajax();
		ajx4.setParams('ajax','1','nomeFale',nome.value,'emailFale',email.value,'mensagemFale',mensagem.value);
		ajx4.sendLoad('fale_conosco_ajax.php', waitFunction, loadFunction,metodo);
	} 
	else 
	{ 
		return false; 
	}
}

//valida o form sem alert
//somente mensagem
function carregaValidacoesFaleConoscoNew()
{
	$.validator.setDefaults({
		submitHandler: function() { 
			verificaFaleNew(); 
			/*
			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: {
				assunto: "required",
				nome: "required",
				ddd: "required",
				telefone: "required",
				email: "required email",
				mensagem: "required"
			},
			messages: {
				assunto: "Digite seu nome.",
				nome: "Digite seu nome.",
				ddd: "Digite seu ddd.",
				telefone: "Digite seu telefone.",
				email: "Digite corretamente seu e-mail.",
				mensagem: "Digite sua mensagem."
			}
		});
		
		//coloca o foco no primeiro campo
		$("#assunto").focus();
	});	
}

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: {
				nomeFale: "required",
				emailFale: "required email",
				mensagemFale: "required"
			},
			messages: {
				nomeFale: "Digite seu nome.",
				emailFale: "Digite corretamente seu e-mail.",
				mensagemFale: "Digite sua mensagem."
			}
		});
		
		//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] == 'adegabrasil' )
{
	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()
{
	$(document).ready(function() {
		$.validator.setDefaults({
			submitHandler: function() { 
				
				//seta a página para ser remetida por javascript
				if( strPagina.indexOf('identificacao.php') != -1 )
					strPaginaEnviar = 'entrega.php';
				else if( strPagina.indexOf('central-cliente.php') != -1 )
					strPaginaEnviar = 'central-cliente.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 validaLoginTopo()
{
	email = document.getElementById('email');
	senha = document.getElementById('senha');
	total = document.getElementById('total-menu');
	if( email.value == "" || email.value.indexOf('.') == -1 || email.value.indexOf('@') == -1 )
	{
		alert('E-mail inválido.');
		email.focus();
		return false;
	}
	else if( senha.value.length < 6 )
	{
		alert('Senha inválida. Digite os 6 caracteres da senha.');
		senha.focus();
		return false;
	}
	else
	{
		$.ajax({
		   type: "POST",
		   url: "identificacao-ajax.php",
		   data: "email="+email.value+"&senha="+senha.value+"&total="+total.value,
		   success: function(){
			   window.location.href='central-cliente.php';
		     // $("#status").html(msg);
			 //$("#msg-login-carrinho").html(msg);
			 
		   }
		 });
		return true;
	}
}

function esqueciSenhaTopo()
{
	erro = 0;
	email	=	document.getElementById("login-menu");
	
	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.frmLoginTopo.email_topo.value.indexOf('@')==-1 || document.frmLoginTopo.email_topo.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; 
	}	
}


function verificaLogin()
{
	email = document.getElementById('email');
	senha = document.getElementById('senha');
	
	//verifica se os campos foram preenchidos corretamente
	if(email.value == "" ){
		alert("Digite seu e-mail.");
		email.focus(); 
		segue = 2;
	}
	else if(email.value.indexOf('@')==-1 || email.value.indexOf('.')==-1) 
	{ 
		alert("E-mail inválido. Verifique se no esqueceu '.' e '@' no seu e-mail."); 
		email.focus(); 
		segue = 2; 
	} 
	else if(senha.value == "")
	{
		alert("Digite sua senha.")
		senha.focus(); 
		segue = 2;
	}
	else if(senha.value.length < 6 || senha.value.length > 10)
	{
		alert("Senha inválida. A senha deve ter de 6 a 10 caracteres.");
		senha.focus(); 
		segue = 2;
	}
	else
	{
		segue = 1;
	}
	
	//se foram preenchidos de modo correto segue para o ajax
	if(segue == 1)
	{
		email_form	=	email.value;
		senha_form	=	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 = 'sdasd'; 
				  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;
	
	if (document.getElementById("email"))
	{
		email = document.getElementById("email");
	} 
	else 
	{
		email = document.getElementById("login-menu");
	}
	gd_string = document.getElementById("captcha");
	
	if(email.value == '')
	{
		alert('Informe seu endereço de e-mail.');
		email.focus();
		erro = 1;
		return false;
	}
	if(gd_string.value == '')
	{
		alert('Campo de verificação não pode ser vazio.');
		gd_string.focus();
		erro = 1;
		return false;
	}
	//alert(erro);
	if(erro==0)
	{
		 // liberar soh quando funcionar o ajax
	// passou na validação
		//alert("passou");
		var waitFunctionLogin = function(status) 
		{ 
			//mostra quando estiver carregando
			switch (status) {
				case 'inicializando' : ;
				case 'carregando...' : ;
				case 'carregado' : ;
				case 'interação' :
					mensagem = "Aguarde, enviando senha...";
					break;				
				case 'completo' :
					mensagem = "Sucesso!";
					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;
			}
		//	document.getElementById('status').innerHTML= mensagem;
			alert(mensagem);
			mensagem = "";
		}
		var metodo = 'POST';
	
		var ajx8 = new ajax();
		//alert(email.value + gd_string.value);
		ajx8.setParams('ajax','1','email',email.value,'gd_string',gd_string.value);
		ajx8.sendLoad('../includes/esqueci-senha-ajax.php', waitFunctionLogin, loadFunctionLogin,metodo);
	} 
	else 
	{ 
		return false; 
	}
	
	
}


function esqueciSenha2()
{
	erro = 0;
	
	if (document.getElementById("email"))
	{
		email = document.getElementById("email");
	} 
	else 
	{
		email = document.getElementById("login-menu");
	}
	gd_string = document.getElementById("captcha");
	
	if(email.value == '')
	{
		alert('Informe seu endereço de e-mail.');
		email.focus();
		erro = 1;
		return false;
	}
	if(gd_string.value == '')
	{
		alert('Campo de verificação não pode ser vazio.');
		gd_string.focus();
		erro = 1;
		return false;
	}
	//alert(erro);
	if(erro==0)
	{
	var emailad = $('#email').val();
	$.post("../includes/esqueci-senha-ajax.php", { email: emailad, gd_string: gd_string.value},
   		function(ok){
     	if (ok == '0') {
			alert('Senha enviada com sucesso!');
			}
			else	{
					alert('Senha nao pode ser enviada! Verifique os campos!');
					}
 	  });
	} 
	else 
	{ 
		return false; 
	}
	
	
}


function setCaptcha(valor)
{
	document.getElementById("captcha").value = valor;
}
/*****************************************************
*	// 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"
				         },
				//profissao: "required",
				sexo: "required",
				pessoa1: { 
							required: "#pessoa2:unchecked"
				         },
				dia: {
								required: "#pessoa1:checked",
								minLength: 2						
						   },
				mes: {
								required: "#pessoa1:checked",
								minLength: 2						
						   },
				ano: {
								required: "#pessoa1:checked",
								minLength: 4						
						   },
				rg: {
						required: "#pessoa1:checked"						
					},
				cpf: {
					  	required: "#pessoa1:checked",
					  	minLength: 12						
					  },
				pessoa2: { 
						 	required: "#pessoa1:unchecked"
				         },
				cnpj: {
				  	   	 required: "#pessoa2:checked",
				  	   	 minLength: 14						
				       },
			    confirma_email: {
					        required: "#email:filled",
					   		equalTo: "#confirma_email"
					      }
				/*,
				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.",
				dia: "Digite o dia do seu nascimento.",
				mes: "Digite o mês do seu nascimento.",
				ano: "Digite o ano do seu nascimento.",
				rg: "Digite seu RG.",
				cpf: "Digite o seu CPF completo.",
				pessoa2: "Selecione o tipo de pessoa.",
				cnpj: "Digite o CNPJ.",
				//inscricao: "Digite a inscrição estadual",
				//confirma: "Senha e confirmação de senha diferentes.",
				confirma_email: "Confirmação do e-mail e e-mail são 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 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"),
  li_select_localidade: document.getElementById("li_select_localidade")
};

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.li_select_localidade.disabled = true;
    campos.li_select_localidade.style.display = "none";
    campos.validcep.innerHTML = "";
    var r = ajax.responseText, i, endereco, numero, bairro, cidade, estado;
    endereco = r.substring(0, (i = r.indexOf(':')));
	if(endereco == '')
	{
		campos.li_select_localidade.disabled = false;
		campos.li_select_localidade.style.display = "";
	}
    campos.endereco.disabled = false;
    campos.endereco.value = unescape(endereco.replace(/\+/g," "));
    r = r.substring(++i);
    bairro = r.substring(0, (i = r.indexOf(':')));
	if(bairro == '')
	{
		campos.li_select_localidade.disabled = false;
		campos.li_select_localidade.style.display = "";
	}
    campos.bairro.disabled = false;
    campos.bairro.value = unescape(bairro.replace(/\+/g," "));
    r = r.substring(++i);
    cidade = r.substring(0, (i = r.indexOf(':')));
	if(cidade == '')
	{
		campos.li_select_localidade.disabled = false;
		campos.li_select_localidade.style.display = "";
	}
    campos.cidade.disabled = false;
    campos.cidade.value = unescape(cidade.replace(/\+/g," "));
    r = r.substring(++i);
    estado = r.substring(0, (i = r.indexOf(';')));
	if(estado == '')
	{
		campos.li_select_localidade.disabled = false;
		campos.li_select_localidade.style.display = "";
	}
    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++ )
		{
			if( document.getElementById(idEsconder+'_'+i) )
				document.getElementById(idEsconder+'_'+i).style.display = 'none';
		}
		
		//mostra
		for( i = 1; i <= 2; i++ )
		{
			if( document.getElementById(idMostrar+'_'+i) )
				document.getElementById(idMostrar+'_'+i).style.display = '';
		}
	}
	else if( idEsconder == 'juridica' )
	{
		//esconde
		for( i = 1; i <= 2; i++ )
		{
			if( document.getElementById(idEsconder+'_'+i) )
				document.getElementById(idEsconder+'_'+i).style.display = 'none';
		}
		
		//mostra
		for( i = 1; i <= 3; i++ )
		{
			if( document.getElementById(idMostrar+'_'+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');
	}
}

/*****************************************************
*	// Funções do entrega                            *
******************************************************/

/*****************************************************
*	 Funções do detalhe do produto                 *
******************************************************/
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;
}

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

/*****************************************************
*	 // Funções do detalhe do produto                 *
******************************************************/

/*****************************************************
*    // Funções do cadasto da news letter
******************************************************/

//valida o form sem alert
//somente mensagem
function carregaValidacoesNewsLetter()
{
	$().ready(function() {
		//carrega as validações do form
		$("#frmNewLetter").validate({
			rules: {
				nome: "required",
				email: "required email",
				cidade: "required",
				estado: "required"
			},
			messages: {
				nome: "Digite seu nome.",
				email: "Digite corretamente seu e-mail.",
				cidade: "Digite sua cidade.",
				estado: "Selecione seu estado."
			}
		});
		
		//coloca o foco no primeiro campo
		$("#nome").focus();
	});	
}


jQuery.fn.DefaultValue = function(text){
    return this.each(function(){
		//Make sure we're dealing with text-based form fields
		if(this.type != 'text' && this.type != 'password' && this.type != 'textarea')
			return;
		
		//Store field reference
		var fld_current=this;
		
		//Set value initially if none are specified
        if(this.value=='') {
			this.value=text;
		} else {
			//Other value exists - ignore
			return;
		}
		
		//Remove values on focus
		$(this).focus(function() {
			if(this.value==text || this.value=='')
				this.value='';
		});
		
		//Place values back on blur
		$(this).blur(function() {
			if(this.value==text || this.value=='')
				this.value=text;
		});
		
		//Capture parent form submission
		//Remove field values that are still default
		$(this).parents("form").each(function() {
			//Bind parent form submit
			$(this).submit(function() {
				if(fld_current.value==text) {
					fld_current.value='';
				}
			});
		});
    });
};
