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

var votedID;

$(document).ready(function(){
  $("#poll").submit(formProcess); // setup the submit handler
  
  if ($("#poll-results").length > 0 ) {
    animateResults();
  }
  
  if ($.cookie('vote_id')) {
    $("#poll-container").empty();
    votedID = $.cookie('vote_id');


   /*$.getJSON("php/poll.php?vote=9",loadResults);*/

  results_html = "Voto efetuado. Obrigado pela sua participação!\n";
  
  $("#poll-container").append(results_html).fadeIn("slow");

  }
});

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("php/poll.php?vote="+id,loadResults);
  
    $.cookie('vote_id', id, {expires: 0});
    });
}

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;
  var maior = 0;
  data = data.split(";"); 

  for (i=0; i<4; i++) {
    total_votes = total_votes+parseInt(data[i]);
    if(parseInt(data[i])>maior)
      maior = parseInt(data[i]);
  }


  opcoes = ["Não tenho interesse","São mal divulgadas","Outras prioridades","Sempre Participei"];  

  var results_html = "<p style='color: #666; border-bottom: 1px solid; font-weight: bold;'>Resultado Parcial:</p><div id='poll-results'><dl class='graph'>";
  for (i=0; i<4; i++) {
    percent = Math.round((parseInt(data[i])/parseInt(total_votes))*100);
    if (data[i] == maior) {
      results_html = results_html+"<dt class='bar-title'>"+opcoes[i]+"</dt><dd class='bar-container'><div id='bar"+data[i]+"'style='width:0%;'>&nbsp;</div><strong>"+percent+"%</strong></dd>\n";
    } else {
      results_html = results_html+"<dt class='bar-title'>"+opcoes[i]+"</dt><dd class='bar-container'><div id='bar"+data[i]+"'style='width:0%;background-color:#0066cc;'>&nbsp;</div><strong>"+percent+"%</strong></dd>\n";
    }
  }
  
  results_html = results_html+"</dl></div><p style='border-top: 1px dashed #666;'>Total: "+total_votes+" votos</p><br/>\n";
  
  $("#poll-container").append(results_html).fadeIn("slow",function(){
    animateResults();});
}
