var rating = {
  init: function () {
    jQuery('.unit').mouseover(function () { rating.mouseover(this) });
    jQuery('.unit').click(function () { rating.click(this) });
    jQuery('.unit').mouseout(function () { rating.mouseout(this) });
    jQuery('.unit').each(function () { rating.mouseout(this) });
  },

  mouseover: function (obj) {
    this.blank(obj);
    this.highlight(obj);
  },

  mouseout: function (obj) {
    var input = jQuery(obj).parent().children("input").get()[0];

    var self  = this;
    self.blank(obj);

    if (input.value) {
      var i = 1;
      jQuery(obj).parent().children(".unit").each(function () {
         if (input.value == i++) {
           self.highlight(this);
         }
      });
    }
  },

  click: function (obj) {

    var n = 0;
    var current = jQuery(obj);
    while (current.get().length) {
      n++;
      current = current.prev('.unit');
    }

    jQuery(obj).parent().children("input").get()[0].value = n;
    obj.innerHTML;
    this.blank(obj);
    this.highlight(obj);
  },

  highlight: function (obj) {
    var traverse = jQuery(obj)
    while (traverse.get().length) {
      traverse.removeClass('unselected').addClass('selected');
      traverse = traverse.prev('.unit');
    }
  },

  blank: function (obj) {
    jQuery(obj).parent().children().each(function () {
      jQuery(this).removeClass('selected').addClass('unselected');
    });
  }
}
