function loadPollChart(poll_id, poll_url, option) {
    $("#poll_"+poll_id+"_form").hide();
    var results_div = $("#poll_"+poll_id+"_results");
    results_div.show();
    results_div.load(poll_url+"/poll_chart", {"option": option}, function(responseText, textStatus, XMLHttpRequest) {
        if(textStatus == "error") { alert("Server error while attempting to process your vote."); }
    });
}

function showPollForm(poll_id) {
    $("#poll_"+poll_id+"_results").hide();
    $("#poll_"+poll_id+"_form").show();
    return false;
}

function registerPoll(poll_id, poll_url, poll_open) {
    $(document).ready(function() {
        var form = $("#poll_"+poll_id+"_form");
        var message = $("#poll_"+poll_id+"_message");
        if(poll_open) {

            // Disable the submit button until a radio is checked.
            var submit = form.find("input[type='submit']");
            var checked = form.find("input[name='option']:checked");
            if(checked.length == 0) {
                submit.attr("disabled", true);
                form.find("input[type='radio']").click(function() {
                    submit.attr("disabled", false);
                });
            }

            $("#poll_"+poll_id+"_result_link").click(function() {
                loadPollChart(poll_id, poll_url, "");
                return false;
            });

            form.submit(function(event){
                var checked = form.find("input[name='option']:checked");
                if(checked.length == 0) {
                    message.text("Please check an option.");
                } else {
                    loadPollChart(poll_id, poll_url, checked.val());
                    submit.attr("disabled", true);
                    message.text("Submitting your vote...");
                }
                return false;
            });

            // Has the user already voted?
            // Pass a parm to prevent IE caching.
            $.getJSON(poll_url+"/alreadyVotedJSON", {'x': new Date().getTime()}, function(data, textStatus) {
                if(data['result']) {
                    loadPollChart(poll_id, poll_url, "");
                }
            });
        } else {
            loadPollChart(poll_id, poll_url, "");
        }
    });
}
