/**
 * Class to handle deister media container
 * 
 */

// Create instance when page is ready
var dmc;
Event.observe(window, 'load', function(){
	dmc = new DeisterMediaContainer();
});

var DeisterMediaContainer = Class.create();
Object.extend(DeisterMediaContainer.prototype, {

	/**
	 * Initializes instance
	 * 
	 */
	initialize: function(){
		$$('.media-slideshow .media-box').each(function(elm, i){
			var startdelay = $(elm).up('.media-slideshow').hasClassName('media-slideshow-async') ? .5*i : 0;
			
			new DeisterMediaContainerSlideshow({
				'target' : elm,
				'delay' : 8,
				'startdelay' : startdelay, 
				'duration' : .2
			});
		});
	}
	
});


/**
 * 
 * 
 */
DeisterMediaContainerSlideshow = Class.create();
Object.extend(DeisterMediaContainerSlideshow.prototype, {
	
	/**
	 * Initializes instance
	 * 
	 */
	initialize: function(options){
		// target container
		this.target = $(options.target);
		this.id = 'dmcsl-' + Math.round(Math.random()*1000000);
		
		// delay btw slide
		this.delay = options.delay || 8;
		this.startdelay = options.startdelay || 0;
		this.duration = options.duration || .25;
		this.async = options.async || false;

		// all images
		this.frames = this.target.getElementsBySelector('.media-item');
		if (0==this.frames.length) {
			return false;
		}

		// hide all images except the last one and get the max height and width
		this.frames.each(function(frame, i){
			frame.hide();
		});
		
		// initialize frame counters
		this.frame = {};
		this.frame.current = -1;
		this.frame.start = 0;
		this.frame.end = this.frames.length-1;
		this.nextZIndex = 10;
		
		// start the show
		this.showFrame();
		var _this = this;
		window.setTimeout(function(){
			new PeriodicalExecuter(_this.onPeriodicalShowFrame.bind(_this), _this.delay);
		}, this.startdelay*1000);
		
		return this;
	},

	
	/**
	 * 
	 * 
	 */
	onPeriodicalShowFrame: function(){
		this.showFrame();
	},
	
	
	/**
	 * 
	 * 
	 */
	nextFrame: function(){
		var frame = this.frame.current;
		
		if( frame == this.frame.end ){ 
			frame = this.frame.start; 
		} else { 
			frame++; 
		}
		
		return frame;
	},
	

	/**
	 * 
	 * 
	 */
	showFrame: function(){
		// get the next frame
		var frame = this.nextFrame();
		
		// get the desried frame object
		var frameObj = this.frames[frame];
		
		// set desired frame on top of the others and hide it
		frameObj.hide();
		frameObj.style.zIndex = ++this.nextZIndex;
		
		// clear effect queue
		var queue = Effect.Queues.get(this.id);
		queue.each(function(effect) { effect.cancel(); });

		// fade in
		var options = {
			'duration' : this.duration,
			'queue' : { 'position':'end', 'scope':this.id, 'limit':1 }
		};
		Effect.Appear(frameObj, options);
		
		this.frame.current = frame;
	}
	
});