
function fitDimensions(input_width, input_height, target_width, target_height) {
	r = Math.min(target_width / input_width, target_height / input_height);
	if (r > 1) {
		r = 1;
	}
	return {width: Math.min(target_width, Math.round(input_width * r)), height: Math.min(target_height, Math.round(input_height * r)) };
}

function showPopup(popupSource, popupSources, immediately, oldPopup) {
	// the popup elements
	var meta = $(popupSource).metadata();
	var thumb = $(popupSource).find('img.popup-source-img');
	
	var popup = !oldPopup ? {
		wrapper : $('<div style="overflow:hidden; position:absolute; left:0; top:0;" />'), 
		box : $('<div class="loading popup-box" />'),
		label : $('<div class="popup-label" />'),
		closeButton : $('<a href="#" class="cross smallText">close</a>'),
		downloadButton : $('<a href="#" class="download smallText">download</a>'),
		background : $('<div class="popup-background" />'),
		shadow : $('<div class="popup-shadow" />')
	} : oldPopup;
	
	
	// always replace img tags
	popup.box.find('img').remove();
	popup.thumbImg = $('<img />');
	popup.fullView = $('<img />');
	popup.box.append(popup.thumbImg).append(popup.fullView);

	
 	// measure
	var docSize = {width: $(document).width(), height:$(document).height()};
	var shadowScale9 = {top:92,bottom:92,left:92,right:92};
	var popupPadding = {left:92, right:92, bottom:($(window).height()<620) ? 92 : 112 , top:92};
	var popupRect = fitDimensions(meta.width, meta.height, $(window).width() - (popupPadding.left+popupPadding.right), $(window).height() - (popupPadding.top+popupPadding.bottom));
	popupRect.left = popupPadding.left + (($(window).width()- (popupPadding.left+popupPadding.right))  - popupRect.width) / 2;
	popupRect.top = popupPadding.top + (($(window).height()- (popupPadding.top+popupPadding.bottom)) - popupRect.height) / 2;
	
	
	// initialize elements
	popup.box
	.css({
		position:'absolute', 
		textAlign: 'left', 
		left: thumb.offset().left, top: thumb.offset().top, 
		width: thumb.width(), height: thumb.height(),
		opacity: 0.0, 
		zIndex:100
	});
	
	popup.thumbImg
	.attr('src', thumb.attr('src'))
	.attr('width', thumb.width())
	.attr('height', thumb.height())
	.css({position:'absolute'});
	
	popup.fullView
	.attr('src', "/assets/photo/" + meta.image_id + ".jpg?width="+ popupRect.width + "&height=" + popupRect.height)
	.attr('width', popupRect.width)
	.attr('height', popupRect.height)
	.css({position:'absolute'})
	.hide();
	
	popup.label
	.text($(popupSource).find('.popup-source-label').text()).css({position:'absolute', display:'block', opacity:0, zIndex:12, left:popupRect.left, top:popupRect.top+popupRect.height, width:popupRect.width, height:popupPadding.bottom-10});
	
	popup.closeButton
	.css({position:'absolute', opacity:0, zIndex:13, top:popupRect.top-22, right:docSize.width-(popupRect.left+popupRect.width+4)});

	popup.downloadButton
	.css({position:'absolute', opacity:0, zIndex:14, top:popupRect.top-22, left:popupRect.left-4})
	.attr('href', '/assets/photo/' + meta.image_id + '.jpg?download=true');

	popup.shadow
	.css({
		left:(popupRect.left - shadowScale9.left) + ((thumb.offset().left + thumb.width()) - (popupRect.left + (popupRect.width/2)))*0.5, 
		top:popupRect.top - shadowScale9.top, 
		width:popupRect.width + shadowScale9.right + shadowScale9.left, 
		height:popupRect.height + shadowScale9.bottom + shadowScale9.top,
		opacity:0
	});
	
	popup.background
	.css({opacity:0, zIndex:10, width:docSize.width, height:docSize.height});

	popup.wrapper
	.css({opacity:1, zIndex:11, width:docSize.width, height:docSize.height});
	
	
	// add elements to document if necessary
	if (!oldPopup) {
        if (!$.browser.msie) {
            popup.background.append(popup.shadow);
            popup.shadow.css('background-image', 'url(/assets/img/gallery-popup-shadow.png)').scale9Grid(shadowScale9);
        }
		popup.wrapper.append(popup.box).append(popup.label).append(popup.closeButton).append(popup.downloadButton);
		popup.wrapper.append(popup.background);
		$('body').append(popup.wrapper);
	} else {
		if (!$.browser.msie) popup.shadow.layout9Grid();
	}

	
	// start a zoom effect thats starts at the position of the source
	var openPopupDuration = immediately ? 0 : 350;
	var closePopupDuration = 600;
	var openPopupComplete = function () { 
		popup.label.animate({opacity:1}, !oldPopup ? 200 : 0); 
		popup.closeButton.animate({opacity:1}, !oldPopup ? 200 : 0);
		popup.downloadButton.animate({opacity:1}, !oldPopup ? 200 : 0);
		popup.fullView.show(); 
	}
	popup.background.animate( {opacity:0.7}, openPopupDuration );
	if (!$.browser.msie) popup.shadow.animate( {opacity:1, left:popupRect.left - shadowScale9.left}, openPopupDuration );
    popup.thumbImg.animate( {width:popupRect.width, height:popupRect.height}, openPopupDuration );
	popup.box.animate(
			{left:popupRect.left, top:popupRect.top, width:popupRect.width, height:popupRect.height, opacity:1}, 
			{duration:openPopupDuration, complete:openPopupComplete} );

	
	// find current index and set the hash var
	var currentIndex = -1;
 	for (var popupSourceElement=popupSource[0], i=0; i < popupSources.length; i++) {
		if (popupSources[i] === popupSourceElement) {
			currentIndex = i;
			break;
		}
	}
 	setLocationHashVar('photo', currentIndex);
 	

 	// setup navigation actions
 	var unbindKeys = function() {
 		var doc = $(document);
 		doc.unbind('keydown', 'space');
 		doc.unbind('keydown', 'esc');
 		doc.unbind('keydown', 'left');
 		doc.unbind('keydown', 'right');
 	};
 	var unbindMouse = function () {
		popup.background.unbind('click');
		popup.label.unbind('click');
		popup.closeButton.unbind('click');
		popup.box.unbind('click');
 	}
 	var previous = function () {
 		if (currentIndex == 0) {
 			closeAndFinish(); 
 			return;
 		} else {
 			unbindKeys();
 			unbindMouse();
 		}
		showPopup($(popupSources[currentIndex-1]), popupSources, true, popup);
		// move slider and scroll content (rude)
		var scrollbar = $('.scroll-bar'), 
			scrollContent = $('.scroll-content'), 
			leftVal = (scrollContent.css('margin-left') == 'auto' ? 0 : parseInt(scrollContent.css('margin-left'),10)) + thumb.width() + 6, 
			remainder = $('.scroll-pane').width() - scrollContent.width();
		scrollContent.css('margin-left', Math.min(leftVal, 0));
		setLocationHashVar('scroll', -Math.min(leftVal, 0));
		scrollbar.slider("value", Math.round(leftVal / remainder * 100));
 	}
	var next = function () {
 		if (currentIndex+1 >= popupSources.length) {
 			closeAndFinish(); 
 			return;
 		} else {
 			unbindKeys();
 			unbindMouse();
 		}
		showPopup($(popupSources[currentIndex+1]), popupSources, true, popup);
		// move slider and scroll content (rude)
		var scrollbar = $('.scroll-bar'), 
			scrollContent = $('.scroll-content'), 
			leftVal = (scrollContent.css('margin-left') == 'auto' ? 0 : parseInt(scrollContent.css('margin-left'),10)) - (thumb.width() + 6), 
			remainder = $('.scroll-pane').width() - scrollContent.width();
		scrollContent.css('margin-left', Math.max(leftVal, remainder));
		setLocationHashVar('scroll', -Math.max(leftVal, remainder));
		scrollbar.slider("value", Math.round(leftVal / remainder * 100));
	}
	var close = function (immediately) {
		popup.label.stop();
		popup.background.stop(); 
		popup.shadow.stop(); 
		popup.thumbImg.stop(); 
		popup.box.stop();
		popup.closeButton.stop();
		popup.downloadButton.stop();
		unbindKeys();
		popup.background.fadeOut(immediately ? 0 : 'normal');
		popup.thumbImg.animate( {width:thumb.width(), height:thumb.height()}, immediately ? 0 : closePopupDuration);
		popup.label.fadeOut(immediately ? 0 : closePopupDuration*0.35);
		popup.closeButton.fadeOut(immediately ? 0 : closePopupDuration*0.35);
		popup.downloadButton.fadeOut(immediately ? 0 : closePopupDuration*0.35);
		popup.fullView.hide();
		popup.box.animate(
			{left:thumb.offset().left, top:thumb.offset().top, width:thumb.width(), height:thumb.height(), opacity:0}, 
			{duration:immediately?0:closePopupDuration, complete:function(){popup.wrapper.remove()}} );
		unbindMouse();
	};
	var closeAndFinish = function () {setLocationHashVar('photo', null); close(); return false; }
	$(document).bind('keydown', 'space', next);
	$(document).bind('keydown', 'left', previous);
	$(document).bind('keydown', 'right', next);
	$(document).bind('keydown', 'esc', closeAndFinish);
	popup.background.click(closeAndFinish);
	popup.label.click(closeAndFinish);
	popup.closeButton.click(closeAndFinish);
	popup.box.click(next);
}


$(document).ready(function() {
	var pp = $('.popup-source');
	for (var i=0; i < pp.length; i++) {
		var source = $(pp[i]);
		source.click(function(event){
			event.preventDefault();
			showPopup( $(this), pp );
		});
	}
	var photoHV = getLocationHashVar('photo');
	if (photoHV != null) {
		var selectedIndex = parseInt(photoHV, 10);
		showPopup( $(pp[selectedIndex]), pp, true );
	}
});
