/**
 * Image Switcher
 * Dependencies: Mootools v1.1+
 * @author Kevin Dew <kev@dewsolutions.co.uk>
 * @copyright Copyright Kevin Dew, 2007
 */

var SwitchImage = 
{
	init: function()
	{	
		if(typeof images == 'undefined' || !$('imageSwitch') || (images.length < 2))
			return;

                this.images = images;

                $each(this.images, function(k, v)
                {
                        if($('imageSwitch').getProperty('src') == v)
                                this.current = k;
                });
		
                this.imageChange.periodical('5000', this);
                
		return;
	
	},
        current:0,
        running:false,        
	imageChange: function()
	{
                if(this.running)
                        return;
                this.running = true
                
                if((this.current + 1) >= this.images.length)
                        this.current = 0;
                else
                        this.current++;

		this.newImg = new Image();
		this.newImg.onload = this.hideOldImage.bind(this);
		this.newImg.src = this.images[this.current];
		
		return;		
	},
	hideOldImage: function()
	{
		this.oldImg = $('imageSwitch');
		new Fx.Style(this.oldImg, 'opacity', {duration: 250, onComplete:this.showNewImage.bind(this)}).start(1,0);
	},
	showNewImage: function()
	{		
		var alt = this.oldImg.getProperty('alt');
		var currentClass = this.oldImg.getProperty('class');
		this.newImgEl = new Element('img', {'alt': alt, 'src': this.newImg.src, 'class': currentClass, 'id': 'imageSwitch'});		
		var newFx = new Fx.Style(this.newImgEl, 'opacity', {duration: 250}).hide();
		this.oldImg.replaceWith(this.newImgEl);
                this.running = false;
		newFx.start(0,1);
	}
}

window.addEvent('domready', SwitchImage.init.bind(SwitchImage));
