var pollVotedID;

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

  if ($.cookie('vote_results_height'))
  {
      $("#poll-container").css({'height': $.cookie('vote_results_height')+'px'});
  }

  if ($("#poll-results").length > 0 ) {
    animateVoteResults();
  }

  var quest_id = $("input[name='questionid']").attr("value");

  if ($.cookie('vote_id') && quest_id==$.cookie('quest_id') ) {
      $('#poll').hide();
      showVoteResults();
  }
  else
  {
      $('#poll').show();
  }
});

function showVoteResults(){
    $("#poll-container").empty();
    pollVotedID = $.cookie('vote_id');
    $.getJSON("index.php?cl=start&fnc=ajax_getresults",loadVoteResults);
}

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

  var id = $("input[name='vote']:checked").attr("value");
  var quest_id = $("input[name='questionid']").attr("value");

  $("#poll-container").fadeOut("fast",function(){
    $(this).empty();

    pollVotedID = id;
    $.getJSON("index.php?cl=start&fnc=vote&calltype=ajax&vote="+id,loadVoteResults);

    $.cookie('vote_id', id, {expires: 365});
    $.cookie('quest_id', quest_id, {expires: 365});
    $.cookie('vote_results_height', null, {expires: 365});
  });
}

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

function loadVoteResults(data) {

  var total_votes = 0;
  var percent;

  for (id in data) {
      if (data[id]['OXCOUNTER'] !== undefined) {
          total_votes = total_votes + parseInt(data[id]['OXCOUNTER']);
      }
  }
  var results_html = "<div id='poll-results'>\n<dl class='graph clear'>\n";
    for (id in data) {
        if (data[id]['OXCOUNTER'] !== undefined) {
            percent = Math.round((parseInt(data[id]['OXCOUNTER']) / parseInt(total_votes)) * 100);
            if (isNaN(percent))
                percent = 0;
            if (data[id]['OXID'] !== pollVotedID) {
                results_html = results_html + "<dt class='bar-title'>" + data[id]['OXTITLE'] + "</dt><dd class='bar-container'><div id='bar" + (id + 1) + "'style='width:0%;'>&nbsp;</div><strong>" + percent + "%</strong></dd>\n";
            }
            else {
                results_html = results_html + "<dt class='bar-title'>" + data[id]['OXTITLE'] + "</dt><dd class='bar-container'><div id='bar" + (id + 1) + "'style='width:0%;' class='personalVote'>&nbsp;</div><strong>" + percent + "%</strong></dd>\n";
            }
        }
    }

    results_html = results_html + "</dl><p class='totalVotes'>" + POLL_TOTALVOTES + " " + total_votes + "</p></div>\n";
  $("#poll-container").html(results_html).fadeIn("slow",function()
  {
    animateVoteResults();
  });
  
  }
$(function(){
     $("#poll-container").css({'height': 'auto'});
     $.cookie('vote_results_height', $("#poll-container").height(), {expires: 365});
});

