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

var votedID = Array();



function pollFormProcess(postId) {
	var id = $("input[@name='poll']:checked").attr("value");
	  
	votedID[postId] = id;
	  
	$("#poll-container_" + postId).fadeOut("slow",function() {
		
		$(this).empty();
		
		$.getJSON("/blogs/poll/vote/" + id, loadResults);
	
	});
}

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

function animateResults(postId){
	  $("#poll-results_" + postId + " 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 postId;
  
  for (id in data) {
    total_votes = total_votes+parseInt(data[id].OPT_VOTES);
    postId = parseInt(data[id].POST_ID);
  }
  
  var results_html = "<table cellpadding='0' cellspacing='0' class='graph' id='poll-results_" + postId + "'>\n\n";
//  var results_html = "<div id='poll-results_" + postId + "'>\n<dl class='graph'>\n";
  for (id in data) {
    percent = Math.round((parseInt(data[id].OPT_VOTES)/parseInt(total_votes))*100);
    
    if (data[id].OPT_ID != votedID[postId])
    	results_html = results_html+"<tr><td class='bar-title'>"+data[id].OPT_TITLE+"</td><td class='bar-container'><div id='bar"+data[id].OPT_ID+"'style='width:0%;'>&nbsp;</div><span style='visibility: hidden;'>"+percent+"</span></td><td><strong>"+percent+"%</strong></td></tr>\n";
    else
    	results_html = results_html+"<tr><td class='bar-title'>"+data[id].OPT_TITLE+"</td><td class='bar-container'><div id='bar"+data[id].OPT_ID+"'style='width:0%;background-color:#00802a;'>&nbsp;</div><span style='visibility: hidden;'>"+percent+"</span></td><td><strong>"+percent+"%</strong></td></tr>\n";
    
//    if (data[id].OPT_ID != votedID[postId]) {
//      results_html = results_html+"<dt class='bar-title'>"+data[id].OPT_TITLE+"</dt><dd class='bar-container'><div id='bar"+data[id].OPT_ID+"'style='width:0%;'>&nbsp;</div><strong>"+percent+"%</strong></dd>\n";
//    } else {
//      results_html = results_html+"<dt class='bar-title'>"+data[id].OPT_TITLE+"</dt><dd class='bar-container'><div id='bar"+data[id].OPT_ID+"'style='width:0%;background-color:#00802a;'>&nbsp;</div><strong>"+percent+"%</strong></dd>\n";
//    }
  }
  
  results_html = results_html+"</table><p>Всего проголосовало: "+total_votes+"</p></div>\n";
//  results_html = results_html+"</dl><br clear=\"all\" /><p>Всего проголосовало: "+total_votes+"</p></div>\n";
  
  $("#poll-container_" + postId).append(results_html).fadeIn("slow",function(){
    animateResults(postId);});
}