var OPT_ID = 0;
var OPT_TITLE = 1;
var OPT_VOTES = 2;
var OPT_ARTIST = 3;

var votedID;

$(document).ready(function(){
						   
  $("#poll").submit(formProcess);
  
  if ($("#poll-results").length > 0 ) {
    animateResults();
  }
  
  if ($.cookie('vote_id')) {
    /* $("#poll-container").empty(); */
    votedID = $.cookie('vote_id');
    /* $.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("normal",function(){

    $(this).empty();
    
    votedID = id;
    $.getJSON("/poll.php?vote="+id,loadResults);

    $.cookie('vote_id', id, {expires: 1});
    });
}

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) {
	if(data[id][OPT_VOTES] != 0){
		total_votes = total_votes+parseInt(data[id][OPT_VOTES]);
	}
  }
  
  var results_html = "<div id='poll-results'><h3>Резултат</h3>\n<dl class='graph'>\n";
  for (id in data) {
	if(data[id][OPT_VOTES] == 0){
		percent = 0;
	}else{
		percent = Math.round((parseInt(data[id][OPT_VOTES])/parseInt(total_votes))*100);
    }
	if (data[id][OPT_ID] !== votedID) {
      results_html = results_html+"<dt class='bar-title'><strong>"+data[id][OPT_ARTIST]+"</strong> - "+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' style='color:#ffab00;'><strong>"+data[id][OPT_ARTIST]+"</strong> - "+data[id][OPT_TITLE]+"</dt><dd class='bar-container'><div id='bar"+data[id][OPT_ID]+"'style='width:0%;background-color:#ffab00;'>&nbsp;</div><strong>"+percent+"%</strong></dd>\n";
    }
  }
  
  results_html = results_html+"</dl></div>\n";
  
  $("#poll-container").append(results_html).fadeIn("normal",function(){
    animateResults();});
}
