jQuery(function( $ ){
	$.easing.elasout = function(x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
	};	


	$('#bt_detalhes_do_jogo').click(function(){
		$.scrollTo('#C_bt_detalhes_do_jogo', 1000, { over:{ top:-0.5 } });
	});
	
	$('#bt_favoritar').click(function(){
		$.scrollTo('#C_favoritar', 1000, { over:{ top:-0.5 } });
	});
	
	$('#bt_ler_comentarios').click(function(){
		$.scrollTo('#C_ler_comentarios', 1000, { over:{ top:-0.2 } });
	});
	
	$('#bt_enviar_a_um_amigo').click(function(){
		$.scrollTo('#C_enviar_a_um_amigo', 1000, { over:{ top:-0.5 } });
	});
	
	$('#btComentar').click(function(){
		$.scrollTo('#C_titComentario', 1000, { over:{ top:-0.5 } });
	});
	
	$('.bt_voltar').click(function(){
		history.go(-1);
	});
	
	$('#quero_participar').click(function(){
		//$("#div0").hide();
		//$("#div1").hide();
		//$("#div2").hide();
		$("#div3").show();
		$.scrollTo("#div3", 1000, { over:{ top:-0.1 } });
	});
	
	$('.btDownload').click(function(){
		var ids = $(this).attr('id').split("|")
		$("#txtAREAID").val(ids[0]);
		$("#txtID").val(ids[1]);
		//$("#div0").hide();
		//$("#div1").hide();
		//$("#div2").hide();
		$("#boxDownload").show();
		$.scrollTo("#boxDownload", 1000, { over:{ top:-0.1 } });
	});
	
	$("#btOpterDownload").click(function(){
		$("#msgDownload").show();
		$("#msgDownload").html("Verificando o c&oacute;digo ...");
		var teste = $("#txtCodigoDown").val()=="";
		if(teste){
			$("#msgDownload").html("Digite o c&oacute;digo ...");
		}
		$.post('includes/verificaDownload.php',
			{ codigo : $("#txtCodigoDown").val(), areaid : $("#txtAREAID").val(), id : $("#txtID").val() },
				function(resposta){
					teste = resposta;
					if(teste==0){
						$('#msgDownload').html("C&oacute;digo inválido");
					}else{
						$("#txtCodigoDown").hide();
						$("#btOpterDownload").hide();
						$('#msgDownload').html("<a href='baixar_download.php?arquivo="+resposta+"' class='conteudoInterna' style='color:#FF3300;;font-size:16px; font-weight:bold'>Clique aqui para baixar o refil</a>");
					}
				}
		  );
	});

	$("#PromoEnviaEmail").click(function(){
		//$("#txtEmail").hide();
		$("#promoMSGEmail").show();
		$("#promoMSGEmail").html("Verificando...");
		$.post('includes/verificaPreenchimentoEndereco.php',
			{ email : $("#txtEmail").val() },
				function(resposta){
					variaveis 		= resposta.split("|");
					usuarioExst 	= variaveis[0]==true; // Bool: existe ou nao no banco
					preencheuEnd 	= variaveis[1]; // Bool: preencheu endereco ou nao

					if(usuarioExst==false){
						$('#promoMSGEmail').html("<a href='cadastro.php'>Voc&ecirc; n&atilde;o est&aacute; cadastrado, clique aqui para se cadastrar.</a>")
					}else{
						if(preencheuEnd==0){
							$("#promoDivSenha").show();
							$("#exibeEndereco").show();	
							$('#emailVerifica').hide();	
							$("#camposPromo").show();
						}else{
							$("#promoDivSenha").show();
							$("#exibeEndereco").hide();	
							$('#emailVerifica').hide();	
							$("#camposPromo").show();
						}
					}
					//$('#cidades').html(resposta);
				}
			);
	});

	$("#btGravar").click(function(){
			
		var $msgErro="";
		$senha = $("#txtSenha").val();

		if($("#promoResposta").val()==""){
			$msgErro = $msgErro + "Digite sua resposta antes de clicar em Participar. \n";
			$("#promoResposta").focus();
			
		}

		if($("#exibeEndereco").css('display')=='block'){
			$endereco 		= $("#endereco").val();
			$numero   		= $("#numero").val();
			$complemento   	= $("#complemento").val();
			$bairro   		= $("#bairro").val();
			$estado   		= $("#estados").val();
			$cidade   		= $("#cidades").val();
			$cidade2   		= $("#cidades2").val();
			$cep      		= $("#promoCep1").val()+"-"+$("#promoCep2").val();
			if($endereco==""){
				$msgErro = $msgErro + " Informe o seu endereço.\n";
			}
			if($numero==""){
				$msgErro = $msgErro + " Informe o número.\n";
			}
			
			if($bairro==""){
				$msgErro = $msgErro + " Informe o bairro.\n";
			}
			if($estado==""){
				$msgErro = $msgErro + " Informe o estado.\n";
			}
			
			if($cidade==""){
				$msgErro = $msgErro + " Informe a cidade.\n";
			}
			if($("#promoCep1").val()=="" || $("#promoCep2").val()==""){
				$msgErro = $msgErro + " Informe o CEP.\n";
			}
		}

		if($senha==""){
			$msgErro = $msgErro + " Digite sua senha.\n";
		}

		if($msgErro==""){
			var $verifica = $.post('includes/verificaSenha.php',
				   {senha:$("#txtSenha").val(),email:$("#txtEmail").val()},
				   function(resposta){
						var $teste = resposta;
						if($teste==0){
							$("#promoMSGPart").show();
							$('#promoMSGPart').html("<b>Erro! A senha informada é inválida</b>");	
						}else if($teste==1){
								$.post('includes/gravaFrase.php',
									{ endereco:$("#endereco").val(),numero:$("#numero").val(),bairro:$("#bairro").val(),cidade:$("#cidades").val(),estado:$("#estados").val(),cep:$("#promoCep1").val()+"-"+$("#promoCep2").val(),frase : $("#promoResposta").val() , userid : $("#userid").val(), areaid : $("#promoid").val(), complemento: $("#complemento").val() },
										function($resposta){
											$teste = $resposta==true;
											$("#promoMSGPart").show();
											if($teste==false){
												$('#promoMSGPart').html("<b>Erro! Voc&ecirc; j&aacute; est&aacute; participando da promo&ccedil;&atilde;o</b>");
											}else{
												$(".menuPromocao li:eq(3)").hide();
												$("#div0").show();
												$("#div3").hide();
												$("#estouParticipando").show();
												alert("Participaçao recebida com sucesso!");												}
										}
									);
						}
				   }	
			);
		}
			
		if($msgErro!=""){
			alert("Erro(s) encontrado(s): \n\n " + $msgErro)	
		}
		
	});
	
	
	$("#btGravar2").click(function(){
							   
		var $msgErro="";
		
		if($("#promoResposta").val()==""){
			$msgErro = $msgErro + "Digite sua resposta antes de clicar em Participar. \n";
			$("#promoResposta").focus();
		}

		if($("#exibeEndereco").css('display')=='block'){
			$endereco 		= $("#endereco").val();
			$numero   		= $("#numero").val();
			$complemento   	= $("#complemento").val();
			$bairro   		= $("#bairro").val();
			$estado   		= $("#estados").val();
			$cidade   		= $("input[name=cidade]").val();
			
			$cep      		= $("#promoCep1").val()+"-"+$("#promoCep2").val();
			
			if($endereco==""){
				$msgErro = $msgErro + " Informe o seu endereço.\n";
			}
			if($numero==""){
				$msgErro = $msgErro + " Informe o número.\n";
			}
			
			if($bairro==""){
				$msgErro = $msgErro + " Informe o bairro.\n";
			}
			if($estado==""){
				$msgErro = $msgErro + " Informe o estado.\n";
			}
			if($cidade==""){
				$msgErro = $msgErro + " Informe a cidade.\n";
			}
			
			if($("#promoCep1").val()=="" || $("#promoCep2").val()==""){
				$msgErro = $msgErro + " Informe o CEP.\n";
			}
		}

		if($msgErro==""){
			
			if($("#exibeEndereco").css('display')=='block'){
				$.post('includes/gravaFrase.php',
					{ endereco:$("#endereco").val(),numero:$numero,bairro:$bairro,cidade:$cidade,estado:$estado,cep:$("#promoCep1").val()+"-"+$("#promoCep2").val(),frase : $("#promoResposta").val() , userid : $("#userid").val(), areaid : $("#promoid").val(), complemento: $("#complemento").val() },
						function($resposta){
							$teste = $resposta==true;
							$("#promoMSGPart").show();
							if($teste==false){
								$('#promoMSGPart').html("<b>Erro! Voc&ecirc; j&aacute; est&aacute; participando da promo&ccedil;&atilde;o</b>");
							}else{
								$(".menuPromocao li:eq(3)").hide();
								$("#div0").show();
								$("#div3").hide();
								$("#estouParticipando").show();
								alert("Participaçao recebida com sucesso!");	
								
								$("#endereco").val("");
								$("#numero").val("");
								$("#complemento").val("");
								$("#bairro").val("");
								$("#bairros").val("");
								$("#estados").val("");
								$("#cidades").val("");
								$("#promoCep1").val("")
								$("#promoCep2").val("");
								$("#promoResposta").val("")
							}
						}
					);
			}else{
				$.post('includes/gravaFrase.php',
					{ frase : $("#promoResposta").val() , userid : $("#userid").val(), areaid : $("#promoid").val() },
						function($resposta){
							$teste = $resposta==true;
							$("#promoMSGPart").show();
							if($teste==false){
								$('#promoMSGPart').html("<b>Erro! Voc&ecirc; j&aacute; est&aacute; participando da promo&ccedil;&atilde;o</b>");
							}else{
								$(".menuPromocao li:eq(3)").hide();
								$("#div0").show();
								$("#div3").hide();
								$("#estouParticipando").show();
								alert("Participaçao recebida com sucesso!");	
								$("#promoResposta").val("")
								}
						}
					);
			}
								
		}

		if($msgErro!=""){
			alert("Erro(s) encontrado(s): \n\n " + $msgErro)	
		}
	});

	$("#btfiqueporDentro").click(function(){
		var email = $("#txtfiqueporDentro").val();
		if(email=="" || email=="Seu email"){
			$("#divfiqueporDentro").show();
			$("#divfiqueporDentro").html("Por favor, informe seu email");
		}else{
			$("#divfiqueporDentro").html("Enviando...");
			$.post('fiquepordentro.php',
				   {email: $("#txtfiqueporDentro").val() },
				   		function(resposta){
							$("#divfiqueporDentro").html(resposta);
						}
			);
		}
	});
	
	// Grava o comentário do usuário.
	$('#btComentou').click(function(){
		var $msgE="";
		$areaid       = $("#jogoID").val();
		$nome       = $("#comentarioNome").val();
		$comentario = $("#comentarioJogo").val();
	
		if($nome=="Seu nome" || $nome==""){
			$msgE = "- Digite o seu nome \n";	
		}
		
		if($comentario=="Deixe seu comentário aqui..." || $comentario.length<5){
			$msgE = $msgE + "- Digite o comentário \n";	
		}
		
		if($msgE!=""){
			alert("Erro(s) encontrado(s):\n\n" + $msgE)	
		}else{
			$.post('includes/comentarJogo.php',
				   {nome:$("#comentarioNome").val(), comentario:$("#comentarioJogo").val(), areaid:$areaid},
				   function(resposta){
					  	alert('Seu comentário foi enviado com sucesso!')
				   }
			);
		}
	});
	
	// Habilita a votaçao em todas as divs que tenham a classe hover-star
	$('.hover-star').rating({
	  focus: function(value, link){
		var star = $(this);
		var idStar = $(this).attr("name").split("_");
		var tip = $('.voto-mensagem_' + idStar[1]);
		var texto = tip.html();
		tip.html(link.title || 'value: '+value);
	  },
	  blur: function(value, link){
		var star = $(this);
		var idStar = $(this).attr("name").split("_");
		var tip = $('.voto-mensagem_' + idStar[1]);
		tip.html("Avalia&ccedil;&atilde;o");
	  },
	  callback: function(value, link){
		var star = $(this);
		var idStar = $(this).attr("name").split("_");
		$.post('includes/jogos_votacao.php',
			   {idjogo:idStar[1],valor:value});
	  }
	 });

	// Habilita os comentarios
/*	$(document).ready(function(){
		$("#comentarios").tablesorter();
		$("#comentarios").tablesorterPager({pagesize:10,size:10, container: $("#pager")});
	});
*/
	// Habilita a paginacao do busca
	$(document).ready(function(){
		$("#busca").tablesorter();
		$("#busca").tablesorterPager({pagesize:20,size:20, container: $("#pager")});
	});

	// Habilita a paginacao
	$(document).ready(function(){
		$("#paginacao").tablesorter();
		$("#paginacao").tablesorterPager({pagesize:10,size:10, container: $("#controles")});
	});

	// Inicia o SlideShow da Sessao JOGOS
	var jogoRelacinadoIndice = 0;
	$('#setaDir').click(function(){
		if(jogoRelacinadoIndice<5){
			jogoRelacinadoIndice++;
		}
			var $c = $("#slideShowGames");
			$c.stop().scrollTo("#container ul li:eq("+jogoRelacinadoIndice+")", {speed:1500, easing:'elasout', axis:'x'});
	});

	$('#setaEsq').click(function(){
		if(jogoRelacinadoIndice>0){
			jogoRelacinadoIndice--;
		}
			var $c = $("#slideShowGames");
			$c.stop().scrollTo("#container ul li:eq("+jogoRelacinadoIndice+")", {speed:1500, easing:'elasout', axis:'x'});
	});

	$("#produtos .princOff").click(function(){
		$(".princOff").removeClass('princOn');
		$(this).addClass('princOn',function(){});
		$(".subprodutos").hide();
		$(this).next().show();
		
	});

	// Exibe o formulario da assinatura internacional
	$("#btAssinarExt").click(function(){
		$("#btAssinarExt").animate({width:0,height:0,opacity:0});
		$("#formAssinaturaInternaional").css({display:'block',opacity:0});
		$("#formAssinaturaInternaional").fadeTo('slow',1);
	});

	$("#presente").click(function(){
		if(this.checked){
			$("#formularioAssinaturaPresente").css({display:'block',opacity:0});
			$("#formularioAssinaturaPresente").fadeTo('slow',1);
		}else{
			$("#formularioAssinaturaPresente").fadeTo('slow',0,function(){
																  $("#formularioAssinaturaPresente").css({display:'none'});	
															   });
		}
	});

	$("#chkAceite").click(function(){
		if(this.checked){
			$("#btJornaisContinuar").css({display:'block',opacity:0});
			$("#btJornaisContinuar").fadeTo('slow',1);
		}else{
			$("#btJornaisContinuar").fadeTo('slow',0,function(){
																  $("#btJornaisContinuar").css({display:'none'});	
															   });
		}
	});

	$("#sltPeridiocidade").change(function(){
		var id = $(this).val();
		$("#peridiocidadeTable").show();
		// Mensal
		if(id==1){
			$(".peridiocidadeTitulo:eq(0)").html("1o mes");
			$(".peridiocidadeTitulo:eq(1)").html("2o mes");
			$(".peridiocidadeTitulo:eq(2)").html("3o mes");
			$(".peridiocidadeTitulo:eq(3)").html("4o mes");
			$(".peridiocidadeTitulo:eq(4)").html("5o mes");
			$(".peridiocidadeTitulo:eq(5)").html("6o mes");
			$(".periodicidade").css({opacity:0,display:"none"});
			$("#divMensal").css({opacity:0,display:"block"});
			$("#divMensal").fadeTo('normal',1);
		}
		if(id==2){
			$(".periodicidade").css({opacity:0,display:"none"});
			$("#divSemanal").css({opacity:0,display:"block"});
			$("#divSemanal").fadeTo('normal',1);
		}
		if(id==3){
			$(".periodicidade").css({opacity:0,display:"none"});
			$("#divQuinzenal").css({opacity:0,display:"block"});
			$("#divQuinzenal").fadeTo('normal',1);
		}
		// Diario
		if(id==4){
			$(".peridiocidadeTitulo:eq(0)").html("1o sem");
			$(".peridiocidadeTitulo:eq(1)").html("2o sem");
			$(".peridiocidadeTitulo:eq(2)").html("3o sem");
			$(".peridiocidadeTitulo:eq(3)").html("4o sem");
			$(".peridiocidadeTitulo:eq(4)").html("5o sem");
			$("#peridiocidadeTable tr:[0-5] td:eq(5)").hide();
			$(".periodicidade").css({opacity:0,display:"none"});
			$("#divDiario").css({opacity:0,display:"block"});
			$("#divDiario").fadeTo('normal',1);
		}
		if(id==5){
			$(".periodicidade").css({opacity:0,display:"none"});
			$("#divBimestral").css({opacity:0,display:"block"});
			$("#divBimestral").fadeTo('normal',1);
		}
		if(id==6){
			$(".periodicidade").css({opacity:0,display:"none"});
			$("#divBisemanal").css({opacity:0,display:"block"});
			$("#divBisemanal").fadeTo('normal',1);
		}
		if(id==8){
			$(".periodicidade").css({opacity:0,display:"none"});
			$("#divTrisemanal").css({opacity:0,display:"block"});
			$("#divTrisemanal").fadeTo('normal',1);
		}
	});
	
	$(".btRenovar").click(function(){
		$("#btAssinaturaNac").attr({src:'imagens/bt_renovar_por_1_ano.png'});
		$("#btAssinaturaInt").attr({src:'imagens/bt_renovar_por_2_anos.png'});
	});
	
	$(".numberPage").click(function(){
			
			$paginas   = ($(".numberPage").length);
			$atual     = ($(".numberPage").index(this));
			$porpagina = 8;
			
			if(($atual%$porpagina)==7){
				for($k=0;$k<(($atual+1)-($porpagina));$k++){
					$(".numberPage:eq("+$k+")").css({display:'none'});
				}
				
				for($k=(($atual)-($porpagina));$k<=(($atual+1)+($porpagina));$k++){
						$(".numberPage:eq("+$k+")").css({display:'inline-block'});
				}
				
				for($k=(($atual+1)+($porpagina));$k<=$paginas;$k++){
						$(".numberPage:eq("+$k+")").css({display:'none'});
				}
			}
			
	});
});

