;(function ($) {$(function () {
	/* WARINING: order in which $(window).resize handlers is attached matters */
	
	// zoom behavior
	$('.zoom').each(function () {
		var $z = $(this);
		var $img = $z.find('img');
		var handler;
		$z.mousemove(function (e) {
			/* fix no horizontal scrolling
			var z_w = $z.width();
			var x = e.pageX - $z.offset().left; (x > 0) || (x = 0); x < z_w || (x = z_w - 1);
			var left = (z_w - $img.width()) * x / z_w;
			*/
			var z_h = $z.height();
			var y = e.pageY - $z.offset().top; (y > 0) || (y = 0); y < z_h || (x = z_h - 1);
			var top = (z_h - $img.height()) * y / z_h;
			$img.css({/* 'margin-left': left,*/ 'margin-top': top}); // fix: no horizontal scrolling
		});
		$z.init = function () {
			var left = ($z.width() - $img.width()) * 0.5;
			var top = ($z.height() - $img.height()) * 0.5;
			$img.css({'margin-left': left, 'margin-top': top}); // no horizontal scrolling
		};
		$img.load($z.init);
		$(window).load($z.init).resize(function () {
			setTimeout($z.init, 10);
		});
	});
	
	// fix gallery to have width which can fit 6 elements of equal width with pixel precision
	$('.gallery').each(function () {
		var $gal = $(this);
		$gal.fix = function () {
			var base_w = $gal.parent().width() - 20;
			var fix_w = base_w % 6;
			$gal.width($gal.parent().width() - fix_w);
			$gal.css('padding-left', fix_w);
			var $thumbs = $gal.not('.big').find('.thumb'); $thumbs = $thumbs.add($thumbs.find('img'));
			$thumbs.css({
				width: (base_w - fix_w) / 6,
				height: 'auto'
			}).each(function () {$(this).height($(this).height());});
		};
		$gal.fix();
		$(window).resize($gal.fix).load($gal.fix);
	});
	
	// disable tooltips from `alt` attribute in IE
	$('.thumb img').each(function () {
		if ( ! $(this).attr('title')) $(this).attr('title', '');
	});
	
	// fit image to its parent and auto center
	$('.js-fit').each(function () {
		var $el = $(this);
		var MAX_TOP_MARGIN = $el.attr('js-fit-top-limit') || 0.5;
		$el.init = function () {
			$el.css({width: 'auto', 'height': 'auto'});
			$el.ratio = $el.width() / $el.height(); // init ratio
			$el.fit();
			$el.parent().css('overflow', 'hidden');
		};
		$el.fit = function () {
			var p_w = $el.parent().width();
			var p_h = $el.parent().height();
			if ( ! $el.ratio) return; // no fitting unless image is loaded to know it's dimention ratio
			if ($el.width() / p_w < $el.height() / p_h) { // fit to width
				var top_margin = 1 - p_h / $el.height();
				$el.width(p_w); $el.css('margin-left', 0);
				$el.height('auto');
				var top_margin = 0.5 * (1 - p_h / $el.height());
				$el.css('margin-top', - Math.min(top_margin, MAX_TOP_MARGIN) * $el.height());
			} else { // fit to height
				$el.height(p_h); $el.css('margin-top', 0);
				$el.width('auto'); $el.css('margin-left', (p_w - $el.width()) * 0.5);
			}
		};
		$el.load($el.init);
		$(window).resize($el.fit);
		$(window).load($el.init); // in case if images is already buffered
	});

	// scroll element content
	$('.js-scroll-y').each(function () {
		var $el = $(this); $el.wrap('<div class="js-scroll-y-wrap" style="width:100%; height:100%; overflow:hidden" />');
		$el.parent = $el.parent();
		$el.speedRatio = 0; // [-1, 1], 1 and -1 = close to border, 0 = outside triggering area
		$el.shift = -$el.parent.scrollTop(); // in pixels
		$el.init = function () {
			$el.minShift = $el.parent.height() - $el.height(); $el.minShift <= 0 || ($el.minShift = 0);
			$el.triggerArea = $el.parent.height() / 4;
			$el.step = $el.parent.height() / 100;
		};
		$el.init();
		
		$el.anim = function () {
			$el.shift += $el.speedRatio * $el.step;
			if ($el.speedRatio > 0 && $el.shift > 0) $el.shift = 0;
			if ($el.speedRatio < 0 && $el.shift < $el.minShift) $el.shift = $el.minShift + 1;
			$el.parent.scrollTop(-$el.shift);
			if ( ! $el.speedRatio) {
				$el.animStop();
			}
		};
		$el.animStart = function () {
			if ( ! $el.interval && $el.speedRatio) {
				$el.interval = setInterval($el.anim, 10);
				$el.css('cursor', 'pointer');
			}
		};
		$el.animStop = function (d) {
			if ($el.interval) {
				clearInterval($el.interval);
				$el.interval = false;
				$el.css('cursor', 'auto');
			}
		};
		$el.mousemove(function (e) {
			var y = e.pageY - $el.parent.offset().top;
			if (y < $el.triggerArea && $el.shift < 0) { // up
				$el.speedRatio = 1 - y / $el.triggerArea;
			} else if ($el.parent.height() - y <=  $el.triggerArea  && $el.shift > $el.minShift) { // down
				$el.speedRatio = ($el.parent.height() - y)  / $el.triggerArea - 1;
			} else {
				$el.speedRatio = 0;
			}
			if ($el.speedRatio) {
				$el.animStart();
			} else {
				$el.animStop();
			}
		}).hover($el.mousemove, $el.animStop);
		$(window).resize(function () {
			setTimeout(function () {
				var _minShift = $el.minShift;
				$el.init();
				$el.shift *= _minShift ? $el.minShift / _minShift : 0;
				$el.anim();
			}, 1);
		}).load($el.init);
	});
	
	// gallery navigation
	$('.gallery.thumbs').each(function () {
		var $galleries = $('.gallery').add('.description, .js-scroll-y-wrap');
		var $gal = $(this).add($(this).parent('.js-scroll-y-wrap')); $gal.thumbs = $gal.find('a.thumb'); $gal.total = $gal.thumbs.length;
		var $nav = $('.gallery-navigation'); $nav.next = $nav.find('a.next'); $nav.prev = $nav.find('a.prev');
		var $preview = $('.gallery.preview'); $preview.left = $preview.find('.thumb.left'); $preview.right = $preview.find('.thumb.right');
		var $detailed = $('.gallery.detailed'); $detailed.desc = $('.description');
		var $desc = $('.gallery.text');
		
		$gal.navTo = function (hash) {
			if ('#thumbnails' == hash || '#desc' == hash) $gal.no = $gal.no || 1; else $gal.no = parseInt(hash.replace(/^.*#/, '')) || 1;
			
			$gal.no = ($gal.no - 1) % $gal.total + 1; $gal.no += $gal.no % 2; // fix no to be in range of availabe images and even number since we navigate by 2
			if ($gal.no < $gal.total) {
				$nav.next.attr('href', '#' + ($gal.no + 2).toString());
			} else {
				$nav.next.attr('href', '#desc');
			}
			if ($gal.no > 2) {
				$nav.prev.attr('href', '#' + ($gal.no - 2).toString());
			} else {
				$nav.prev.attr('href', '#desc');
			}
			
			if ('#desc' == hash) {
				$galleries.hide(); $desc.show();
				$nav.prev.attr('href', '#' + $gal.total);
				$nav.next.attr('href', '#2');
			} else {
				if ('#thumbnails' == hash) {
					$(window).resize(); // fix for IE to rescroll thumbs
					$galleries.hide(); $gal.show(); $(window).resize();
				} else {
					if ($preview.is(':hidden')) {
						$preview.find('img').attr('src', '');
					}
					$preview.left.find('img').attr('src', $gal.thumbs.eq($gal.no - 2).attr('rel'));
					$preview.right.find('img').attr('src', $gal.thumbs.eq($gal.no - 1).attr('rel'));
					$preview.left.find('.foot').html($gal.no - 1);
					$preview.right.find('.foot').html($gal.no);
					$galleries.not($preview /* esclude so we don't blink */).hide(); $preview.show();
					$(window).resize();
				}
			}
		};
		$gal.thumbs.add($nav.find('a')).click(function () {$gal.navTo($(this).attr('href'));});
		$gal.navTo(location.hash.toString());
		
		$preview.find('.thumb').click(function () {
			var $target = $(this).hasClass('left') ? $gal.thumbs.eq($gal.no - 2) : $gal.thumbs.eq($gal.no - 1);
			$detailed.desc.find('.body').html($target.find('img').attr('alt').replace(/^\n|\n$/g, '').replace(/\n/g, '<br />'));
			$detailed.find('img').attr('src', '').attr('src', $target.attr('rev'));
			$galleries.hide(); $detailed.add($detailed.desc).show();
		});
		
		$detailed.find('.close').click(function () {
			$galleries.hide(); $preview.show();
			$(window).resize();
		});
		
		// expanding without overlay
		$gal.thumbs.hover(function () {
			var exp_ratio = 0.05; // 5%
			var exp_x = Math.round($(this).width() * exp_ratio);
			var exp_y = Math.round($(this).height() * exp_ratio);
			$(this).find('img').css({
				marginTop: -exp_y,
				marginRight: -exp_x,
				marginBottom: -exp_y,
				marginLeft: -exp_x,
				width: $(this).width() + exp_x * 2,
				height: $(this).height() + exp_y * 2
			});
		}, function () {
			$(this).find('img').css({
				marginTop: 0,
				marginRight: 0,
				marginBottom: 0,
				marginLeft: 0,
				width: '100%',
				height: 'auto'
			});
		});
		
		/* // expanding with overlay
		if ( ! $.browser.msie || parseInt($.browser.version.replace(/\..+$/, '')) >= 8) {
			// extend thumbs on mouse over
			$gal.thumbs.hover(function () {
				var exp = 8;
				$(this).height($(this).height()-1);
				$(this).find('img').css({
					position: 'relative',
					left: - ($(this).is(':first-child') ? 0 : ($(this).is(':nth-child(6)') ? exp * 2 : exp)) - 4,
					top: - exp - 4,
					width: $(this).width() + exp * 2,
					height: $(this).height() + exp * 2,
					border: '4px solid white'
				});
			}, function () {
				$(this).find('img').css({
					width: '100%',
					height: 'auto',
					position: 'static',
					border: 'none'
				});
				$(this).height('auto');
			});
		}
		*/
		
		// `zoom` cursor
		var $cur = $('<img src="img/zoom.png" alt="" />').css({
			cursor: 'pointer',
			display: 'none',
			position: 'absolute',
			zIndex: 9999
		}).appendTo(document.body);
		$preview.find('.thumb').hover(function () {
			$cur.show();
		}, function () {
			$cur.hide();
		});
		$(document.body).mousemove(function (e) {
			$cur.offset({
				left: e.pageX,
				top: e.pageY - 10
			});
		}).mousemove();
		
	});	
});})(jQuery);
