/***
 * RotateDiv.js
 * Tom McFarlin / March 2008
 * version 0.2 beta 1
 */

/*---------------------------------------------------------------------------*/
document.observe('dom:loaded', function() {
	var divs = $$('div#rotate-div-container div');
	var container = $('rotate-div-container');
	if (divs.length == 1 || !container) return;
	divs.each(function(i) {
		if (divs.first() != i) i.hide();
	});
});
Event.observe(window, 'load', function(evt) {
	new RotateDiv($$('div#rotate-div-container div'), $('rotate-div-container'));
});
/*---------------------------------------------------------------------------*/
var RotateDiv = Class.create({
	
	initialize: function(imgs, cntnr) {
		
		var This = this;
		this.divs = imgs;
		this.container = cntnr;
		this.FADE = false;
		this.SPEED = 8;		
		this.activeDiv = null;
		this.nextDiv = null;

		this.start();
		
	},
	
	start: function() {
		
		this._setupDivs();
		this._setupContainer();
		var This = this;
		new PeriodicalExecuter(function(pe) {
			This._rotate();
		}, This.SPEED)
		
	},
	
	_setupDivs: function() {
		
		var This = this;
		this.divs.each(function(i) {

			This._setStyle(i);
			
			if(This.divs.first() == i) {
				This.activeDiv = i;
			} else {
				i.hide();
			}

		});
		
	},
	
	_setupContainer: function() {
		
		var maxHeight = -1;
		var maxWidth = -1;
		this.divs.each(function(i) {
			if (i.height > maxHeight) {
				maxHeight = i.height;
			}
			if (i.width > maxWidth) {
				maxWidth = i.width;
			}
		});
	
		this.container.setStyle({
			height: maxHeight + 'px',
			width: maxWidth + 'px'
		});
		
		var This = this;
		this.container.classNames().each(function(n) {
			if(n.toLowerCase() == 'fade') {
				This.FADE = true;
			} else if ((n * 0) == 0) {
				This.SPEED = n;
			}
		});
		
	},
	
	_rotate: function() {

		if(this.activeDiv == this.divs.last()) {
			this.nextDiv = this.divs.first();
		} else {
			this.nextDiv = this.divs[this.divs.indexOf(this.activeDiv) + 1];
		} 
		
		this._swap(this.activeDiv, this.nextDiv);

	},
	
	_swap: function(current, next) {
	
		/* opera's failsafe */
		this._setStyle(current);
	
		if(this.FADE) {
			new Effect.Fade(current);
			new Effect.Appear(next);
		} else {
			current.hide();
			next.show();
		}
		
		this.activeDiv = this.nextDiv;
		
	},
	
	_setStyle: function(image) {
	
		var margin = '-' + image.height + 'px';
		if(image.getStyle('margin-bottom') != margin) {
			image.setStyle({
				marginBottom: margin,
				float: 'left'
			});
		}
		
	}
	
});
