var OPT_ID = 'option_id';
var OPT_TITLE = 'title';
var OPT_VOTES = 'votes';

var votedID;

$(document).ready(function() {
    $("#poll").submit(formProcess);

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

    if ($.cookie('vote_id')) {
        $("#poll-container").empty();
        votedID = $.cookie('vote_id');
        var question = $("#poll_question").val();
        $.getJSON(base_url + "/poll/vote/question/" + question + "/id/none", loadResults);
    }
});

function formProcess(event) {
    event.preventDefault();

    var id = $("input[@name='poll']:checked").attr("value");

    if (id == undefined) {
        alert('Maak een keuze');
        return;
    }

    var question = $("#poll_question").val();
    id = id.replace("opt", '');

    $("#poll-container").fadeOut("slow", function() {
        $(this).empty();

        votedID = id;
        $.getJSON(base_url + "/poll/vote/question/" + question + "/id/" + id, loadResults);

        $.cookie('vote_id', id, {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"><dl class="graph">' + "\n";
    for (id in data) {
        percent = Math.round((parseInt(data[id][OPT_VOTES])/parseInt(total_votes))*100);
        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%;height: 6px;margin: 3px 0;background-color:#ffff88;">&nbsp;</div><strong>' + percent + '%</strong></dd>' + "\n";
    }

    results_html = results_html+"</dl><p>Aantal stemmen: "+total_votes+"</p></div>\n";

    $("#poll-container").append(results_html).fadeIn("slow",function() {
        animateResults();
    });
}
