// modal plugin
(function($) {
		  
	$.fn.extend({
				
		modalPanel: function() {
			
			// hide function
			function modalHide() {
				
				$(document).unbind("keydown", handleEscape);
				
				var remove = function() { $(this).remove(); };
				
				overlay.fadeOut(remove);
				modalWindow.fadeOut(remove).empty();
				
			}
			
			// escape listener
			function handleEscape(e) {
				
				if(e.keyCode == 27) {
					
					modalHide();
					
				}
				
			}
			
			// create overlay object
			var overlay = $("<div id='modal-overlay'></div>");
			// create modal window
			var modalWindow = $("<div id='modal-window'></div>");
			
			return this.each(function() {
									  
				// listen for click passed to the object
				$(this).click(function(e) {
				
					// append overlay to the document
					$("body").append(overlay.click(function() { modalHide(); }));
					
					// add loader animation
					$("body").append("<div id='modal-load'></div");
									 
					// set css and fade in overlay
					overlay.css("opacity", 0.8);
					overlay.fadeIn(150);
					
					// prevent default link behaviour
					e.preventDefault();
					
					// activate close listener
					$(document).keydown(handleEscape);
					
					// image loader
					var img = new Image();
					
					$(img).load(function () {
										  
						var imageWidth = img.width / 2;
						var imageHeight = img.height / 2;
						
						modalWindow.css({"margin-left": -imageWidth, "margin-top": -imageHeight});
						
						// remove loader image
						$("#modal-load").remove();
						
						modalWindow.append(img);
						$(this).addClass("modal-image");
						$("body").append(modalWindow);
						modalWindow.fadeIn(50);
						
					}).attr({ src: this.href }).click(function() { modalHide(); });
					
				});
					
			});
			
		}
				
	});

})(jQuery);