// Global variable definitions
// DB column numbers
jQuery.noConflict();
var OPT_ID = 0;
var OPT_TITLE = 1;
var OPT_VOTES = 2;
var noOfOptions=5;//stores the no. of options in the poll
var votedID;
//alert("hello");

jQuery(document).ready(function(){
  jQuery("#poll").submit(formProcess); // setup the submit handler
  
  if (jQuery("#poll-results").length > 0 ) {
  
    animateResults();
  }
  
  if (jQuery.cookie('vote_id')) {
  //alert("hello1");
    jQuery("#poll-container").empty();
    votedID = jQuery.cookie('vote_id');
	
    jQuery.getJSON("poll.php?vote=none",loadResults);
  }
});

function formProcess(event){
  event.preventDefault();
  
  var id = jQuery("input[@name='poll']:checked").attr("value");
  id = id.replace("opt",'');
  
  jQuery("#poll-container").fadeOut("slow",function(){
    jQuery(this).empty();
    
    votedID = id;
    jQuery.getJSON("poll.php?vote="+id,loadResults);
    
    jQuery.cookie('vote_id', id, {expires: 365});
    });
}

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

function loadResults(data) {
	
  var total_votes = 0;
  var percent;
  var id=0;
  //alert(noOfOptions);
  while(id<noOfOptions)
  {
		//alert(id);

    total_votes = total_votes+parseInt(data[id][OPT_VOTES]);
	//alert(parseInt(data[id][OPT_VOTES]));
	id++;
  }
  id=0;
  	//alert(id);

  var results_html = "<div id='poll-results'><h3>Which was the toughest event in Kshitij 2009?</h3>\n<dl class='graph'>\n";
  for (id=0;id<noOfOptions;id++) 
  {
    percent = Math.round((parseInt(data[id][OPT_VOTES])/parseInt(total_votes))*100);
	//alert(percent);
    if (data[id][OPT_ID] !== votedID) {
      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:#0066cc;'>&nbsp;</div><strong>"+percent+"%</strong></dd>\n";
    }
  }
  
  results_html = results_html+"</dl><p style='margin-top:10px;'>Total Votes: "+total_votes+"</p></div>\n";
  
  jQuery("#poll-container").append(results_html).fadeIn("slow",function(){
    animateResults();});
}
