$(function() {
    // get all vote_links
    $('.vote_link').click(function(event) {
        // post to link
        var link = $(this);
        var href = link.attr('href');
        event.preventDefault();


        // do the post
        $.ajax({
           type: 'POST',
           url: href,
           data: {},
           success: function(data, textStatus) {
                // toggle display on success
                link.parent().toggleClass('voted');

                // update # of votes
                data = eval( '(' + data + ')' );
                link.siblings('.votesCounted').text(data.num_votes + ' Votes');

                // switch link
                parts = href.match(/\/((?:un)?vote)\/(\d+)\//);
                action = parts[1];
                num = parts[2];
                if (action == 'vote') {
                    link.attr('href', '/unvote/' + num + '/');
                } else { 
                    link.attr('href', '/vote/' + num + '/');
                }
            },
            error: function(request, textStatus, errorThrown) {
                alert('You have already voted the maximum of three times.');
            }});
        return false;
    });
});
