var BgShow = new Class({

	Implements: Options, 	
	options: {
			imgId: 'bgEl',
			frequency: 5,
			transitionTime: 1200,
			srcDir: 'tl_files/meertz/pics/bg/',
			images: [
				'concerto2.jpg',
				'concerto.jpg',
				'creditsuisse.jpg',
				'ctp.jpg',
				'frau.jpg',
				'moped.jpg',
				'porsche.jpg',
				're_kwk2.jpg',
				're_kwk.jpg',
				'somat2.jpg',
				'somat.jpg',
				'stiftung1.jpg',
				'stp2.jpg',
				'sundbeam.jpg',
				'wand.jpg',
				'wsdp.jpg',
				'xarelto.jpg'
			]
	},

	initialize: function(options){
		this.setOptions(options);
		this.bgImages = this.preload();
		this.intervalIndex = this.bgImages.length; 
		this.el = $(this.options.imgId);
		this.el.set('src',this.options.srcDir+this.options.images[0]);
		this.letsRun();
	},

	preload: function(){
		var srcDir = this.options.srcDir;
		var srcImagesArray = this.options.images;
		var preloadImages = srcImagesArray.map(function(item,index){
			return srcDir + item;
		});
		var loader = new Asset.images(preloadImages);  
		return preloadImages;
	},


	backgroundChange: function(){
		var m = this.el;
		// lets clone and inject after
		var t = m.clone();
		t.setStyle('opacity',0);

		this.intervalIndex--;
		var pBackground = this.bgImages[this.intervalIndex];
		if(this.intervalIndex <= 0)
			this.intervalIndex = this.bgImages.length;

		t.set('src',pBackground);
		t.inject(m,'after');

		// the effect section
		var fx1 = new Fx.Tween(m,{
			duration: this.options.transitionTime,
			onComplete: function(){
				m.destroy();
			}
		});
		var fx2 = new Fx.Tween(t,{
			duration: this.options.transitionTime
		});
		fx1.start('opacity',1,0);
		fx2.start('opacity',0,1);

		this.el = t;
	},

	letsRun: function() {
		this.stop();
		this.timer = setInterval(this.onTimerEvent.bind(this), this.options.frequency * 1000);
		return this
	},

	execute: function() {
		this.backgroundChange();
		return this
	},

	stop: function() {
		if (!this.timer) return this;
		clearInterval(this.timer);
		this.timer = null;
		return this
	},

	onTimerEvent: function() {
	
		if (!this.currentlyExecuting) {
		
			try {
			
				this.currentlyExecuting = true;
				this.execute();
			} finally {
			
				this.currentlyExecuting = false;
			}
		}
			
		return this
	}

});

