var Banner = Class.create();
Object.extend(Banner.prototype, {
  initialize: function(element) {
    this.element = $(element);
    this.images = $A(this.element.getElementsByTagName('img'));
    if(this.images.length <= 0) return;
    if(!this.element.style.width)
      this.element.setStyle({
        width: this.images.max(function(e){return $(e).getWidth()})+'px'
      });
    if(!this.element.style.height)
      this.element.setStyle({
        height: this.images.max(function(e){return $(e).getHeight()})+'px'
      });
    if(this.images.length <= 1) return;
    this.index = -1; //Fade in begins immediately for first photo
    this.images.each((function(e) {
      e = $(e);
      e.setStyle({
        top: (typeof(banner_dont_center) != "undefined") ? '0px' : (this.element.getHeight()-e.getHeight())/2+'px',
        opacity: 0.01
      });
    }).bind(this));
    this.images.first().setStyle({opacity: 1});
    this.rotate();
  },

  rotate: function(reverse) {
  	if(this.index >= 0) { //For the first photo, a fade won't be called
    	this.images[this.index].setStyle({zIndex: 1});
    	Effect.Fade(this.images[this.index], {to: 0.01});
    }
    
    if(typeof(reverse) != "undefined" && reverse) {
			this.index--;
    } else {
    	this.index++;
    }
    
    if(this.index >= this.images.length) this.index = 0;
    if(this.index < 0) this.index = this.images.length-1;
    
    banner = this.element;
    
    var delayed_rotate = (function() {
      rotateCallback = setTimeout(this.rotate.bind(this), ((5000).random()+5000));
      func = this;
      
      banner.down(".arrow.right").stopObserving("click").observe("click", function () {
      	clearTimeout(rotateCallback);
      	func.rotate();
      	this.stopObserving("click");
      });
      
      banner.down(".arrow.left").stopObserving("click").observe("click", function () {
      	clearTimeout(rotateCallback);
      	func.rotate(true);
      	this.stopObserving("click");
      });
    }).bind(this);
    this.images[this.index].setStyle({zIndex: 2});
    Effect.Appear(this.images[this.index],
      {afterFinish: delayed_rotate});
    banner.down(".arrow.right").stopObserving("click");
    banner.down(".arrow.left").stopObserving("click");
  }
});

Number.prototype.random = function() {return Math.ceil(Math.random()*this)};

