(function($){
	$.fn.extend({
		modalPanel: function() {
		    
			var active = 0;
			var data = {};
			
			var len = 0;
			this.each(function(i, elem) {
			    data[i] = {
			        href: $(elem).attr('href'),
			        title: $(elem).attr('title')
			    };
			    $(this).data('index', i);
			    len++;
			});
			
			data.length = len;
			
			var show = function() {
			    loader.show();
			    var img = new Image();
				$(img).load(function() {
				    var ratio = Math.min(1, Math.min(($(window).height() - 50)/img.height, $(window).width()/img.width) );
					img.width = img.width * ratio;
					img.height = img.height * ratio;
				    modalWindow.empty();
				    loader.hide();
					var imageWidth = img.width / 2;
					var imageHeight = img.height / 2;
					modalWindow.css({
						"margin-left": -imageWidth
					});
					
					if ( !(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6
						modalWindow.css({
							"margin-top": -imageHeight - 10
						});
            		}

					$(this).addClass("modal-image");
					modalWindow.show().append(img).append('<span class="title">'+ data[active].title +'</span>');
					$(document).bind('keyup', handleKey);
				}).attr('src', data[active].href);
			}
			
			//Our function for hiding the modalbox
			var hide = function() {
				$(document).unbind("keydown", handleKey);
				var remove = function() { $(this).remove(); };
				overlay.hide();
				modalWindow.empty().hide();
			}
			
			var nextImage = function() {
			    active = active >= data.length-1 ? 0 : active +1;
			    show();
			}
			
			var prevImage = function() {
			    active = active <= 0 ? data.length-1 : active -1;
			    show();
			}
			
			var overlay = $("<div id='modal-overlay'></div>").css('opacity',0.9).appendTo('body').bind('click', hide);
			var modalWindow = $("<div id='modal-window'></div>").hide().appendTo('body').bind('click', nextImage);
			var loader = $("<div id='modal-load'><img src='/media/i/loading.gif'></div>").hide().appendTo('body');
			
			//Our function that listens for escape key.
			var handleKey = function(e) {
			    var code = e.keyCode || e.which;
				if (code == 27) {
					hide();
				}
				if (code == 39) {
				    nextImage();
				}
				if (code == 37) {
				    prevImage();
				}
			}
			
			if (typeof document.body.style.maxHeight === "undefined") { //if IE 6
				$("body","html").css({height: "100%", width: "100%"});
			}
			
			return this.each(function() {
				$(this).click(function(e) {
				    e.preventDefault();
				    overlay.show();
				    active = $(this).data('index');
        			show();
				});
			});
		}
	});
})(jQuery);
