/**
 * @author Arian Stolwijk <http://www.aryweb.nl>
 * 
 */

var Awf = Awf ? Awf : {};

Awf.imageSlideshow = new Class({
	version: 1.1,
	
	Implements: Options,
	
	options: {
		duration: 1500,
		wait: 4000,
		elmtDimensions: 'auto',
		fadeAtStart: false,
		max: 1,
		min: 0
	},
	
	current: null,
	count: 0,	
	fx: {},
	
	initialize: function(elmt,options){
		this.setOptions(options);
		
		this.elmt = elmt;
		
		this.images = this.elmt.getElements('img');
		this.count = this.images.length;
		
		if (this.count > 1) {
			this.elmt.setStyles({
				'overflow': 'hidden',
				'position': 'relative'
			});
			if($type(this.options.elmtDimensions) == 'object'){
				this.elmt.setStyles(this.options.elmtDimensions);
			}else{
				this.elmt.set('morph',{duration:this.options.duration});
			}
			this.images.setStyles({
				'position': 'absolute',
				'top' : 0,
				'right': 0,
				'opacity': this.options.min
			});
			
			this.changeImage(0,!this.options.fadeAtStart);
			this.changeImage.periodical(this.options.wait, this);
		}
	},
	
	nextI: function(){
		this.current = (this.current+1) >= this.count ? 0 : this.current+1;
		return this.current;
	},
	
	getTween: function(i){
		if(!this.images[i].retrieve('tween')){
			this.images[i].set('tween',{duration:this.options.duration});
		}
		return this.images[i].get('tween');		
	},
	
	changeImage: function(i,doNotFade){
		var current = this.current ? this.current : 0;
		var i = $type(i) == 'number' ? i : this.nextI();
		if (
			$type(this.images[current]) == 'element' &&
			$type(this.images[i]) == 'element'
		) {
			if(!doNotFade){
				this.getTween(current).start('opacity',this.options.min);
				this.getTween(i).start('opacity',this.options.max);
				if (this.options.elmtDimensions == 'auto') {
					this.elmt.morph({
						'width': this.images[i].getStyle('width'),
						'height': this.images[i].getStyle('height')
					});
				}
			}else{
				this.images[current].setStyle('opacity',this.options.min);
				this.images[i].setStyle('opacity',this.options.max);
				if (this.options.elmtDimensions == 'auto') {
					this.elmt.setStyle('width', this.images[i].getStyle('width'));
					this.elmt.setStyle('height', this.images[i].getStyle('height'));
				}
			}			
		}
	}
	
});

/* So you can do like this $('photos').imageSlideshow(); or even $('photos').imageSlideshow().setStyle('border',1); */
Element.implement({
	imageSlideshow: function (options){
		new Awf.imageSlideshow(this,options);
		return this;
	}
});

