var Rating = {
  rate: 0,
  config: {
      endpoint: '/api/rating'
    , max_show_stars: 20
    , add_image: '/images/item/icon_add_star.jpg'
    , star_image: '/images/item/icon_star.jpg'
  },
  initialize: function () {
    if ( $('rate_box') ) {
      this.setupRatebox();
      this.getRate();
    }
  },
  setupRatebox: function () {
    var id = $('rate_box');
    var button = document.createElement('div');
    button.id = 'rate-button';
    button.innerHTML = '<div id="stars"></div>';
    button.innerHTML += '<a href="javascript:Rating.addRate();" class="add-rate"><img src="' + this.config.add_image + '"></a>';
    id.appendChild(button);
  },
  setStars: function () {
    var stars = $('stars');
    var rate = this.rate;
    this.removeStars();

    if ( rate < this.config.max_show_stars ) {
      for ( var i = 0; i < rate; i++ ) {
        this.addStar();
      }
    }
    else {
      this.addStar();
      this.showRate();
      this.addStar();
    }
  },
  removeStars: function () {
    $('stars').innerHTML = '';
  },
  addStar: function () {
    var star = document.createElement('img');
    star.src = this.config.star_image;
    $('stars').appendChild(star);
  },
  showRate: function () {
    var rate_text = document.createElement('span');
    rate_text.setAttribute('class','rate');
    rate_text.innerHTML = this.rate;
    $('stars').appendChild(rate_text);
  },
  getRate: function () {
    var rating_obj = this;
    var req = new Ajax.Request( this.config.endpoint + '/get', {
      method: 'get',
      parameters: 'uri=' + encodeURIComponent(location.href),
      onComplete: function(res) {
        rating_obj.rate = res.responseText;
        rating_obj.setStars();
      }
    });
  },
  addRate: function () {
    var rating_obj = this;
    var req = new Ajax.Request( this.config.endpoint, {
      method: 'post',
      parameters: 'uri=' + encodeURIComponent(location.href),
      onComplete: function(res) {
        var status = eval( res.responseText );
        if ( status ) {
          var rate = parseInt(rating_obj.rate);
          rating_obj.rate = rate + 1;
          rating_obj.setStars();
        }
      }
    });
  }
};

var onloadfunc = function(){
  Rating.initialize();
};

if (window.addEventListener) {
  window.addEventListener('load', onloadfunc, false );
} else {
  window.attachEvent('onload', onloadfunc);
}
