/*

*/

var MooRating = new Class({
  Implements: [Options],
  getOptions: function(){
    return {
    items: 5,
    styleItemOff: 'rating-selector-off',
    styleItemOn: 'rating-selector',
    locked: false,
    onTest: function(str) {}
    }
    
  },
  initialize: function(el,options) {
    // let's build control
    this.setOptions(this.getOptions(),options);
    this.container = el;
    this.x = this.container.getPosition().x;
    this.width = this.container.getSize().x;
    this.bar = new Element('div', {'class': 'rating-bar'});  
    this.container.grab(this.bar);
    this.ul = new Element('ul');
    this.container.grab(this.ul);
    this.stars = new Array();
    for(var i=0; i < this.options.items; i++) {
      var li = new Element('li');
      var star = new Element('a', {'class': this.options.styleItemOff, 'html': (i / this.options.items)  });
      this.stars[i] = star; 
      li.grab(star)        
      this.ul.grab(li);      
      star.addEvent('click', this.click.bind(this));      
    }  
    this.container.addEvent('mousemove', this.over.bind(this));
    this.container.addEvent('mouseout', this.out.bind(this));   
    this.setValue(el.getElement('input[name=rating]').value);
    
  },
  lock: function() {
    this.options.locked = true;
  },
  unlock: function() {
    this.options.locked = false;
  },
  setValue: function(v) {
    var d = - (this.width) + this.width * v; 
    this.bar.setStyle('margin-left', d);
  },
  over: function(e) {
    if(this.options.locked == false) {
      var level = Math.ceil((e.client.x - this.x) / this.stars[0].getSize().x );
        for(var i = 0; i < level; i++)
          this.stars[i].set('class',this.options.styleItemOn);
        for(var j = i; j < this.options.items; j++)
          this.stars[i].set('class',this.options.styleItemOff);  
    }
  },
  out: function(e) {
    if(this.options.locked == false) {
      for(var j = 0; j < this.options.items; j++)
        this.stars[j].set('class',this.options.styleItemOff);    
    }
  },
  click: function(e) {
    if(this.options.locked == false) {
      this.lock();
      for(var j = 0; j < this.options.items; j++)
        this.stars[j].set('class',this.options.styleItemOff);
      this.options.onTest(e.target.get('text')); 
       
    } 
  }
});

