$(window).load(function () {
	var lastPosition = 0;
	
	var wd = $('#window');
	var chs = $.map(wd.children(), function (a) {
		return $(a).width()+34;
	});
	var len = chs.length;
	var wd_width = 0;
	var img_width = 0;
	for (var i = 0; i < len; i++) {
		wd_width += chs[i];
		img_width = chs[i];
	}
	wd.width(wd_width);
	var total_holes = Math.ceil(len / 5);
	var holes_distance = Math.floor($('#sliderframe').width() / total_holes);
	for (var i = 0; i < total_holes; i++) {
		$('#holes').append(
			$(document.createElement('div')).addClass('hole')
				.css('left', (i+1) * holes_distance - 0.5 * holes_distance)
		)
	}
	$('#slider').hide().css('left', (0.5*holes_distance)+'px');
	$('#holes').children('.hole:nth-child(1)').addClass('fillhole');
	
	lastPosition = (0.5)*holes_distance;
	
	$('#sliderframe').bind('click', function (e) {
			var x = e.pageX - $('#sliderframe').offset().left;
			var min_d = 100000;
			var target = null;
			var c = 0;
			var target_c = 0;
			var target_pos = 0;
			
			$('#holes').children('.hole').each(function () {
				var hole = $(this); c += 1;
				if ((p = Math.abs((q = parseInt(hole.css('left'))) - x)) < min_d) {
					min_d = p;
					target_pos = q;
					target = hole;
					target_c = c-1;
				}
			})

			if (target) {
				var finAnimate = function () {
					target.addClass('fillhole');
					$('#slider').hide();
					$('#frame').css('opacity', 1);
				};
				
				if (Math.abs(target_pos - parseInt($('#slider').css('left'))) < 6) {
					return;
				}
				
				animDelay = Math.min(Math.abs(lastPosition - target_pos)*1.5, 800);

				$('#frame').css('opacity', 0.4);
				$('#slider').show().animate({ left : target_pos }, animDelay);
				lastPosition = target_pos;
				
				target.parent().children().removeClass('fillhole');
				if (target_c == total_holes-1) {
					var targetX = wd_width - 5 * img_width;
					$('#window').animate({ left : -(targetX) }, animDelay, finAnimate);
				} else {
					var targetX = target_c * 5 * img_width;
					$('#window').animate({ left : -targetX }, animDelay, finAnimate);
				}
			}
			
		})
	
});