$(document).ready(function() {
	
	$("div.preloader").css("display", "none");
	
	var pergAtualC = $.cookie("pergAtual");
	var pergAtual = $.getURLParam("perg");
	var qtdPerg = parseInt($("#qtdPerguntas").text());
	var totalLetras = $.cookie("totalLetras");
	var resultado = false;

	/*
	 * Se não marcar a pergunta Zera
	 */
	if (pergAtual == null && qtdPerg != parseInt(pergAtual)) {
		
		pergAtual = 0;
		totalLetras = new String('');
		$.cookie("totalLetras", null);
	}
	else {
		pergAtual = parseInt(pergAtual);
		pergAtualC = parseInt(pergAtualC);
		
		if(pergAtual == qtdPerg) resultado = true;
		
		if(pergAtual != pergAtualC) window.location = window.location.pathname;
	}
	
	if (!resultado) {
		/**
		 * Mostra a Pergunta e coloca as ações
		 */
		$("dl.testeLista:eq(0)").find("a.aResposta").each(function(i){
		
			var valor = $(this).attr('rel');
			
			// URL para Proxima pergunta
			var urlPergunta =  window.location.pathname + "?perg=" + (pergAtual + 1);
			
			// Para o Click do A
			$(this).click(function(e) {
				e.preventDefault();
			});
			
			// Click no DD
			$(this).parent().parent().click(function(e) {

				// Coloca o total
				var valorNovo = valor;
				if(totalLetras != '') valorNovo = '|'+ valor;
				$.cookie("totalLetras", totalLetras + valorNovo);
				
				// Check se não é a ultima Pergunta
				$.cookie("pergAtual", (pergAtual + 1));
				
				window.location = urlPergunta;
			});			
		});
		
		$("dl.testeLista:eq(0)").fadeIn("def");
		
		// Contador
		$("p.contador").css("display", "block");
		$("p.contador").html((pergAtual+1)+" de "+qtdPerg);
	}
	// RESULTADO
	else {
		// Limpa
		$.cookie("pergAtual", null);
		$.cookie("totalLetras", null);
		$("p.contador").css("display", "none");
		
		/*
		 * Calcula o Resultado de Maioria
		 */
		totalLetras = totalLetras.split('|');
		
		// Mapeia as repetições
		var resultLetra = new Object();
		jQuery.each(totalLetras, function (i, letra) {
			if (!eval("resultLetra."+ letra)) {
				eval("resultLetra."+ letra +" = 0");
			}
			eval("resultLetra."+ letra +" += 1");
		});
		
		// Procura o Maior
		var maior = 0;
		jQuery.each(resultLetra, function (letra, valor) {
			if(valor > maior)
			{
				maior = valor;
			}
		});
		// Agora checa se tem mais algum com o mesmo valor
		var resultados = new Array();
		jQuery.each(resultLetra, function (letra, valor) {
			if(valor == maior)
			{
				resultados.push(letra);
			}
		});
		
		// Mostra os resultados
		$("dd.resultado_txt").each(function (i) {
			var letra = $(this).attr('rel');
			// Mostra
			if(jQuery.inArray(letra, resultados) != -1)
			{
				$(this).fadeIn("def");
				$("dt.resultado").fadeIn("def");
			}
		});
	}
});
