var RatingWidget = Behavior.create({
  initialize: function(){
    this.form = this.element.up("form");
    this.category = this.element.up(".rating").getAttribute('data-category');
    this.rating = this.element.getAttribute('data-rating');
  },

  onclick: function(){
    this.form.request({
      parameters: { category: this.category, rating: this.rating },
      onSuccess: this.setRatings.bind(this)
    });
  },

  onmouseover: function(event) {
    // Red stars
    var img = Event.element(event);
      var redstar = '/images/icons/red_star.png';
      img.setAttribute("src", redstar);

    img.previousSiblings().each(function(sib) {
      sib.setAttribute("src", redstar);
    });

    var criteria_class = '.' + this.category + this.rating;
    var criteria_text = $$(criteria_class).first();

      if (criteria_text) {
          this.show_criteria(criteria_text.innerHTML);
      }
  },

  onmouseout: function(event) {
    var img = Event.element(event);
      var litstar = '/images/icons/lit_star.png';
      img.setAttribute("src", litstar);

    img.previousSiblings().each(function(sib) {
      sib.setAttribute("src", litstar);
    });

    this.hide_criteria();
  },

  show_criteria: function(text) {
    this.form.down('.rating_criteria').update(text);
    this.form.down('.rating_criteria').show();
  },

  hide_criteria: function() {
    this.form.down('.rating_criteria').hide();
    this.form.down('.rating_criteria').update("None selected");
  },

  toggleRatingsOn: function(img){
    img.removeClassName("unlit");
    img.addClassName("lit");
  },

  toggleRatingsOff: function(img){
    img.removeClassName("lit");
    img.addClassName("unlit");
  },

  setRatings: function(response) {
    $$(".ratings.mine .rating[data-category=" + response.responseJSON.category + "] .stars img").each(function(img) {
      var rating = parseInt(img.getAttribute("data-rating"));
      if(rating <= response.responseJSON.yours){
        this.toggleRatingsOn(img);
      } else {
        this.toggleRatingsOff(img);
      }
    }.bind(this));

    $$(".ratings.overall .rating[data-category=" + response.responseJSON.category + "] .stars img").each(function(img) {
      var rating = parseInt(img.getAttribute("data-rating"));
      if(rating <= response.responseJSON.overall){
        this.toggleRatingsOn(img);
      } else {
        this.toggleRatingsOff(img);
      }
    }.bind(this));
  }
});

Event.addBehavior({
  '.ratings.mine .rating .stars img': RatingWidget
});
