document.observe('dom:loaded', function() {

    var delay = 15;	// sekunden
    var duration = 2;	// sekunden
    var mode = 'next';	// Standard-Laufrichtung [next|prev]
    
    var images = $$('.headerImage');
    var actual_image_index = 0;
	var fade_index = 0;

    // Buttons einblenden
    if (images.length > 1)
    {
		$('prev').show();
		$('next').show();

		var action = window.setInterval(function call() { fade(mode); }, delay*1000);
    }
    
    function fade(mode)
    {
		var displayed_image_index = actual_image_index;
		var next_image_index = mode == 'prev' ? getPreviousImageIndex() : getNextImageIndex();

		$(images[next_image_index]).setStyle({zIndex: fade_index});
		
		new Effect.Appear($(images[next_image_index]), {
			duration: duration,
			queue: 'end',
			afterFinish: function() {
				$(images[displayed_image_index]).hide();
			}
		});

		actual_image_index = next_image_index;
		fade_index++;
    }

    function getNextImageIndex()
    {
		return actual_image_index == images.length - 1 ? 0 : actual_image_index + 1;
    }

    function getPreviousImageIndex()
    {
		return actual_image_index == 0 ? images.length - 1 : actual_image_index - 1;
    }

    // Buttons überwachen
    $('prev').observe('click', function() {
		window.clearInterval(action);
		fade('prev');
    });

    $('next').observe('click', function() {
		window.clearInterval(action);
		fade('next');
    });

});