/* roate.js
 */

var Rotate = Fx.Elements.extend({
  currentIndex: 0,
  options: {
    showFor: 5,
    fadeTime: 500
  },
  initialize: function (parent, times, options){
    this.setOptions(options);
    parent = $(parent);
    if(!parent) return;
    
    var random = function(){ return Math.round(Math.random()) - 0.5; };
    
    this.container = parent;
    this.items     = parent.getChildren().sort(random).sort(random).sort(random);  //Very Random :-)
    this.times     = times || {};
    this.items[this.currentIndex].injectTop(this.container);    //Prevent flash
    this.container.addClass("running");
    this.change(0);
  },
  change: function (index) { //Should be using pass & chaining here
    if(index >= this.items.length) return;
    var show = this.items[index].setStyle("opacity",0);
    var time = (this.times[show.getProperty("class")] || this.options.showFor) * 1000;
    var next = (function(){
      this.change.delay(time, this, [(index + 1) % this.items.length]);
    }).bind(this);
    
    var transition = (function() {
      show.injectTop(this.container);
      show.effect("opacity", {duration: this.options.fadeTime, onComplete: next}).start(1);
    }).bind(this);
    
    var old = this.items[this.currentIndex].effect("opacity", 
      {duration: this.options.fadeTime, onComplete: transition}).start(0);    
    this.currentIndex = index;    
  }
});