$(function() {

	$.fn.centerBox = function() {
		return this.each(function() {
			var s = this.style, w = $(window), b = $(this);
			var top = ($.browser.msie && $.browser.version < 7) ? w.scrollTop() : 0;
			s.left = ((w.width() - b.width()) / 2) + "px";
			s.top = (top + (w.height() - b.height()) / 2) + "px";
		});
	}

	$.showBox = function(url, options) {
		options = options || {};
		options.load = options.load || function() {};

		var overlay = $('<div id="overlay" style="z-index:1001"></div>')
			.css("opacity", "0");
		var box = $('<div id="darkbox" style="z-index:1002;position:fixed;display:none;"></div>');
		$("<a href='#' class='close' style='z-index: 1003' title='Close box'></a>")
			.click(function() { dismiss(); return false; }).appendTo(box);
		if ($.browser.msie) {
			var frame = $('<iframe id="overlay-frame" style="z-index:1000;border:none;margin:0;padding:0;position:absolute;width:100%;height:100%;top:0;left:0" src="javascript:false"></iframe>')
				.css("opacity", "0").appendTo(document.body);
			if (parseInt($.browser.version)<7) {
				box.css("position", "absolute");
				overlay.css("position", "absolute");
				$("html,body").css({width: "100%", height: "100%"});
			}
		}
		overlay.appendTo(document.body).fadeTo(500, 0.7);
		box.appendTo(document.body).addClass("loading").centerBox().fadeIn(1000);

		$(document).keydown(function(e) {
			if (e.keyCode == 27) dismiss(); // dismiss on escape key
		});
		function dismiss() {
			box.fadeOut(500);
			overlay.fadeOut(1000, function() {
				$("#darkbox, #overlay, #overlay-frame").remove();
			});
			$(document).unbind("keydown");
		}
		overlay.click(function() { dismiss(); });

		if (/\.(png|jpg|gif)$/.test(url)) {
			var img = $("<img>");
			img.bind("load", function() {
				box.removeClass("loading").append(img).addClass("loaded").centerBox().each(function() {
					options.load(box.children()[0]);
				});
			}).attr("src", url);
		} else {
			$.get(url, function(html) {
				$(html).appendTo(box);
				box.removeClass("loading").addClass("loaded").centerBox().each(function() {
					options.load(box.children()[0]);
				});
			});
		}
	}

	$("a.external").click(function(e) {
		if (e.shiftKey || e.altKey || e.ctrlKey || e.metaKey) return true;
		var win = window.open(this.href, '_blank');
		if (win) {
			win.focus();
			return false;
		}
		return true;
	});
});

function unrot(string) {
	return string.replace(/[a-zA-Z]/g, function(c) {
		return String.fromCharCode((c <= "Z" ? 90 : 122) >= (c = c.charCodeAt(0) + 13) ? c : c - 26);
	});
}
