var timeout;
var first = true;
function nextImage() {
	if (!first)
		$.galleria.next();
	first = false;
	timeout = setTimeout("nextImage()", 4000);
}

function stopSlideShow() {
	clearTimeout(timeout);
}

function initCallbackFunction(carousel) {
	$('#galleria_container').bind('image-loaded', function () {
		var idx = $('.galleria li.active').data('index') - 3;

		carousel.scroll(idx);
		return false;
	});
};

$(document).ready(function () {
	jQuery('ul.galleria').jcarousel({
		start: 1,
		scroll: 1,
		animation: "fast",
		initCallback: initCallbackFunction
	});

	$('ul.galleria').galleria({
		history: false,
		insert: "#galleria_container",
		onImage: function (image, caption, thumb) { // let's add some image effects for demonstration purposes
			var newLink = $("<a rel=\"shadowbox\"></a>");
			newLink.attr("href", image.attr("src"));
			newLink.append(image.clone());
			image.replaceWith(newLink);

			Shadowbox.setup(newLink, {
				language: "nl",
				players: ["img"],
				path: "/scripts/shadowbox/"
			});

			image = newLink;

			image.hide().fadeIn(500);

			// fetch the thumbnail container
			var _li = thumb.parents('li');

			// fade out inactive thumbnail
			_li.siblings().children('img.selected').fadeTo(500, 0.3);

			// fade in active thumbnail
			thumb.fadeTo('fast', 1).addClass('selected');

			// add a title for the clickable image
			image.removeAttr('width');
			image.removeAttr('height');

			image.click(stopSlideShow);

			// add event
			$('#galleria_container').trigger('image-loaded');

			// to each list item
			$('ul.galleria li').each(function (idx) {

				// add data 'index' with value idx+1
				$(this).data('index', (++idx));
			});
		},
		onThumb: function (thumb) { // thumbnail effects goes here

			// fetch the thumbnail container
			var _li = thumb.parents('li');

			// if thumbnail is active, fade all the way.
			var _fadeTo = _li.is('.active') ? '1' : '0.3';

			// fade in the thumbnail when finnished loading
			thumb.css({ display: 'none', opacity: _fadeTo }).fadeIn(1500);

			// hover effects
			thumb.hover(
								function () { thumb.fadeTo('fast', 1); },
								function () { _li.not('.active').children('img').fadeTo('fast', 0.3); } // don't fade out if the parent is active
							);

			thumb.click(stopSlideShow);
		}

	}).find('li:first').addClass('active');
	// For some reason, if the page is visited again without refresh, the galleria didn't work. This is a fix
	if ($('ul.galleria').find('li:first').find('img').attr('rel') !== undefined)
		$.galleria.activate($('ul.galleria').find('li:first').find('img').attr('rel'));
	if ($('ul.galleria').find('li:eq(1)').length > 0)
		nextImage();
}); 
