$(function(){
	var gallery = $('#content .gallery');
	var slider = $('.inner', gallery);
	var photos = $('figure', slider);
	var photo_count = photos.length;
	var active_photo = 0;
	
	var scrollbar = $('.scrollbar', gallery);
	var shaft = $('.shaft', scrollbar);
	var thumb = $('.thumb', scrollbar);
	var shaft_width = (shaft.width() - thumb.width());
	var thumbdown = false;

	function scrollToPhoto(n) {
		active_photo = n;
		photo = photos.eq(active_photo);
		pos = photo.position();
		sliderLeft = (pos.left * -1) + (gallery.width() / 2) - (photo.width() / 2) - 10;
		thumbLeft = (shaft_width / (photo_count - 1)) * n;
		if (!thumbdown) {
			thumb.stop().animate({left: thumbLeft}, 400);
			slider.stop().animate({left: sliderLeft}, 400);
		} else {
			slider.css({left: sliderLeft});
		}
	}

	photos
	.each(function(i){
		$(this).attr('data-index', i);
	})
	.click(function(){
		scrollToPhoto($(this).attr('data-index'));
	});

	$('.scrollarrow-left', scrollbar)
	.click(function(){
		scrollToPhoto(0);
	});
	$('.scrollarrow-right', scrollbar)
	.click(function(){
		scrollToPhoto(photo_count - 1);
	});
	
	thumb
	.mousedown(function(e){
		e.preventDefault();
		thumbdown = true;
	});
	
	shaft
	.click(function(e){
		offset = scrollbar.offset();
		n = Math.floor(((e.pageX - offset.left) / shaft.width()) * photo_count);
		scrollToPhoto(n);
	});


	$('img', photos)
	.load(function(){
		$(this).closest('figure').css({background: 'transparent'});
		$(this).animate({opacity: 1}, 400);
	})
	.each(function(){
		if (!this.complete) {
			$(this).css({opacity: 0});
		} else {
			$(this).closest('figure').css({background: 'transparent'});
		}
	});

	$(window)
	.load(function(){
		$('#content .gallery figure img').trigger('load');
	});
	$(document.body)
	.mousemove(function(e){
		if (thumbdown) {
			offset = scrollbar.offset();
			l = e.pageX - offset.left - (thumb.width() / 2);
			if (l < 0) l = 0;
			else if (l > shaft_width) l = shaft_width;
			thumb.css({left: l});

			thumbpos = thumb.position();
			n = Math.floor((thumbpos.left / shaft_width) * photo_count);
			scrollToPhoto(n);
		}
	})
	.mouseup(function(){
		if (thumbdown) {
			thumbpos = thumb.position();
			n = Math.floor((thumbpos.left / shaft_width) * photo_count);
			thumbdown = false;
			scrollToPhoto(n);
		}
	});

	scrollToPhoto(active_photo);
});