
/**
 * Determine next, add onload for image to complete
 */
function gotoNext()
{
	// Get next image 
	var imageId = getNextImage();
	
	// When image is loaded, do the animation
	$(imageId).bind('load', function(){
			animateNext();
			$(this).unbind('load'); // Unbind to prevent recursion
		})
		.each(function(){ // Cache fix, some browsers don't call load
			if (this.complete)
				$(this).trigger('load');
		});
}


/**
 * Animate the change.
 * Start loading the next image & set timeout for next
 */
function animateNext()
{
	var current = $('#menu-main ul li:nth-child(1) a');
	var next 	= $('#menu-main ul li:nth-child(2) a');
	
	// Bring in the next menu-element
	next.parent().addClass('active');
	current.parent().slideUp(1000, function(){
		// Reset the old menu-element
		current.parent().removeClass('active');
		current.parent().appendTo('#menu-main ul');
		current.parent().slideDown(1000, function(){
			// Animation competed, add next's next image to load
			getNextImage();
			// After timeout start next animation
			setTimeout('gotoNext()', 4000);
		});
	});
	
	// Switch the images
	var active = $('#container-slideshow .active');
	if (active.length == 0)
		active = $('#container-slideshow img:first');
	active.addClass('last-active');
	
	var nextImage = active.next().length
		?  active.next()
		:  $('#container-slideshow img:first');
	nextImage.css({opacity: 0.0})
		.addClass('active')
		.animate({opacity: 1.0}, 1750, function() {
			active.removeClass('active last-active');
		});
}


/**
 * Create the image-object if needed
 * @return DOM-id
 */
function getImage(name)
{
	var imageId = 'home-slideshow-'+ name;
	if ($('#'+imageId).length == 0)
		$('<img id="'+ imageId +'" src="'+ imagePath + name +'.jpg" alt="">')
			.appendTo('#container-slideshow');
	return '#'+ imageId;
}

/**
 * Easy accessor function to get the next image
 */
function getNextImage()
{
	var next = $('#menu-main ul li:nth-child(2) a');
	return getImage( next.attr('href') );
}


/**
 * On document ready, start animation
 */
$(document).ready(function(){
	// 
	$('#menu-main ul li:first').addClass('active');
	
	// Start first slide
	setTimeout('gotoNext()', 3000);
});

