$(document).ready(function() {
	// Since TinyMCE keeps removing the #nav-items div, we'll just inject
	// it dynamically
	if ($('#nav-items').size() == 0) {
		$('#slideshow-prev').after('<div id="nav-items" />');
	}
	
	// Clear the nav item's content
	$('#nav-items').html('');
	
	var item_counter = 1;
	$('div#slideshow-items').find('img').each(function(){
		item_counter = item_counter + 1;
	});
	
	// Homepage slideshow
	$('div#slideshow-items').cycle({
		fx : 'fade',
		pager : '#nav-items',
		next : '#slideshow-next',
		prev : '#slideshow-prev',
		autostop: true,
		autostopCount: item_counter,     // true to end slideshow after X transitions (where X == slide count) 
		timeout: 6000,
		before : function(c, n, o, f) {
			$('#slideshow-content').html($(this).children('img').attr('alt'));
		}
	});
	$('#nav-items a').each(function() {
		$(this).html('<span>'+$(this).html()+'</span>');
	});
	$('#nav-items').css('margin-left', -$('#nav-items').outerWidth());
	// Item covers
	$('#coverItems a').each(function() {
		$(this).click(function() {
			loadCover(this);
			return false;
		}).mouseover(function() {
			loadCover(this);
		});
		
		// Preload image
		$('<img>').attr('src', $(this).attr('href'));
	});
	
	// Album voorbeelden
	$('#overzichtFormaten a').each(function() {
		$(this).click(function(e) {
			e.preventDefault();
			var src = $(this).attr('href');
			// Stop both ongoing transitions
			$('#overzichtImg').stop(true, true);
			$('#overzichtImg-out').stop(true, true);
			// Set "out" fading element to the current source,
			// and the "in" fading element to the new source but with
			// no opacity
			$('#overzichtImg-out').show();
			$('#overzichtImg').hide().attr('src', src);
			
			$('#overzichtImg').bind('load', function() {
				fadeInItem($(this));
				$(this).unbind('load');
			});
			return;
		});
		// Preload image
		$('<img />').attr('src', $(this).attr('href'));		
	});
});

/* Fade an item in, use for callback */
function fadeInItem(item) {
	// Fade out the "out" item
	$('#overzichtImg-out').fadeOut('slow', function() {
		$('#overzichtImg-out').attr('src', $('#overzichtImg').attr('src'));
	});
	$('#overzichtImg').fadeIn('slow');
}

/* Load item cover */
function loadCover(item) {
	$('#coverImg').attr('src', $(item).attr('href'));
}

