var Ellington = window.Ellington || {};


/*
 * Vote Form
 * Turns a typical vote form into a nice ajax form.
 *
 * Markup:
 *   <form action="." method="post" class="vote_form">
 *     <button type="submit" name="value" value="1">Vote</button>
 *     <span class="vote_count">0</span>
 *     <input type="hidden" name="content_type" value="1">
 *     <input type="hidden" name="object_id" value="1">
 *   </form>
 *
 * Template: ratings/vote_form.html
 */

Ellington.VoteForm = (function($) {
  function onClick(e) {
    e.preventDefault();
    var button = $(this);
    var form = $(button.attr('form'));
    var serialized = form.serialize()+'&'+button.attr('name')+'='+button.attr('value');

    $.ajax({
      type: 'POST',
      url: form.attr('action'),
      data: serialized,
      dataType: 'json',
      success: function(response, status, request) {
        var count = form.find('.vote_count');
        count.text(response.score);
        count.addClass('voted');
        form.replaceWith(count);
      },
      error: function(request, status, error) {
        window.location = '/accounts/login/?next='+window.location.pathname;
      }
    });
  }

  return function(form) {
    $(form).find('button').bind('click', onClick);
  };
})(jQuery);


jQuery(document).ready(function($) {
  $('.vote_form').each(function() {
    Ellington.VoteForm(this);
  });
});
