var pollVotedID;
var pollUrl = ''

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

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

  var quest_id = $("input[@name='questionid']").attr("value");
  
  if ($.cookie('vote_id') && quest_id==$.cookie('quest_id') ) 
  {
    showVoteResults();
  }
});

function showVoteResults()
{
    $("#poll-container").empty();
    pollVotedID = $.cookie('vote_id');
    $.getJSON(pollUrl+"index.php?cl=start&fnc=ajax_getresults&pollid="+$.cookie('quest_id'),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("slow",function(){
    $(this).empty();
    
    pollVotedID = id;
    $.getJSON(pollUrl+"index.php?cl=start&fnc=vote&calltype=ajax&vote="+id+"&pollid="+quest_id,loadVoteResults);
    
    $.cookie('vote_id', id, {expires: 365, path: '/shop/'});
   	$.cookie('quest_id', quest_id, {expires: 365, path: '/shop/'});
  });
}

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) {
    total_votes = total_votes+parseInt(data[id]['COUNTER']);
  }
  
  var results_html = "<div id='poll-results'><dl class='graph'>\n";
  for (id in data) {
    percent = Math.round((parseInt(data[id]['COUNTER'])/parseInt(total_votes))*100);
    if (isNaN(percent)) percent = 0;
    if (data[id]['OXID'] !== pollVotedID) {
      results_html = results_html+"<dt class='bar-title'>"+data[id]['OXANSWER']+" <i>("+percent+"%)</i></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]['OXANSWER']+" <i>("+percent+"%)</i></dt><dd class='bar-container'><div id='bar"+(id+1)+"'style='width:0%;'>&nbsp;</div><strong>"+percent+"%</strong></dd>\n";
    }
  }
  results_html = results_html+"</dl><p class='clearFix'></p></div>\n";
  
  $("#poll-container").append(results_html).fadeIn("slow",function(){
    animateVoteResults();});
}