$(document).ready(function() {
	
	filtros = $('#maincontent div.filtros');
	filtros.find('a').click(function() {
		botao = $(this);
		if ( ! botao.hasClass('ativo') ) {
			c_inner_ = $('#content_inner');
			c_inner_.find('div.productItem').toggleClass('item_lista');
			c_inner_.find('div.product_item_tr').toggleClass('remove_espaco');
			botao.parent().find('a').toggleClass('ativo');
		}
	});

	
	banners = $("#banner");
	banners.show();			

	//apenas numeros na quantidade
	$("input.biginput").keypress(function(){
			(new Mascara(this,mascaraNumeros)).executaMascara();			
		}
	);
	$("input.smallinput").keypress(function(){
			(new Mascara(this,mascaraNumeros)).executaMascara();			
		}	
	);

	novoCabecalho();
	
	$("#okEsqueciSenha").click(function(){
		if($("#email2").val() == ""){
			alertaMensagem('Atenção!','Mensagem de Erro','Por favor, informe o e-mail corretamente.');		
			return false;
		}else{
			try {
				pageTracker._trackPageview("/esqueciSenha.do?utm_source=LAYER&utm_medium=LINK&utm_campaign=ESQUECIMINHASENHA"); 
			} catch (e) {
				// TODO: handle exception
			}
			
			$.ajax({
				   type: "POST",
				   url: "ajaxReenviarSenha.do",
				   data: "method=gerarEmailConfirmacao&email="+$("#email2").val(),
				   success: function(msg){
						$('#retornoEsqueciSenha').html(unescape(msg));
				   }
				 });
			}
		}

	);
	
});

function ativarTabs(id_div){
	
	tabs = $('#' + id_div +  ' ul');
	if( tabs.length > 0 ) {
		tabs.idTabs();
		tab = tabs.find("li");
		if( tab.length == 1 ) {
			tab.find('a').css({cursor: 'default'});
		}
	}

}
function Mascara(elemento,funcao){
	this.elemento = elemento;
	this.funcao = funcao;	
	objeto  = this;
	this.executaMascara = function(){		
		setTimeout(this.executaFuncao,1);
	}		
	this.executaFuncao = function(){		
		objeto.elemento.value = objeto.funcao(objeto.elemento.value);
	}
}
function mascaraNumeros(valor){
	return valor.replace(/\D/g,"");	
}
function mascaraData(valor){	
	valor = valor.replace(/\D/g,"");	
	valor = valor.replace(/^[^0-3]/,"");//primeiro digito do dia só pode ser de 0 a 3 
	valor = valor.replace(/^(3)[^0-1]/,"$1");//se o primeiro digito é 3, o segundo digito do dia só pode ser de 0 a 1
	valor = valor.replace(/^(\d{2})[^0-1]/,"$1");//mes só pode comecar por 0 ou 1
	valor = valor.replace(/^(\d{2})(0)[^1-9]/,"$1$2");//se o mes começar por 0, só pode aceitar de 1 a 9
	valor = valor.replace(/^(\d{2})(1)[^0-2]/,"$1$2");//se o mes começar por 1, só pode aceitar 0, 1 ou 2 depois 
	valor = valor.replace(/^(\d{2})(\d{1})/,"$1/$2");//coloca a barra após o segundo numero	
	valor = valor.replace(/^(\d{2})[/](\d{2})(\d{1})/,"$1/$2/$3");//coloca a barra depois do primeiro digito do ano
	
	var validaDiaMes = new RegExp("(\\d{2})/(\\d{2})"); //dd/MM	    
    if (validaDiaMes.test(valor)){
    	var dia = RegExp.$1;
  	    var mes = RegExp.$2;
  	    
	  	diaMes = new Date(2012,--mes,dia);//engessado ano bissexto
  	    if(diaMes.getMonth() != mes){  	    
  	    	valor = valor.substr(0,(valor.length-1));
  	    }
    }
	    
    var validaDiaMesAno = new RegExp('(\\d{2})/(\\d{2})/(\\d{4})'); //dd/MM/yyyy
    
    if (validaDiaMesAno.test(valor)){
    	var dia = RegExp.$1;
  	    var mes = RegExp.$2;
  	    var ano = RegExp.$3;
	  	diaMesAno = new Date(ano,--mes,dia);
	  	 if (!(diaMesAno.getMonth() == mes && diaMesAno.getFullYear() == ano)) {
	  		valor = valor.substr(0,(valor.length-1));
        }
    }  
	
	return valor;
}

