$(function () {
	$('.scroll-gallery').each(function () {
		var scrollframe = $('.scrollframe', this);
		var scrollpane = $('.scrollpane', this);
		
		$('a', this).fancybox();
		
		var timerId = false;
		var total = 0;
		var mouseup = true;
		
		$('.prev-button', this).mousedown(function () {
			clearInterval(timerId);
			
			var anim = $({value:0}).animate({value:10}, 500);
			total = 0;
			mouseup = false;
			
			timerId = setInterval(function () {
				var left = scrollpane.position().left+anim[0].value;
				total += anim[0].value;
				
				if (mouseup && total >= 99) {
					clearInterval(timerId);
					timerId = false;
				} else {
					if (left >= 0) {
						scrollpane.css('left', 0);
						clearInterval(timerId);
						timerId = false;
					} else {
						scrollpane.css('left', left);
					}
				}
				
			}, 13);
		}).mouseup(function () {
			mouseup = true;
		});
		
		$('.next-button', this).mousedown(function () {
			clearInterval(timerId);
			
			var anim = $({value:0}).animate({value:-10}, 500);
			total = 0;
			mouseup = false;
			
			timerId = setInterval(function () {
				var left = scrollpane.position().left+anim[0].value;
				var minLeft = scrollpane.outerWidth() - scrollframe.innerWidth();
				total += anim[0].value;
				
				if (mouseup && total <= -99) {
					clearInterval(timerId);
					timerId = false;
				} else {
					if (left <= -minLeft) {
						scrollpane.css('left', -minLeft);
						clearInterval(timerId);
						timerId = false;
					} else {
						scrollpane.css('left', left);
					}
				}
				
			}, 13);
		}).mouseup(function () {
			mouseup = true;
		});
	});
});
