if (typeof(Jesper) == 'undefined')
    var Jesper = {};

if (typeof(Jesper.utils) == 'undefined')
    Jesper.utils = {};
Jesper.utils.Rating = new Class({
  Implements: [Options,Events],
  initialize: function (el, options) {
    this.setOptions(options);
    this.element = document.id(el) || document;
    this._init();
  },
  _init : function(){
    this.element.getElements(this.options.search).each(function(el){
      var el = document.id(el),
          info = el.get('id').split('-'),
          post_info = {
            'type': info[1],
            'id': info[2]
          },
          rating = Math.round(parseFloat(el.get('html')))/100,
          tpl = '<div class="rating-helper">{avg}</div>'
              + '<div class="rating-bg"><div style="width:{width}" class="rating-fg"></div></div></div>',
          obj = {'avg':Math.round(rating*100)+"%",'width':rating*85+"px"},
          self = this;
      if(el.hasClass('r-done'))
          return ;
      el.set('html',tpl.substitute(obj));
      el.addEvent('mousemove', function (e)
      {
        var bg = el.getFirst('.rating-bg'),
            x = bg.getPosition().x,
            w = bg.getWidth(),
            p = (e.page.x-x)/w;
        w = Math.max(Math.min(85, (w*p)), 0);

        bg.getFirst('.rating-fg').setStyle("width", w+"px");
        el.getFirst('.rating-helper').set('html', Math.round(w/85*100)+"%");

        e.stopPropagation();
      })
      .addEvent('mouseleave', function (e)
      {
        var bg = el.getFirst('.rating-bg');
        el.getFirst('.rating-helper').set('html', Math.round(rating*100)+"%");
        bg.getFirst('.rating-fg').setStyle("width", rating*bg.getWidth()+"px");
      })
      .addEvent('click', function (e)
      {
        var bg = el.getFirst('.rating-bg'),
            req = new Request.JSON( {
                    method: 'get',
                    url: '/_ajax/rating.php?type='+post_info.type+'&id='+post_info.id+'&rating='+bg.getFirst('.rating-fg').getWidth()/el.getFirst('.rating-bg').getWidth(),
                    onSuccess: function (i) {
                      if (i.error_code == '0x000') {
                        self.fireEvent('success',[i.votes,i.avg,el]);
                        rating = parseInt(parseFloat(i.avg)*20, 10)/100;
                      } else
                        self.fireEvent('failure',[i.error,el]);
                    }
                  });
        req.send();
      });
      el.addClass('r-done');
    }.bind(this));
    this.fireEvent('complete');
  }
});