function adicionaItemCesta(codigoItem,codigoListaPresentes){
	$("#codigoItem").val(codigoItem);
	if(codigoListaPresentes != undefined){
		$("#numeroSequencialLista").val(codigoListaPresentes);
	}
	$("#quantidade").val($("#quantidade"+codigoItem).val());	
	$("form#formAdicionarCesta").submit();
}

function adicionaItemLista(codigoItem,codigoListaPresentes){	
	$("#codigoItem").val(codigoItem);
	$("#numeroSequencialLista").val(codigoListaPresentes);
	$("#quantidade").val($("#quantidade"+codigoItem).val());
	$("form#formAdicionarCesta").attr("action","produtosComprados.do");
	$("#metodo").val("paginaPrincipal");
	$("form#formAdicionarCesta").submit();
}

/*
function fecharLayer(layer){
	$.ajax({
		   type: "POST",		  
		   data: "cookie="+($("#cepCheckbox:checked").val() == null ? "false" : "true"),
		   url: "fecharLayer.do"
		 });
	layer.close();
	try {
		pageTracker._trackPageview("/fecharLayer.do?utm_source=LAYER&utm_medium=LINK&utm_campaign=FECHAR"); 
	} catch (e) {
		// TODO: handle exception
	}
	
}*/

function mudaCep(idCepInicio,idCepFim){	
	setTimeout("testaCep('"+idCepInicio+"','"+idCepFim+"')",1);
}
function testaCep(idCepInicio,idCepFim){
	if(gebi(idCepInicio).value.length == 5){
		gebi(idCepFim).select();
	}
}
function linkPrimeiraCompra(urlPrimeiraCompra){	
	try {
		pageTracker._trackPageview("/primeiraCompra.do?utm_source=LAYER&utm_medium=LINK&utm_campaign=CADASTRO"); 
	} catch (e) {
		// TODO: handle exception
	}
	
	redirect(urlPrimeiraCompra);
}
function verCorreios(){
	try {
		pageTracker._trackPageview("/consultarCorreios.do?utm_source=LAYER&utm_medium=LINK&utm_campaign=CONSULTARCORREIOS"); 
	} catch (e) {
		// TODO: handle exception
	}
	
	window.open('http://www.buscacep.correios.com.br/');
}
function enviarAviseme(){
	
	var msg = '';
	if ($("#aviseMeNome").val() == '' ) {
		msg += 'Por favor, digite o seu nome.<br />';
		$("#aviseMeNome").focus();
	}
	if ($("#aviseMeEmail").val() == '' ) {
		msg += 'Por favor, digite o seu e-mail.<br />';
		$("#aviseMeEmail").focus();
	}		
	if (msg == '') {
		$('#aviseme_form').hide();
		$('#texto_enviado').show();
		$.ajax({
			   type: "POST",
			   url: "aviseMe.do",
			   data: "nomeCliente="+$("#aviseMeNome").val()+"&emailCliente="+$("#aviseMeEmail").val()+"&codigoItem="+$("#codigoItemAviseme").val(),				 
			   success: function(msg){
						
			   }
			 });
	}
	else {
		alertaMensagem("Atenção!","Mensagem de Erro",msg);				
	}
}
function alertaMensagem(titulo, tipoMsg, msg,functionClose){


	iHeight = 85;
	iHeight = (iHeight * (msg.split("<br />").length - 1));

	if (iHeight < 100)
		iHeight = 160;
	
	if (iHeight > 500)
		iHeight = 420;
	
	$('#modal_alert_h2').text(titulo);//ex:'Atenção!'
	$('#modal_alert_p').text(tipoMsg);//ex:'Mensagem de erro'
	$('#modal_alert_p_strong').html(msg);//ex:'campo com erro,<br />outro campo.'			
	
	if($.isFunction(functionClose)){
		$("#modal_alert").modal(
				{onClose: function (dialog) {
					$.modal.close();
					$(functionClose);
				},
				containerCss:{width:"380px",height:""+iHeight+"px"}}
		);	
	}else{
		$("#modal_alert").modal({containerCss:{width:"380px",height:""+iHeight+"px"}});	
	}
}


