// Global variable definitions
// DB column numbers
var OPT_ID = 0;
var OPT_TITLE = 1;
var OPT_VOTES = 2;

var cookiename = $.ajax({url: "/poll/get_cookiename.php", async: false}).responseText;

var votedID;

$(document).ready(function(){
	$("#poll").submit(formProcess); // setup the submit handler
	
	if ($("#poll-results").length > 0 ) {
	animateResults();
	}
	
	if ($.cookie(cookiename)) {
		$("#poll-container").empty();
		votedID = $.cookie(cookiename);
		$.getJSON("/poll.php?vote=none", loadResults);
	}
});

function formProcess(event){
	event.preventDefault();
  
	var id = $("input[@name='poll']:checked").attr("value");
	id = id.replace("opt", '');
  
	$("#poll-container").fadeOut("slow", function(){
		$(this).empty();
		
		votedID = id;
		$.getJSON("/poll.php?vote="+id, loadResults);
		
		$.cookie(cookiename, id, {path: '/', expires: 7});
	});
}

function animateResults(){
	$("#poll-results div").each(function(){
		var percentage = $(this).next().text();
		if (parseInt(percentage) == 0) percentage = 1+"%";
		$(this).css({width: "0%"}).animate({width: percentage}, 'slow');
	});
}


function loadResults(data) {
	var total_votes = 0;
	var percent;

	for (id in data) {
		if (!isNaN(parseInt(data[id][OPT_VOTES])))
			total_votes = total_votes+parseInt(data[id][OPT_VOTES]);
	}

	var results_html = "<div id='poll-results'><!--<h3>Výsledky</h3>-->\n<dl class='graph'>\n";
	for (id in data) {
		var votes = parseInt(data[id][OPT_VOTES]);
		if (isNaN(votes))
			percent = 0;
		else
			percent = Math.round((votes/parseInt(total_votes))*100);
		if (data[id][OPT_ID] !== votedID) {
			results_html = results_html+"<dt class='bar-title'>"+data[id][OPT_TITLE]+"</dt><dd class='bar-container'><div id='bar"+data[id][OPT_ID]+"'style='width:0%;'>&nbsp;</div><strong>"+percent+"%</strong></dd>\n";
		} else {
			results_html = results_html+"<dt class='bar-title'>"+data[id][OPT_TITLE]+"</dt><dd class='bar-container'><div id='bar"+data[id][OPT_ID]+"'style='width:0%;background-color:#002F54;'>&nbsp;</div><strong>"+percent+"%</strong></dd>\n";
		}
	}

	results_html = results_html+"</dl><p>Total Votes: "+total_votes+"</p></div>\n";

	$("#poll-container").append(results_html).fadeIn("slow",function(){
		animateResults();});
}
