$(document).ready(function() {
	
	
	$('#images .container .image:last').addClass('last-child');
	
	$.ifixpng("img/pixel.gif");
	$('.left').ifixpng();
	$('.right').ifixpng();

	$('.image').each(function() {
		var img = $(this).attr('name');
		gallery.load_thumbnail(img);
	});
	
	$('.image').click(function() {		
		// $('#view .container').load('view.php?img='+$(this).attr('name'));
		$.get('view.php?img='+$(this).attr('name'),function(r) {
			$('#view .container').get(0).innerHTML = r;
		});
		
		gallery.next = $('#images .image:first');
		gallery.prev = $('#images .image:last');
		
		if ($(this).next('span').length > 0) {
			gallery.next = $(this).next('span');
		}
		if ($(this).prev('span').length > 0) {
			gallery.prev = $(this).prev('span');
		}
	});

	
	$('#images .image:first').click();

	
	$('#images .left').mousedown(function() {
		gallery.go(-1);
	});

	$('#images .right').mousedown(function() {
		gallery.go(1);
	});

	$('#view .left').mousedown(function() {
		if (gallery.prev) gallery.prev.click();
	});

	$('#view .right').mousedown(function() {
		if (gallery.next) gallery.next.click();
	});
	
});

gallery = {
	
	SCROLLING_SPEED: 0.75,
	
	_load_timer: 500,
	
	next: null,
	prev: null,
	
	
	load_thumbnail: function(aImage) {

		// Delay between loading two images (absolute value)
		this._load_timer += 50;
		
		setTimeout(function() {
			
			// Preload the image
			var i = new Image();
			i.src = 'pics/small/' + aImage;
										
			setTimeout(function() {
				// Go check if the image did already load.
				gallery.did_load(aImage,i);
			},100);


		}, this._load_timer);


	},
	
	did_load: function(aImage,i) {
				
		if (!i.complete) {
			// Try again after a little delay.
			setTimeout(function() { gallery.did_load(aImage,i); },100);
			return;
		}


		// Image did load, show it in the browser, animatable.
		$('.image[name='+aImage+']')
			.removeClass('chaosys-loading')
			.children('img')
			.attr('src',i.src)
			.css('visibility','visible')
			.fadeTo(500,1).animate({opacity:1});
		
	},
	
	

	go: function(dir) {


		$(document.body).mouseup(function() {
			$('#images .container').stop();
		});	
		
		var container	= $('#images');
		var strip 		= $('#images .container');
	
		// The strip should have a margin on both sides...
		var strip_w		= parseInt(strip.css('margin-left'))*2;
		// ...or not.
		if (isNaN(strip_w)) strip_w = 0;
	
		// Add the width of all images to get the total width of the strip.
		strip_w += strip.width();
		
		
		var container_w	= container.width();
	
		// The current position inside the container.
		var current_left = parseInt(strip.css('left'));

		if (dir==1) { // right
			var left = container_w - strip_w;
			var duration = (current_left - left) / this.SCROLLING_SPEED + 500;
			strip.animate({left: left},duration);
		}
		else { // left
			var left = 0;
			var duration = (left - current_left) / this.SCROLLING_SPEED + 500;
			strip.animate({left: left},duration);
		}                       		

	}
	
	
}
