﻿var votedID;

$(document).ready(function(){
  if ($("#ctl00_SideStrip1_Poll_autoSubmit").val()=='1') {
	$(".poll-container").hide();
    formProcess('99');
  }
  else
	$(".poll-container").show();
  
  $(".btnPoll").click(function(){
	formProcess($("input[@name='ctl00$SideStrip1$Poll$rdoAnswer']:checked").attr("value"));
  }); 
  
  if ($.cookie('poll' + $("#ctl00_SideStrip1_Poll_PollNo").val())) {
    $(".poll-container").empty();
    votedID = $.cookie('poll' + $("#ctl00_SideStrip1_Poll_PollNo").val());
    formProcess('99');
  }
});

function formProcess(id){
	$.ajax({
		  type: "POST",
		  url: "ViewPolls.aspx/CastVoteFromWeb",
		  data: "{'id':'" + id + "', 'PollNo':'" + $("#ctl00_SideStrip1_Poll_PollNo").val() + "'}",
		  contentType: "application/json; charset=utf-8",
		  dataType: "json",
		  success: function(msg) {
			$(".poll-container").fadeOut("slow",function(){
				$(this).empty();
                if(id!='99'){
                    votedID = id;
				    $.cookie('poll' + $("#ctl00_SideStrip1_Poll_PollNo").val(), id, {expires: 365});
				}
				loadResults($.evalJSON(msg));                
			});       
		  }
	});	
}

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