var VoteHijacker = Class.create();
VoteHijacker.prototype =
{
    initialize: function(prefix)
    {
        this.prefix = prefix || "";
        this.registerEventHandlers();
    },

    registerEventHandlers: function()
    {
        $$("form." + this.prefix + "vote").each(function(form)
        {
            Event.observe(form, "submit", this.doVote.bindAsEventListener(this), false);
        }.bind(this));
    },

    doVote: function(e)
    {
        Event.stop(e);
        var form = Event.element(e);
        var id = /(\d+)$/.exec(form.id)[1];
        var action = /(up|clear)vote/.exec(form.action)[1];
        new Ajax.Request(form.action, {
            onComplete: VoteHijacker.processVoteResponse(this.prefix, id, action)
        });
    }
};

VoteHijacker.processVoteResponse = function(prefix, id, action)
{
    return function(transport)
    {
        var response = transport.responseText.evalJSON();
        if (response.success === true)
        {
            var upArrowType = "grey";
            var upFormAction = "up";

            if (action == "up")
            {
                var upArrowType = "mod";
                var upFormAction = "clear";
            }

            VoteHijacker.updateArrow("up", prefix, id, upArrowType);
            VoteHijacker.updateFormAction("up", prefix, id, upFormAction);
            VoteHijacker.updateScore(prefix, id, response.score);
        }
        else
        {   
            if (response.error_message == "Not authenticated.")
                location.href = "http://rootclip.com/accounts/login/";
            else
                alert("Error voting: " + response.error_message);
        }
    };
};

VoteHijacker.updateArrow = function(arrowType, prefix, id, state)
{
    var img = $(prefix + arrowType + "arrow" + id);
    var re = new RegExp("a" + arrowType + "(?:mod|grey)\\.gif");
    img.src = img.src.replace(re, "a" + arrowType + state + ".gif");
};

VoteHijacker.updateFormAction = function(formType, prefix, id, action)
{
    var form = $(prefix + formType + id);
    form.action = form.action.replace(/(?:up|clear)vote/, action + "vote");
};

VoteHijacker.updateScore = function(prefix, id, score)
{
    var scoreElement = $(prefix + "score" + id);
    scoreElement.innerHTML = score.score;
};

VoteHijacker.pluralize = function(value)
{
    if (value != 1)
    {
        return "s";
    }
    return "";
};