﻿var popupEnabled = 0;

jQuery.showBackgroundFade = function() {
	$("#popup-loader").html('<div id="popup-background"></div><div id="popup-indicator"></div>');
	$("#popup-background").fadeIn("slow");
	$.centerElement("#popup-indicator");
	$("#popup-indicator").fadeIn("slow");
};

jQuery.showPopup = function() {
	if(popupEnabled == 0) {
		popupEnabled = 1;
		$("#popup-indicator").hide();
		$.centerElement("#popup");
		$("#popup").fadeIn("slow");
	}
}

jQuery.hidePopup = function() {
	$("#popup-indicator").hide();
	$("#popup-background").fadeOut("slow");
	$("#popup").fadeOut("slow")
	$("#popup").removeAttr("style")
	popupEnabled = 0;
}

jQuery.centerElement = function(element) {
	var windowWidth = document.documentElement.clientWidth;
	var windowHeight = document.documentElement.clientHeight;
	var scrollHeight = document.body.scrollTop;
	var popupHeight = $(element).height();
	var popupWidth = $(element).width();
	
	if(!document.body.scrollTop) scrollHeight = document.documentElement.scrollTop;

	$(element).css({
		"position": "absolute",
		"top": windowHeight/2-popupHeight/2+scrollHeight-15,
		"left": windowWidth/2-popupWidth/2
	});	
}

$(document).ready(function() {
	$(".viewer").click(function(e) {
	    e.preventDefault();
	    href = $(this).attr("href");
	    title = $(this).attr("title");
	    $("#popup-area").html("<img id='popup-image' src='" + href +"' />");
		$("#popup-text").html(title);
		$.showBackgroundFade();
	    $("img").load(function(){
			$.showPopup();
			$("#popup-image").click(function() {
				$.hidePopup();
			});
		});
	});
	$("#popup-close").live("click", (function() {
		$.hidePopup();
	}));
	$("#popup-background").live("click", (function() {
		$.hidePopup();
	}));
	$(document).keypress(function(e) {
		if(e.keyCode == 27 && popupEnabled == 1) {
			$.hidePopup();
		}
	});
});