/* Author: 

*/
var overlay_selectors = ['#overlay img.top', '#overlay img.bottom'];

function updateCounter(idx) {
	$('#counter').text(idx+1 + ' of ' + IMAGES.length);
}
var current_idx = 0;
function preloadImage(idx) {
	if (idx == IMAGES.length) {
		idx = 0;
	} else if (idx < 0) {
		idx = IMAGES.length - 1;
	}
	$('<img/>').attr('src', IMAGES[idx].src).load();
}
function showImage(idx) {
	var to_show = IMAGES[idx];
	var curr_img = overlay_selectors.shift();
	$('#caption').hide().html('');
	$('#overlay img').removeClass('opaque');
	$('<img/>').load(function(){
	    var wwidth = $(window).width();
    	var wheight = $(window).height();
		var width,height;
		height = Math.min(wheight, this.height);
		width = Math.round((height / this.height) * this.width);
		if (width > wwidth) {
			width = wwidth;
			height = Math.round((width / this.width) * this.height);
		}
		var left = (wwidth - width) / 2;
		var top = 0;
		if (wheight > height) {
			top = (wheight - height) / 2;
		}
		top = Math.round(top);
		left = Math.round(left);
		$(curr_img).css({left:left, top:top}).attr('src', this.src).addClass('opaque');
		if (to_show.caption) {
			$('#caption').css({left:left}).width(width).html(to_show.caption).show();
		}
	}).attr('src', to_show.src);
	overlay_selectors.push(curr_img);
	updateCounter(idx);
	current_idx = idx;
	window.location.hash = to_show.src;
}
function showNext() {
	var next = current_idx + 1;
	if (next == IMAGES.length) {
		next = 0;
	}
	showImage(next);
	preloadImage(next + 1);
}
function showPrev() {
	var prev = current_idx - 1;
	if (prev < 0) {
		prev = IMAGES.length - 1;
	}
	showImage(prev);
	preloadImage(prev - 1);
}
var OVERLAY = $('#overlay');
function hashChanged(onload) {
    var hash = decodeURIComponent(window.location.hash.substr(1));
	for (var i = 0; i<IMAGES.length; i++) {
		var img = IMAGES[i];
		if (img.src == hash) {
			if (!OVERLAY.is(':visible')) {
				if (onload) {
					OVERLAY.show();
				} else {
					OVERLAY.fadeIn();
				}
			}
			if (i != current_idx) {
				// console.log(hash);
				return showImage(i);
			}
		}
	}
}
function closeOverlay() {
	OVERLAY.fadeOut();
	window.location.hash = '';
}
$(function(){
	if (self.IMAGES) {
		$(window).bind('hashchange', hashChanged);
		if (window.location.hash) {
			hashChanged(true);
		}
		$('a[rel=gallery]').click(function(){
			try {
				var idx = parseInt($(this).attr('id').split('_')[1]);
				showImage(idx);
				OVERLAY.fadeIn();
				preloadImage(idx + 1);
			} catch (e) {
				// log(e);
			} 
			return false;
		
		});
		$('#overlay img').click(showNext);
		$('#counter').click(showNext);
		
		$(document).keyup(function(event){
			if (!OVERLAY.is(':visible')) return;
			if (event.keyCode == 27) {
				closeOverlay();
			} else {
				var s = String.fromCharCode(event.keyCode);
				if (s == 'N' || s == 'K') {
					showNext();
				} else if (s == 'P' || s == 'J') {
					showPrev();
				}
			}
		});
		$('#close').click(closeOverlay);
	}
});






















