
/* classes/vote.js */

 if( typeof console == "undefined" ) {
  console = { log: function() { } };
}
// To do: replace specific id and class references
Vote = Class.create(
{
  initialize: function( votable, vote_count ) {
    this.container  = $(votable);
    this.vote_link  = this.container.down( ".vote_link a" );
    this.vote_count = vote_count;

    if( typeof this.vote_link == "undefined" ) return;

    var listener = null;

    var not_logged_in = Element.hasClassName(
      this.container.down( ".vote_link a" ), 'login_required' );

    if( not_logged_in ){
      this.register_login_modal();
    }
    else {
      this.vote_link.observe( "click", this.click.bindAsEventListener(this) );
    }
  },

  click: function(ev){
    ev.stop();
    var url = this.vote_link.href;
    new Ajax.Request( url, {
      method: "post",
      onSuccess: function(request) {
        this.updateAfterVote(request);
      }.bind(this)
    },this);
  },

  // To do: refactor to use with js_open_modal. Doesn't work right now.
  register_login_modal: function(){
    this.vote_link.addClassName("js_login_modal");

    var target = window.location.href;

    var separator = "?";
    if( target.match(/\?/) ) separator = "&";

    this.vote_link.href = window.location.href +
      separator +
      "tab=contest_project&view=grouped#contest_project";

    modalObserver.attachLoginModal();
  },

  // To do: replace specific id and class references
  updateAfterVote: function( response ) {
    var voteResponse = response.responseJSON;
    this.vote_count  = voteResponse.number_of_votes;
    var count_label = this.container.down( ".vote_count_label" );
    count_label.innerHTML = this.vote_count + " votes";
    count_label.show();
    $$("#" + this.container.id + " .has_voted").invoke( "show" );
    $$(".to_vote").invoke( "hide" );
    $('contest_vote_success_message').show();

  }

});