/***
 * 
 * Adiciona o item na cesta por ajax.
 * Efeito down/top na cesta.
 * 
 * @param codigoItem
 */
function adicionaItemCestaAjax(codigoItem){
	
	var param = "metodo=adicionarItem";
	param += "&codigoItem=" + codigoItem;
	param += "&origem=cestaAjax";
	param += "&quantidade=" + $("#quantidade"+codigoItem).val();	
	
	$.ajax({
		   type: "POST",
		   url: "adicionarItemCesta.do",
		   data: param,
		   success: function(msg){
				posAtualizaCestaRodape(msg,codigoItem);
		   }
	});
}

//Atualiza cesta de compras do rodape.
function ajaxAtualizaCestaRodape(){
	$.ajax({
	   type: "POST",
	   url: "ajaxExibirCesta.do",
	   data: "metodo=cestaCabecalho",
	   success: function(msg){
		   posAtualizaCestaRodape(msg);
	   }
	 });
}

function exibirFinalizarPedFlutuante(boxVisivel){
	if(boxVisivel.find('div.cesta_aberta').length > 0 ){
		$('#barra_flutuante #finalizarFlutuante').show();
	}else{
		$('#barra_flutuante #finalizarFlutuante').hide();
	}
}
function posAtualizaCestaRodape(msg,codigoItem){
	$('div.box-toggle').html(unescape(msg));
	addJSCestaCabecalho();
	// if add item no carro.
	boxVisivel = getBoxToggle();
	exibirFinalizarPedFlutuante(boxVisivel);
	if(codigoItem != undefined){
		// verifica se tem mensagem de erro.
		if( boxVisivel.find('#erroCestaCabecalho').length == 0 ) {
			$('span.item_na_cesta'+codigoItem).show();
			cesta = boxVisivel.find('div.cesta_aberta');
			cesta.slideDown();
			showCestaAberta = false;
			numberRandow = Math.random()*10000;	
			hideCestaAbertaDIV(numberRandow ,2000,300,cesta);
		}else {
			alertaMensagem("Atenção!","Mensagem de Erro",boxVisivel.find('#erroCestaCabecalho').html());		
		}
	}	
}

