
/*
* Class creates fading image effect 
* 2 img elements are placed on top of one another
* The top element then fades showing element behind 
* When transition is complete a new element is created below img element in view 
* Old element is removed
*/

var image_effect = Class.create();


image_effect.prototype = {
	
		
	initialize: function(container, images, options){
		
		//check container exists		
		if(!$(container)){
			throw(container+" doesn't exist!");
	   		return false;
	  	} 	
		
		if(images.length < 1){
			throw("No images supplied!");
	   		return false;
	  	} 
		
		//options, default if not supplied
		this.options = Object.extend({
			duration : 5,
			imageClass : "randomiser",
			delay : 5,
			altTag : $$('title')[0].innerHTML
		}, options || {});						
	
		this.container = container;
		this.images = images.split(",");	
		this.imagesSize = this.images.length;
		this.imageKey = 0;		
		
		//create new img element
		var element = new Element('img', { 'class': this.options.imageClass , alt: this.options.altTag , src : this.images[this.imageKey]});				
		new Insertion.Top($(this.container), element);			
		this.imageKey++;					
			
		//Check that image has loaded before loading next image
		Event.observe(element, 'load', function(){															
			//start effect if more than 1 image
			if(this.imagesSize > 1)
				this.addNode();	
				
		}.bind(this));
	},	
	
	
	/*
	* Handle fade
	*/
	
	fade: function(){
		
		var currentImage = $$('#'+this.container+' .'+this.options.imageClass)[1];	
		
		new Effect.Fade(currentImage, {	
			duration: this.options.duration,
			delay: this.options.delay,
			afterFinish: function(){ 			
				this.addNode(); 
				//remove faded element				
				$$('#'+this.container+' .'+this.options.imageClass)[2].remove();
			}.bind(this)
		});	
	},
	
	
	/* 
	* Add new node when fade is complete
	*/
	
	addNode: function(){
		
		//check if image is last in the array
		if(this.imageKey == this.imagesSize)
			this.imageKey = 0;		
			
		//create new img element
		var element = new Element('img', { 'class': this.options.imageClass , alt: this.options.altTag , src : this.images[this.imageKey]});				
		new Insertion.Top($(this.container), element);	
		
		//incremement key
		this.imageKey++;	
		
		this.fade();			
	}
	
}