function initToolTip() {
	// Exibe o tooltip na pagina de jogos
	$('.showTooltip').tooltip({
		track: true,
		delay: 0,
		showURL: false,
		fixPNG: true,
		left: 10,
		top:10,
		bodyHandler:function(){
			var tooltip = $(this).attr("id").split("_");
			return $("#tooltip_"+tooltip[1]).html();
		}
	});
}

function validaBuscaJogos(){
	form = document.buscaJogos
	nome = form.nome.value
	categoria = form.categorias.value
	nivel = form.nivel.value
	
	/*if((nome=="" || nome=="Nome do jogo")){
		alert('Digite o nome do jogo que deseja buscar');
		form.nome.focus();
		return false;
	}*/
	form.submit()
}

function Trim(str){return str.replace(/^\s+|\s+$/g,"");}


function validaComentario(form){
	nome = form.nome
	comentario = form.comentario
	if(nome.value=="" || Trim(nome.value)=='Seu nome'){
		nome.value='';
		alert("Informe seu nome");
		nome.focus();
		return false;
	}

	if(comentario.value=="" || comentario.value=="Deixe seu comentário aqui..."){
		alert("Digite o comentário");
		comentario.focus()
		return false;
	}
	form.submit();
}

function validaIndique(form){
	nome = form.nome
	email = form.email
	nomeamigo = form.nomeamigo
	emailamigo = form.emailamigo
	
	if(nome.value=="" || nome.value=='Seu nome'){
		alert("Informe seu nome");
		nome.focus();
		return false;
	}
	if(email.value=="" || email.value=='Seu email'){
		alert("Informe seu email");
		email.focus();
		return false;
	}
	if(nomeamigo.value=="" || nomeamigo.value=='Nome do amigo'){
		alert("Nome do amigo");
		nomeamigo.focus();
		return false;
	}
	if(emailamigo.value=="" || emailamigo.value=='Email do amigo'){
		alert("Email do amigo");
		emailamigo.focus();
		return false;
	}
	form.submit();
}


