/*
	# Image Crossfader
	REQUIRES Mootools 1.2+
*/

window.addEvent('domready', function() {

	// # crossfade function if container is present
	if( $defined($('imageContainer')) ) {
		
		var images = $$('#imageContainer img');
		var amount = images.length;

		if(amount > 1) {
			// move images to correct position
			var pos = images[0].getPosition();
			//var pos = $('page').getPosition();
			images.setStyles({
				'top': pos.y,
				'left': pos.x
			});
	
			var i = 0;
			var j = 1;
			images[i].xfade_onTop();
			images[j].xfade_onSecond();
	
			runImageFader = function() {
				
				if( i == amount ) {i = 0;}
				if( j == amount ) {j = 0;}
				
				// set images
				images[i].xfade_onTop();
				images[j].xfade_onSecond();
				var new_subtitle = images[j].get('alt');

				// fade out upper image
				var fadeOutFx = new Fx.Tween(images[i], {duration: 2000, transition: Fx.Transitions.Cubic, link: 'cancel', onComplete: function() { 
					// change subtitle
					if( $defined($('xfade_subtitle')) ) {
						$('xfade_subtitle').set('html', new_subtitle);
					}
				} });
				fadeOutFx.start('opacity', 1, 0);
				
				// iterate
				i++;
				j++;
			
			}
		
			timer = runImageFader.periodical(3000); // 5500
		}
		
	}

});

Element.implement({
	
	// moves image "on top"
	xfade_onTop: function() {
		$$('.onTop').removeClass('onTop');
		this.setStyles({'opacity': 1, 'visibility': 'visible'});
		this.addClass('onTop');
	},

	// moves image "on second top"
	xfade_onSecond: function() {
		$$('.onSecond').removeClass('onSecond');
		this.setStyles({'opacity': 1, 'visibility': 'visible'});
		this.addClass('onSecond');
	}

});

