// Global variable definitions

var votedID;

$(document).ready(function(){ 
  $("#poll").submit(formProcess); // setup the submit handler

 if ($("#poll-results").length > 0 ) {
    animateResults();
  }
/*
 if ($.cookie('votepoll') && $.cookie('votepoll')==pid) {
    $("#poll-container").empty();
    $.getJSON("poll.php?vote=none",loadResults);
 
   	}
*/
});

function formProcess(event){
  event.preventDefault();

  var id = $("input[@name='poll']:checked").attr("value");

  if(!id) {
  	 $.getJSON("poll.php");
  }
  $("#poll-container").fadeOut("slow",function(){
    $(this).empty();
    
    votedID = id;
    $.getJSON("poll.php?vote="+id+"&poll_id="+pid,loadResults);
    
    });

}

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

function loadResults(data) {
	
  var total_votes = 0;
  var percent;
  
  for (id in data['rows']) {
    total_votes = total_votes+parseInt(data['rows'][id]['count']);
  }
  
  var results_html = "<div id='poll-results'><h3>"+data['name']+"</h3>\n<dl class='graph'>\n";
  for (id in data['rows']) {
    percent = Math.round((parseInt(data['rows'][id]['count'])/parseInt(total_votes))*100);
    if (data['rows'][id]['id'] !== votedID) {
      results_html = results_html+"<dt class='bar-title'>"+data['rows'][id]['question']+"</dt><dd class='bar-container'><div id='bar"+data['rows'][id]['id']+"'style='width:0%;'>&nbsp;</div><strong>"+percent+"%</strong></dd>\n";
    } else {
      results_html = results_html+"<dt class='bar-title'>"+data['rows'][id]['question']+"</dt><dd class='bar-container'><div id='bar"+data['rows'][id]['id']+"'style='width:0%;'>&nbsp;</div><strong>"+percent+"%</strong></dd>\n";
    }
  }
  
  results_html = results_html+"</dl><p class='clear'>Брой гласували: "+total_votes+"</p></div>\n";
  
  $("#poll-container").append(results_html).fadeIn("slow",function(){
   animateResults();});
}
