if(typeof(Tutoria) == "undefined")
  Tutoria = {};

Tutoria.ArticleRating = function() {
  var articleId;
  var infoContainer;
  var cookieKey;
  var successMsg;
  var ratedBeforeMsg;
  var stars = [];

  function init(id, infoContId, success, ratedBefore) {
    articleId      = id;
    cookieKey      = "wiki-article-" + id + "-rating";
    successMsg     = success;
    ratedBeforeMsg = ratedBefore;
    infoContainer  = $(infoContId);

    for(var i = 1; i <= 5; i++)
      stars[i] = new Star(i);

    var alreadyRated = YAHOO.util.Cookie.get(cookieKey);

    if(alreadyRated) {
      flash(ratedBeforeMsg);
      stars[alreadyRated].upTo('highlight');
      return;
    }

    for(i = 1; i <= 5; i++) {
      stars[i].el.observe('mouseover', stars[i].createHighlightHandler());
      stars[i].el.observe('click',     stars[i].createRateHandler());
    }
  }

  function disable() {
    for(var i = 1; i <= 5; i++) {
      stars[i].el.stopObserving('mouseover');
      stars[i].el.stopObserving('click');
    }
    flash(successMsg);
  }

  function flash(msg) {
    infoContainer.className = 'rating-flash';
    infoContainer.innerHTML = msg;
  }

  function Star(n) {
    this.el = $('star_' + n);
    this.n  = n;
  }

  Star.prototype.mark = function() {
    this.el.className = "set-star";
    this.el.src = "/images/wiki_rating_set.png";
  };

  Star.prototype.highlight = function() {
    this.el.className = "set-star";
    this.el.src = "/images/wiki_rating_set.png";
  };

  Star.prototype.unmark = function() {
    this.el.className = "empty-star";
    this.el.src = "/images/wiki_rating_empty.png";
  };

  Star.prototype.upTo = function(msg) {
    for(var i = 1; i <= this.n; i++)
      stars[i][msg]();
    for(i = this.n + 1; i <= 5; i++)
      stars[i].unmark();
  };

  Star.prototype.createHighlightHandler = function() {
    return function(ev) {
      this.upTo('highlight');
    }.bind(this);
  };

  Star.prototype.createRateHandler = function() {
    return function(ev) {
      var req = new Ajax.Request('/wiki_articles/' + articleId + '/rate', {
	method: 'PUT',
	parameters: {rating: this.n},
	onSuccess: function(response) {
	  this.upTo('highlight');
	  YAHOO.util.Cookie.set(cookieKey, this.n);
	  disable();
	}.bind(this)
      });
    }.bind(this);
  };

  return { init: init };
}();

