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

var votedID;

$(document).ready(function() {

    processForm(true, false);

    $("div#btnVote").click(function() {
        processForm(false, false);
        return false;
    });

    $("#aResults").click(function() {
        processForm(true, true);
        $(".voteRemove").remove();
        return false;
    });
});

function processForm(empty, force) {

    if (!empty && $.cookie('vote_id_' + qid) == null) {
        var id = $("input[@name='options']:checked").attr("class");

        if (id != null) {
            id = id.replace("opt_", '');

             $(".poll-container").fadeOut("slow", function() {
                $(this).empty();
                votedID = id;
                jQuery.ajax({
                    type: "POST",
                    url: "/ajax/pollHandler.ashx?qid=" + qid + "&vote=" + id,
                    dataType: "json",
                    data: "get=1",
                    success: function(data) {
                        //pop li into ol at the top
                    loadResults(data);
                    $.cookie('vote_id_' + qid, id, { expires: 365 });
                    },
                    error: function(xhr, status, error) {
                        // Boil the ASP.NET AJAX error down to JSON.
                        var err = eval("(" + xhr.responseText + ")");
                    }
                });
            });
            if ($(".poll-results").length > 0) {
                animateResults();
            }

            $(".voteRemove").remove();
        }
    }
    else {
        if ($.cookie('vote_id_' + qid)!=null) {
            votedID = $.cookie('vote_id_' + qid);
            
            $(".poll-container").fadeOut("slow", function() {
                $(this).empty();
                $.getJSON("/ajax/pollHandler.ashx?qid=" + qid + "&vote=" + votedID, loadResults);
            });

            if ($(".poll-results").length > 0) {
                animateResults();
            }
            
            $(".voteRemove").remove();
            
        }
        else {
            if (force) {
                $(".poll-container").fadeOut("slow", function() {
                    $(this).empty();
                    $.getJSON("/ajax/pollHandler.ashx?qid=" + qid + "&vote=none", loadResults);
                });

                if ($(".poll-results").length > 0) {
                    animateResults();
                }
            }
        }

    }

    
}

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 class='poll-results'><dl class='graph'>\n";
  for (id in data) {
      percent = 0;
      if (data[id][OPT_VOTES] != 0)
      { percent = Math.round((parseInt(data[id][OPT_VOTES]) / parseInt(total_votes)) * 100); }
    
    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:#CCCCCC;'>&nbsp;</div><strong>"+percent+"%</strong></dd>\n";
    }
  }
  
  results_html = results_html+"</dl><p>"+respText+": "+total_votes+"</p></div>\n";
  
  $(".poll-container").append(results_html).fadeIn("slow",function(){
    animateResults();});
}
