window.addEvent('domready',function() {
	/* settings */
	var showDuration = 4000;
	var container = $('header_bar');
	var buttons = $$('div.header_bar_item');
	var images = container.getElements('img.photo');
	var currentIndex = 0;
	var interval;
	var toc = [];
	var tocWidth = 20;
	var tocActive = 'toc-active';
	
	buttons.addEvent('mouseenter', function(e) {
		e.stopPropagation();
		var i = buttons.indexOf($(this));
		stop();
		show(i);
	});
	
	buttons.addEvent('mouseleave', function(e) {
		start();
	});	

	function followLink() {
			window.location = buttons[currentIndex].getElement('a.btn_meerinfo').getProperty('href');	
	}

	
	/* new: starts the show */
	var start = function() { interval = show.periodical(showDuration); };
	var stop = function() { $clear(interval); };
	/* worker */
	var show = function(to) {
		buttons[currentIndex].removeClass('active');
			
		images[currentIndex].set('tween', {duration: 250});
		images[currentIndex].tween('opacity', 0);		
		
		images[currentIndex].setStyle('z-index','100');
		
		toc[currentIndex].removeClass(tocActive);
		var image = images[currentIndex = ($defined(to) ? to : (currentIndex < images.length - 1 ? currentIndex+1 : 0))];
		
		image.setStyle('z-index','101');
		image.set('tween', {duration: 250});
		image.tween('opacity', 1);

		toc[currentIndex].addClass(tocActive);
		
		buttons[currentIndex].addClass('active');
	};
	
	/* new: control: table of contents */
	images.each(function(img,i){
		toc.push(new Element('a',{
			text: i+1,
			href: '#',
			'class': 'toc' + (i == 0 ? ' ' + tocActive : ''),
			events: {
				click: function(e) {
					if(e) e.stop();
					stop();
					show(i);
				}
			},
			styles: {
				left: ((i + 1) * (tocWidth + 10))
			}
		}).inject(container));
		if(i > 0) { img.set('opacity',0); }
	});
	
	/* new: control: next and previous 
	var next = new Element('a',{
		href: '#',
		id: 'next',
		text: '>>',
		events: {
			click: function(e) {
				if(e) e.stop();
				stop(); show();
			}
		}
	}).inject(container);
	var previous = new Element('a',{
		href: '#',
		id: 'previous',
		text: '<<',
		events: {
			click: function(e) {
				if(e) e.stop();
				stop(); show(currentIndex != 0 ? currentIndex -1 : images.length-1);
			}
		}
	}).inject(container);*/
	
	/* new: control: start/stop on mouseover/mouseout */
	container.addEvents({
		'mouseenter': function() { stop(); },
		'mouseleave': function() { start(); },
		'click': function() { followLink(); }
	});
	
	/* start once the page is finished loading */
	window.addEvent('load',function(){
		start();
	});
});
