/**
 * Image JS Klasse die das hochladen und entfernen von Bildern realisiert
 * 
 * @return
 */
var MemberAdvertising = new Class({
	
	Implements: Options,
	
	image: null,
	actImage: 0,
	image_origin: null,
	interval: null,
	loadedImages: new Array(),
	/*
	 * Optionen der Klasse
	 */
	options: {
		'images': null,
		'wrapper': null,
		'startAt': 0,
		'path': null
	},
	
	initialize: function(options){
		this.setOptions(options);
		
		this.actImage = this.options.startAt;
		
		this.preloadImages();
		if (null != this.options.wrapper) {
			this.image = this.options.wrapper.getElement('img');
		}
		//this.image = new Element('img', {
		//	'src': this.options.path + this.options.images[0].image
		//});
		
		//this.image.inject(this.options.wrapper);
		
		this.interval = setInterval(function () {this.startRotation()}.bind(this), this.options.images[this.actImage].duration);
		
	},
	
	startRotation: function() {
		var nextImageId = this.getNextImageId();
		if (false == this.loadedImages[nextImageId]) {
			
			return null;
		}
		
		clearInterval(this.interval);
		
		//Wenn schon ein zweites Bild vorhanden ist, dieses entfernen
		if (this.image_origin) {
			this.removeOrigin();
		}
		
		this.image_origin = this.image;
		this.image = this.image_origin.clone();
		
		this.image.setStyles({
			'opacity': 0,
			'z-index': '2',
			'position': 'absolute'
			//'top': this.image_origin.getPosition().y,
			//'left': this.image_origin.getPosition().x,
		});
		
		this.image.setProperty('src',this.getNextImage());

		this.image.inject(this.image_origin, 'after');
		
		//new Fx.Styles(this.image_origin, {'duration': 1600}).start({'opacity': [1,0]});
		new Fx.Morph(this.image, {'duration': 1600}).start({'opacity': [0,1]});
		
		this.interval = setInterval(function () {this.startRotation()}.bind(this), this.options.images[this.actImage].duration);
		
	},
	
	removeOrigin: function() {
		this.image.setStyles({
			'z-index': '1',
			'position': 'relative'
			//'left': 0
		});
		this.image_origin.dispose();
	},
	
	getNextImageId: function() {
		var actImage = this.actImage+1;
		
		if (actImage > (this.options.images.length-1)) {
			actImage = 0;
		}
		
		return actImage
	}, 
	
	getNextImage: function() {
		this.actImage = this.getNextImageId();
		
		return this.options.path + this.options.images[this.actImage].image;
	},
	
	preloadImages: function() {
		
		this.options.images.each(function(image, idx) {
			
			this.loadedImages[idx] = false;
			var img = new Image();
			img.src = this.options.path + image.image;
			$(img).addEvent('load', function() {
				this.loadedImages[idx] = true;
			}.bind(this));
		}.bind(this));
	}	
});
