var slide = 2;

$().ready(function() {
	$.ajax({
		type: "GET",
		url: "user",
		cache: false,
		dataType: "json",
		success: function(data) {
			if (data.you.mac || data.you.win) {
				if ((data.you.mac + data.you.win) == 16) {
					$('p.uvod,nav').slideUp();
					stats();
				}
			}
		}
	});		
				
	$('nav').show(0);
	$('section,p.zaver,.choice').hide(0);
	$('body').live("click", function(event) {
		li = $(event.target).parent();
		if (li.hasClass("continue")) {
			$('p.uvod,.stats').slideUp("slow");
			$('section:nth-child(2)').slideDown();
			$('.continue').fadeOut("slow");
			$('.choice').fadeIn("slow");
		} else if (li.hasClass("stats")) {
			$("p.uvod").slideUp();
			$("p.zaver").after('<img src="./images/loading.gif" id="loadinfo">');
			stats();
			$("nav").slideUp();
		} else if (li.hasClass("choice")) {
			if (slide==17) {
				$('section:nth-child('+slide+'),.choice').slideUp("slow");
				$("p.zaver").slideDown("slow").after('<img src="./images/loading.gif" id="loadinfo">');
				slide++;
			} else {
				$('section:nth-child('+slide+')').slideUp();
				slide++;
				$('section:nth-child('+slide+')').slideDown();
			}
			
			os = 1;
			if (li.hasClass("win")) {
				os = 2;
			}
			$('<img src="./images/loading.gif" id="load'+(slide-2)+'">').appendTo("#loading");
			$.post("hlasuj", {slide:slide-2,os:os}, function(slide) {
				if (slide) {
					$("#load"+slide).slideUp("slow");
				}
			});
			if (slide==18) {
				stats();
			}
		}
	});
});

function stats() {
	$.ajax({
		type: "GET",
		url: "user",
		cache: false,
		dataType: "json",
		success: function(data) {
			if (data.you.mac || data.you.win) {
				me = data.you;
				if (me.win > me.mac) {
					like = "Windows";
				} else {
					like = "Mac";
				}
				
				$("p.zaver").after("<div id=\"info\"><p id='like'>"+((me.mac==me.win)?"Oba systémy se vám líbí stejně. <a href=\"tweet\">Tweetnout!</a>":"Více se vám líbí <b>"+like+"</b>. <a href=\"tweet\">Tweetnout!</a> Vaše skóre: </p><p id='score'>"+me.mac+":"+me.win)+"</p></div>");
			} else {
				$("p.zaver").after("<div id=\"info\"></div>");
			}
			
			$('#info').after("<h4>Celková statistika</h4><table><tr><th>Mac</th><th></th><th>Windows</th></tr></table>");
			
			tabulka = "";
			mac = win = 0;
			for (i=0; i<16; i++) {
				mac+= data.all[i].mac;
				win+= data.all[i].win;
				tabulka = tabulka+"<tr><td>"+(data.all[i].mac)+"</td><th>"+($("section:nth-child("+(i+2)+")").find("h3").text())+"</th><td>"+(data.all[i].win)+"</td></tr>"
			}
			$("tr").after(tabulka);
			$('table').after("<p class='summary'>Vyhrává <b>"+((mac>win)?"Mac":"Windows")+"</b>!<br>"+mac+":"+win+"</p>");
			$("#loadinfo").fadeOut();
		}
	});
}
