// Global variable definitions
// DB column numbers
var OPT_ID = 0;
var OPT_TITLE = 1;
var OPT_VOTES = 2;
var QUESTION_ID;
var votedID;
var ipcheck;
 $("#poll-container").animate({"opacity" : 0},0);
 //$("#poll").animate({"opacity" : 0},0);
$(document).ready(function(){
  $("#poll").append(QUESTION_ID);
  $("#poll").submit(formProcess); // setup the submit handler
  $.get("http://www.fwusy.net/poll/data/question.php", function(data){
  var arraydata=data.split("|");
  QUESTION_ID=arraydata[0];
  ipcheck=arraydata[1];
  
  $("#poll_question").append(QUESTION_ID);
  if ($("#poll-results").length > 0 ) {
  
    animateResults();
  }
  if ($.cookie('vote_id') && ($.cookie('question_id') && QUESTION_ID==$.cookie('question_id')) || (ipcheck=="novoteallow"))
  { 
  votedID = $.cookie('vote_id');
    $.getJSON("http://www.fwusy.net/poll/poll.php?vote=none",loadResults);
  }
  else {
  $("#poll").animate({"opacity": 1}, 600);
  $("#poll-container").animate({"opacity" : 1},600);
  }


            }); }); 


function formProcess(event){
  event.preventDefault();
  
  var id = $("input[@name='poll']:checked").attr("value");
  id = id.replace("opt",'');
  
  $("#poll-container").animate({"opacity" : 0},500, function(){
    
    
    votedID = id;
    $.getJSON("http://www.fwusy.net/poll/poll.php?vote="+id,loadResults);
    
    $.cookie('vote_id', id, {path: '/', expires: 365});
    $.cookie('question_id', QUESTION_ID, {path: '/', 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 = 0;
  var percent;
  
  for (id in data) {
    
    total_votes = total_votes+parseInt(data[id][OPT_VOTES]);
  }
  
  var results_html = "<div id='poll-results'><h3 class='poll-results'>Poll Results</h3>\n<span class='poll-question'>"+QUESTION_ID+"</span>\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) {
      results_html = results_html+"<dt class='result-lable'>"+data[id][OPT_TITLE]+"</dt><dd class='result-graph'><div id='bar"+data[id][OPT_ID]+"'style='width:0%;'>&nbsp;</div><strong>"+percent+"%</strong></dd>\n";
    } else {
      results_html = results_html+"<dt class='result-lable'>"+data[id][OPT_TITLE]+"</dt><dd class='result-graph'><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 class='total-votes'>Total Votes: "+total_votes+"</p></div>\n";
  $("#poll-container").html(results_html).animate({"opacity" : 1},500,function(){
    animateResults();});
    
}



