(function ($){
slideSwitch = function() { // Fade into the next image.
    var $active = $('#slideshow  .active');        
    var $next = find_next($active, false); // Second param random: true or false
		
		$active.fadeOut('normal', function(){
			$next.fadeIn('normal').addClass('active');		
		}).removeClass('active last-active');
}

find_next = function($active, random){ // Get the next image.
	if(random){ // Get next image randomly
    var $sibs  = $active.siblings();
    var rndNum = Math.floor(Math.random() * $sibs.length );

    return $( $sibs[ rndNum ] ); 	
	}else{ // Get the next image in order
		return $active.next().length ? $active.next() : $('#slideshow .faderimage:first');
	}	
}

resize = function(img) { // Resize if needed.	
	var container = $('#slideshow');

	if (img.width() < container.width() && img.height() < container.height() ) return img;
	
	var cw = container.width() / img.width();
	var ch = container.height() / img.height();

	if(cw > ch) {
		img.css({width: img.width() * ch, height: container.height()});
	} else {
		img.css({width: container.width(), height: img.height() * cw});
	}
	
	return img;
}


}) (jQuery);

$j(function() { // On document ready (This only happens once...)	 	
  
  // If no Image is set as active make the first one active.
  if ( $j('#slideshow .active').length == 0 ) $j('#slideshow .faderimage:first').addClass('active');
	
  // Make sure the active image is visible.
  $j('#slideshow .active').show();
  
  // Fade to next Image every 5 seconds.
  setInterval( "slideSwitch()", 5000 );

});
