$(document).ready(function() {
	// dom ready

	// Fotocontrols verbergen
	$('.fotonav a').hide();
	$('.preloader').css('width','0px');

});

$(window).load(function() {
	// dom loaded

	restoreImageLoad();

	$('.fotocontainer').each(function() {
		var container_id = $(this).attr('id');
		attachImageLoader(container_id);
	});

});

function restoreImageLoad() {
	$('.fotocontainer .image img').each(function() {
		$(this).attr('src', $(this).attr('realsrc'));
	});
}

function attachImageLoader(ImageContainer) {

	// ImageContainer nr achterhalen
	var container_id = ImageContainer.replace('fotocontainer_','');

	// Preloader bepalen en op 0% instellen
	var preloader = '#preloader_' + container_id;
	var preloader_width = 545;

	// Aantal afbeeldingen bepalen
	var images_totaal = $('#' + ImageContainer + ' .image').length;
	var images_loaded = 0;

	$('#' + ImageContainer + ' .image').onImagesLoad({ 
		itemCallback: function(domObject) {
			images_loaded += 1;
			
			// Fotocontrol weergeven
			$('#photocontrol_' + container_id + '_' + images_loaded).fadeIn(150);
			
			// Loader animeren
			var percentage = images_loaded / images_totaal;
			var preloader_current_width = Math.round(preloader_width * percentage);
			
			$(preloader).animate({
				width: preloader_current_width
			}, {
				duration: 250,
				easing: 'linear',
				queue: 'queue_' + container_id
			});
			
			// http://plugins.jquery.com/project/fxqueues
			
			//console.log('container: ' + container_id + ', image ' + images_loaded + '/' + images_totaal + ': ' + preloader_current_width);
		}
	});	
	initPhotoNavigation(container_id);
}

function initPhotoNavigation(container_id) {

	// Easing list: http://gsgd.co.uk/sandbox/jquery/easing/

	var api = $('#fotocontainer_' + container_id).scrollable({
		size: 1,
		items: '#fotocontainer_inner_' + container_id,
		easing: 'jswing',
		speed: 500,
		navi: '#fotonav_' + container_id
	});
	
	$('#fotonav_' + container_id + ' a').each(function() {
		$(this).click(function() {
			$('#fotonav_' + container_id + ' a').removeClass('active');
			$(this).addClass('active');
			return false;
		});
	})
}
