var votedID;

$(document).ready(function(){
  $("#poll").submit(formProcess); // setup the submit handler
  
  var poll_id = $("#poll_id").attr("value");
  poll_id = poll_id.replace("poll",'');
  
  if ($("#poll-results").length > 0 ) {
    animateResults();
  }
  /**
  if ($.cookie('poll_id') == poll_id) {
    $("#poll-container").empty();
    //votedID = $.cookie('option_id');
	
	$.ajax({
		type: "POST",
		url: "/ajax_cont/poll_return_results/",
		data: "poll_id="+poll_id,
		dataType: "json",
		success: function(msg){
			loadResults(msg);
	   }
	});
	
  }
  **/
});

function formProcess(event){
  event.preventDefault();
  
  var option_id = $("input[@name='poll']:checked").attr("value");
  option_id = option_id.replace("opt",'');
  var poll_id = $("#poll_id").attr("value");
  poll_id = poll_id.replace("poll",'');
  $("#poll-container").fadeOut("slow",function(){
    $(this).empty();
    
    votedID = option_id;
	$.ajax({
		type: "POST",
		url: "/ajax_cont/vote/",
		data: "option_id="+option_id+"&poll_id="+poll_id,
		dataType: "json",
		success: function(msg){
			if(msg.error){
				alert(msg.error);
			}
			loadResults(msg);
	   }
	});
    
    $.cookie('poll_id', poll_id, {expires: 365});
    });
}

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 = data.allVotes;
  var options = data.options;
  var results_html = "<div id='poll-results'><h3 style='color: #cc0000;'>Poll Results</h3>\n<dl class='graph'>\n";
  
  for ( i = 0; i < options.length; i++) {
    percent = Math.round((parseInt(options[i]['votes'])/parseInt(total_votes))*100);
    if (options[i]["options"] !== votedID) {
      results_html = results_html+"<dt class='bar-title'>"+options[i]["title"]+"</dt><dd class='bar-container'><div id='bar"+options[i]['votes']+"'style='width:0%;'>&nbsp;</div><strong>"+percent+"%</strong></dd>\n";
    } else {
      results_html = results_html+"<dt class='bar-title'>"+options[i]["title"]+"</dt><dd class='bar-container'><div id='bar"+options[i]['votes']+"'style='width:0%;background-color:#0066cc;'>&nbsp;</div><strong>"+percent+"%</strong></dd>\n";
    }
  }
  
  
  results_html = results_html+"</dl><p>Total Votes: "+total_votes+"</p></div>\n";
  
  $("#poll-container").append(results_html).fadeIn("slow",function(){
    animateResults();});
}