(function($) {
	$.fn.overlay = function(settings, callback) {
		var config = {
			color: "#000",
			opacity: .7,
			className: "overlay",
			speed: 200,
			width: "auto",
			height: "auto",
			close: null,
			open: null,
			zIndex: 90
		};

		if (settings) $.extend(config, settings);

		var doc = $(document);
		var win = $(window);

		this.each(function() {

			var $elem = this;
			$("<div/>").attr("id", "overlay").css({
				"background-color": config.color,
				opacity: 0,
				position: "absolute",
				width: doc.width() + "px",
				height: doc.height() + "px",
				"z-index": config.zIndex,
				top: 0,
				left: 0
			}).click(function() {
				$(this).fadeOut(config.speed).remove();
				$("." + config.className).fadeOut(config.speed, function() {
					if (config.close) config.close.call($elem);
				}).remove();
			}).appendTo($(document.body))
			.animate({
				opacity: config.opacity
			}, config.speed);

			var content = $("<div/>", {className: config.className}).css({
				"z-index": config.zIndex + 10,
				position: "absolute",
				margin: "0 auto",
				opacity: 0,
				width: config.width,
				height: config.height
			})
			.append(
				$("<div/>").css({
					"text-align": "right",
					"z-index": 999,
					position: "relative",
					cursor: "pointer"
				}).click(function() {
					$("#overlay").click();
				}).text('Close')				
			);

			content
			.append($(this))
			.appendTo($(document.body))
			.css({
				left: Math.max(doc.scrollLeft() + (win.width() - content.outerWidth()) / 2, 10) + "px",
				top: Math.max(doc.scrollTop() + (win.height() - content.outerHeight()) / 2, 40) + "px"
			})
			.animate({
				opacity: 1
			}, config.speed, function() {
				$('#overlay').css({height: doc.height() + 'px'});
				if (callback || config.open) {
					(callback || config.open).call($elem);
				}
			
				win.keypress(function(event) {
					if (event.keyCode == 27) {
						$("#overlay").click();
						$(this).unbind();
					}
				});
			});
		});
		
		return this;
	};
})(jQuery);
