window.addEvent('domready', function() {
	new MenuMorpherIBBBerufsbildung('menu-list');
});

var MenuMorpherIBBBerufsbildung = new Class({
	
	currentPosition: 0,
	targetPositiont: 0,
	elementToMove: null,
	leftControl: null,
	rightControl: null,
	shiftX: 200,
	childsDisplayed: 4,
	isRunning: false,
	leftmostPosition: 0,
	
	initialize: function(moveElement) {
		if ($(moveElement)) {
			this.elementToMove = $(moveElement).getElement('ul.main-navi-bb');
			var childsInList = this.elementToMove.childNodes.length;
			this.leftmostPosition = ((childsInList - this.childsDisplayed) * this.shiftX) * -1;
			this.elementToMove.style.width = childsInList * this.shiftX+'px';
			this.leftControl = $('menu-leftarrow');
			this.rightControl = $('menu-rightarrow');
			this.leftControl.style.visibility = 'hidden';
			if (this.elementToMove.getScrollSize().x <= ( this.childsDisplayed * this.shiftX) ) {
				this.rightControl.style.visibility = 'hidden';
			}
			this.leftControl.addEvents({
				'click': this.clickHandlerLeft.bindWithEvent(this, [this.elementToMove])
			});
			this.rightControl.addEvents({
				'click': this.clickHandlerRight.bindWithEvent(this, [this.elementToMove])
			});
			this.elementToMove.set('tween', {
				'onComplete': this.unsetRunning.bind(this)
			});
		}
	},
	
	clickHandlerLeft: function(event, item) {
		if (!this.isRunning) {
			this.isRunning = true;
			this.calculateTargetPosition(false);
			item.tween('margin-left', this.targetPosition);
			if (this.targetPosition >= 0) {
				this.leftControl.style.visibility = 'hidden';
			}
			this.rightControl.style.visibility = 'visible';
		}
	},
	clickHandlerRight: function(event, item) {
		if (!this.isRunning) {
			this.isRunning = true;
			this.calculateTargetPosition(true);
			item.tween('margin-left', this.targetPosition);
			if (this.targetPosition <= this.leftmostPosition) {
				this.rightControl.style.visibility = 'hidden';
			}
			this.leftControl.style.visibility = 'visible';
		}
	},
	
	calculateTargetPosition: function(left) {
		this.currentPosition = this.elementToMove.getStyle('margin-left').toInt();
		if(left) {
			this.targetPosition = this.currentPosition - this.shiftX;
		} else {
			this.targetPosition = this.currentPosition + this.shiftX;
		}
		this.checkTargetPosition();
	},
	
	checkTargetPosition: function() {
		if (this.targetPosition > 0) {
			this.targetPosition = 0;
		}
		if (this.targetPosition < this.leftmostPosition) {
			this.targetPosition = this.leftmostPosition;
		}
	},
		
	unsetRunning: function() {
		this.isRunning = false;
	}
	
});
