var FM_TeaserControl = new Class({
	init: function(itemContainer){
		this.itemContainer = itemContainer;
		this.fadeinfx = null;
		this.fadeoutfx = null;
		this.options = {
			zIndex 		: 100,
			duration 	: 2000,
			interval 	: 5000
		};
		this.teaserItems = this.getTeaserItems();
		//this.navItems = this.createNavigator();	
		if(this.teaserItems.length> 1) {
    	this.timer = this.showNextItem.bind(this).periodical(this.options.interval);
    }	
	},
	getTeaserItems : function(){
		var tempItems = [];
		var i = 0;
		$A($(this.itemContainer).getElements('div')).each(function(el,index){
			if(el.hasClass('pikal_item')){
				//el.setStyle('z-index',this.options.zIndex+(i++));
				tempItems.push(el);
				if(el.getStyle('visibility') != 'hidden'){
					this.currentItem = index;
				}
			}			
		}, this);
		return tempItems;
	},
	showNextItem : function(){	
		this.showItemNumber((this.currentItem+1) % this.teaserItems.length);
	},
	showPrevItem : function(){		
		this.showItemNumber((this.currentItem-1 + this.teaserItems.length) % this.teaserItems.length);
	},
	clickShowItem : function(event, nextItem){
		this.stopEffect();
		$clear(this.timer);
		this.timer = null;
		this.showItemNumber(nextItem);
		this.timer = this.showNextItem.bind(this).periodical(this.options.interval);
	},
	showItemNumber : function (nextItem) {		
		this.stopEffect();
		var e1 = this.teaserItems[this.currentItem];
		var e2 = this.teaserItems[nextItem];
    var to1 = 0;
    var to2 = 1;
    this.fadeoutfx = new Fx.Tween(e1, {duration: this.options.duration, property: 'opacity', wait: true, fps:16 ,transition: Fx.Transitions.linear});
    this.fadeinfx = new Fx.Tween(e2, {duration: this.options.duration, property: 'opacity', wait: true, fps:16 ,transition: Fx.Transitions.linear});	    
    if (this.currentItem == 0) {
			e1.setStyle("z-index",200);
		}   
		e2.setStyle("z-index",(e1.getStyle("z-index")-1));
		e2.setStyle('visibility','visible');
		e1.setStyle("opacity",to2);
		e2.setStyle("opacity",to1);
		this.fadeoutfx.start(to1);
		this.fadeinfx.start(to2);
		this.setNavigatorItem(this.currentItem, nextItem);
		this.currentItem = nextItem;
	},
	stopEffect : function(){
		if(this.fadeoutfx){
			this.fadeoutfx.cancel();
		}
		if(this.fadeinfx){
			this.fadeinfx.cancel();
		}
	},
	setNavigatorItem : function(currentItem, nextItem){
		if(this.navItems){			
			this.navItems[currentItem].removeClass('navigator_item_active');
			this.navItems[currentItem].addClass('navigator_item_inactive');
			this.navItems[nextItem].removeClass('navigator_item_inactive');
			this.navItems[nextItem].addClass('navigator_item_active');
		}
	}
});

window.addEvent('domready', function()    {
   var header = $$('div.pikal');
   header.each(function(el){
   		el.fm_teaserControl = new FM_TeaserControl()
   		el.fm_teaserControl.init(el);
   });
});