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

var votedID;

$(document).ready(function(){
  
  if ($("#poll-results").length > 0 ) {
    animateResults();
  }
  $("#poll-container").empty();
  votedID = $.cookie('vote_id');
  $.getJSON("/anketa/vysledky",loadResults);
  
  
});

function formProcess(event){
  event.preventDefault();
  var href = $(this).attr("href");
  $("#poll-container").fadeOut("slow",function(){
	$(this).empty();
    $.getJSON(href,loadResults);
    $.cookie('vote_id', id, {expires: 365});
   });
}

function animateResults(){
  $("#poll-results div").each(function(){
      var percentage = $(this).next().text();
      $(this).css({width: "0%"}).animate({
				width: percentage}, 2000);
  });
  $("a.volRef").click(formProcess);
}

function loadResults(data) {
  var total_votes = 0;
  var percent;
  
  for (id in data) {
    total_votes = total_votes+parseInt(data[id]['volba']);
  }
  var odkazy = !($.cookie('vote_id'));
  var results_html = "<div id='poll-results'><dl class='graph'>\n";
  
  for (id in data) {
	percent = Math.round((parseInt(data[id]['volba'])/parseInt(total_votes))*100);
    results_html = results_html+"<dt class='bar-title"+(data[id]['id']== votedID?" current":"")+"'>"+(odkazy?"<a class=\"volRef\" href=\"/anketa/volba/id/"+data[id]['id']+"\">":"")+data[id]['otazka']+(odkazy?"</a>":"")+"</dt><dd class='bar-container'><div id='bar"+data[id]['id']+"'style='width:0%;'>&nbsp;</div><strong>"+percent+"%</strong></dd>\n";
  }
  
  results_html = results_html+"</dl></div>\n" ;
  
  $("#poll-container").append(results_html).fadeIn(1000,function(){
    animateResults();});
}
