window.addEvent('domready', function() {	

	imagestoload	=	images.length;
	imagesloaded	=	0;
	
	if (fade_gal_mode == "n-random") {
		nimages	=	new Array;
		check	=	images.length;
		loop	=	0;
		while (check > 0) {
			id = getrandom(0, images.length - 1);
			
			if (!images[id]) {
				continue;
			}
			
			image = images[id];
			images[id] = null;
			
			nimages[loop++] = image;
			
			check--;
		}
		
		images	=	nimages;
	}
	
	initcache();
});


function initcache ( ) {
	
	if ($('toload')) {
		$('toload').innerHTML	=	imagestoload;
	}			
	
	var imagecache = new Array();
	
			
	for (i = 0; i < imagestoload; ++i) {
		path			=	serverpath + "cms/media/" + images[i];	
		imagecache[i]	=	new Image();
		
		imagecache[i].onload = function ( e ) {
			var imagenumber			=	++imagesloaded;
			
			if ($('loaded')) {
				$('loaded').innerHTML	=	imagenumber;
			}				
		
			checkinitslide();
		}	
					
		imagecache[i].src	=	path;
	}
	
	
	function checkinitslide ( ) {		
		
		if (imagestoload > imagesloaded) {
			return;
		}
		
		if ($('prelaoder')) {
			$('prelaoder').innerHTML = 'Alle Bilder geladen.';		
			$('prelaoder').fade(0);	
		}	
		
			
		if (imagestoload == 1) {
			$('swap_1').setStyle('opacity', 0);
			$('swap_1').setStyle('display', 'block');
			$('swap_1').fade(1);
			return;
		}
		
		
		$('swap_2').setStyle('opacity', 0);
		$('swap_1').setStyle('opacity', 0);
		
		$('swap_2').setStyle('display', 'block');
		$('swap_1').setStyle('display', 'block');
		
		$('swap_1').fade(1);
		
		window.setTimeout("$('swap_2').fade(1);", 1000);					
		window.setTimeout("swap_image()", flowtime);
	}
}

function getrandom ( min, max ) {
	
 	if( min > max )
		return( -1 );
	
	if( min == max )
		return( min );
	
	var r = parseInt( Math.random() * ( max+1 ) );
	
	return( r + min <= max ? r + min : r );
}


/**
 * Swap back image
 */
function swap_image ( ) {	
	
	if (fade_gal_mode == 'n-random') {		
		curr	=	imageno;	
		next	=	++imageno;
				
		if (next >= imagec)
			next = imageno = 0;
			
		curr = next	=	imageno;
		
		while (next == curr)
			next = imageno = getrandom(0, (imagec - 1));	
	}
	
	
	curr	=	imageno;	
	next	=	++imageno;
				
	if (next >= imagec) {
		next = imageno = 0;
	}
		
	
	
	// Fade in the backlight
	var myEffects = new Fx.Morph('swap_1', {
		duration:	(fadetime * 1000),
		onComplete:	function ( ) {
			setStep(curr, next);
		}
	});
	
	myEffects.start({
		opacity: 0
	});
}

function setStep ( curr, next )
{
	path_curr = serverpath + "cms/media/" + images[curr];
	path_next = serverpath + "cms/media/" + images[next];
	
	$('swap_1').src	=	path_curr;
	setTimeout("$('swap_1').setStyle('opacity', 1);", 100);
	
			 
	setTimeout("setNext(\"" + path_next + "\")", (fadetime * 1000));
}

function setNext ( path_next )
{ 
	$('swap_2').src	=	path_next;
	setTimeout("swap_image()", flowtime);
}