function divConsultaCepCorreios(mensagemErro){
	$('.popupInfo.correios').each(function () {
	    var distance = 10;
	    var time = 250;
	    var hideDelay = 500;
	    var hideDelayTimer = null;
	    var beingShown = false;
	    var shown = false;
	    var tooltip = $('.tooltip', this);
	    var info = $('.popup-tooltip', this);
	    $([tooltip.get(0), info.get(0)]).mouseover(function () {
	        if (hideDelayTimer) clearTimeout(hideDelayTimer);
	        if (beingShown || shown || tooltip.attr('disabled') == 'disabled' ) { 
	            return;
	        } else {
	            beingShown = true;
	            info.css({
	                top: 15,
	                left:  55,
	                display: 'inline'
	            }).animate({
	                top: '+=' + distance + 'px',opacity: 1,  zindex: 100
	            }, time, 'swing', function() {
	                beingShown = false;
	                shown = true;
	            });

	            
	        }
	        return false;
	    }).mouseout(function () {
	        if (hideDelayTimer) clearTimeout(hideDelayTimer);
	        hideDelayTimer = setTimeout(function () {
	        	if(tooltip.attr('disabled') != 'disabled') {
		            hideDelayTimer = null;
		            info.animate({
		                top: '+=' + distance + 'px',
		                opacity: 0
		            }, time, 'swing', function () {
		                shown = false;
		                info.css('display', 'none');
		            });
	        	}
	        }, hideDelay);
	        return false;
	    });
	});	
}
function novoCabecalho(){

	divConsultaCepCorreios();
	
	$('#fechar-aviso').click(function(){
		$("#aviso-logar").slideToggle("slow");
		$.ajax({
			   type: "POST",		  
			   data: "",
			   url: "fecharLayer.do"
		 });
	
	});
	if($('#cepCabecalho').length > 0 ) {
		$('#cepCabecalho').mask('99999-999').
		bind('keydown', function(e) {
			 var code = e.which;
			 if(code == 13) { 
				 $('#lnk-cep').click();
			 }else if(code == 27){
 			   setTimeout(function () {	
 				   showCepNavegacao();
 			   },50);
			 }
		}).focusout(function(){
			cepVal  = $('#cepCabecalho').val().replace('_','').replace(' ','');
			if(cepVal.length != 9){
				showCepNavegacao();
			}else {
				setTimeout(function () {
					tooltip = $('#cep-topo .tooltip');
					cepVal  = $('#cepCabecalho').val().replace('_','').replace(' ','');
					if( $('#lnk-cep').is(':visible') && tooltip.attr('disabled') != 'disabled' && cepVal.length == 9 ) {
						showCepNavegacao();
					}
				},800);
			}
		});
	}

	$("#cep_navegacao_ativo").click(function(){
		showEditarCep();
	});

}
function showEditarCep(){
	divCepTopo = $("#cep-topo");
	divCepTopo.find('#cep_navegacao_ativo').hide();
	divCepTopo.find('#loadingCep').hide();
	divCepTopo.find('#lnk-cep').show();
	divCepTopo.find('#cepCabecalho').show();
	$("#cepCabecalho").val('').focus();	
	return divCepTopo;
}

function showCepNavegacao(){
	divCepTopo = $("#cep-topo");
	divCepTopo.find('#loadingCep').hide();
	divCepTopo.find('#lnk-cep').hide();
	divCepTopo.find('#cepCabecalho').hide();
	divCepTopo.find('#cep_navegacao_ativo').show();
	return divCepTopo;	
}

function showLoadingCepNavegacao(){
	divCepTopo = $("#cep-topo");
	divCepTopo.find('#loadingCep').show();
	divCepTopo.find('#lnk-cep').hide();
	divCepTopo.find('#cepCabecalho').hide();
	divCepTopo.find('#cep_navegacao_ativo').hide();
	return divCepTopo;
}
function editarCepNavegacaoErro(mensagemErro){
	divCepTopo = showEditarCep();
	tooltip = $('.tooltip',divCepTopo);
	tooltip.attr('disabled','disabled');
	mensagem = $('#dpop span',divCepTopo);
	mensagem.show();
	mensagem.html(mensagemErro);
    var info = $('#dpop');
	var distance = 10;
	var time = 250;
	var hideDelay = 5000;
    info.css({
        top: 15,
        left:  -17,
        display: 'inline'
    }).animate({
        top: '+=' + distance + 'px',
        opacity: 1,  zindex: 100
    }, time, 'swing');
	setTimeout(function () {
	            hideDelayTimer = null;
	            info.animate({
	                top: '+=' + distance + 'px',
	                opacity: 0
	            }, time, 'swing', function () {
	                info.css('display', 'none');
	            });
            	mensagem.hide();
            	mensagem.html('');
            	tooltip.attr('disabled','');
	}, hideDelay);
}
