
window.addEvent('domready', function() {
	
	var cover = $$('#stage .cover');
	var coverLength = cover.length;
	var randomIndex = Math.floor ( Math.random() * coverLength);
	var lastrandom = randomIndex;
	
	$$('#stage .cover').each(function(div,index){
		div.setStyles({
			display:'block',
			opacity: 0
		});
		
		cover[randomIndex].setStyles({
			opacity: 1
		});

	});	

	function fadeOutDelay(div) {
	 timeoutID = window.setTimeout(fadeOut.bind(div), 3500);
	}
	function fadeOut(){
		var childDivs = this.getChildren('div');
		this.fade('out');
		childDivs.each(function(div){
			div.fade('out');
		});	
	};
	
//random cover order 
	function fadeIn(){
		
		var randomIndex = Math.floor ( Math.random() * coverLength);
		
		if(randomIndex == lastrandom) {
			if(randomIndex == coverLength - 1) {
				randomIndex--;
			} else {
				randomIndex++;
			}
		}
		var currentCover = this[randomIndex];
		var childDivs = currentCover.getChildren('div');

		currentCover.fade('in');
		
		childDivs.each(function(div){
			div.fade('in');
		});	
		
		fadeOutDelay(currentCover);
		
		lastrandom = randomIndex;
	};



	var first = fadeOut.bind(cover[randomIndex]);
	var repeat = fadeIn.bind(cover);

	first.delay(3000);
	repeat.periodical(4000);

});
