var messagebox = {

	_autoReset: true,
	_messageBoxId: "MB_MessageBox",
	_messageBoxContentId: "MB_MessageBoxContent",
	_overlayId: "MB_Overlay",
	_overlayFrameId: "MB_OverlayFrame",
	_loaderId: "MB_Loader",
	_loaderContentId: "MB_LoaderContent",
	_types: { "default": { "className": "MB_Type_Default", "modal": false, "loadMessage": "Loading..."} },
	_type: "default",
	_params: null,
	_iframeElem: null,
	_classFinder: /\b_|\b[a-z0-9]\w*\b/ig,

	get_autoReset: function()
	{
		if (arguments.length !== 0) { throw "Invalid number of arguments."; }
		return this._autoReset;
	},
	set_autoReset: function(autoReset)
	{
		if (arguments.length !== 1) { throw "Invalid number of arguments."; }
		if (autoReset !== true && autoReset !== false) { throw "Invalid autoReset parameter: autoReset='" + autoReset + "'."; }
		this._autoReset = autoReset;
	},

	get_type: function()
	{
		if (arguments.length !== 0) { throw "Invalid number of arguments."; }
		return this._type;
	},
	set_type: function(type)
	{
		if (arguments.length !== 1) { throw "Invalid number of arguments."; }
		if (typeof (this._types[type]) === "undefined") { throw "Unknown type: type='" + type + "'."; }
		this._type = type;
	},
	set_content: function(html)
	{
		if (arguments.length !== 1) { throw "Invalid number of arguments."; }
		if (typeof (this._messageBoxContent) === "undefined") { throw "Invalid operation: not initialized."; }
		this._messageBoxContent.html(html);
	},
	get_content: function(returnElement)
	{
		if (arguments.length > 1) { throw "Invalid number of arguments."; }
		if (typeof (this._messageBoxContent) === "undefined") { throw "Invalid operation: not initialized."; }
		if (returnElement === true) { return this._messageBoxContent; }
		return this._messageBoxContent.html();
	},
	get_messagebox: function()
	{
		if (arguments.length !== 0) { throw "Invalid number of arguments."; }
		if (typeof (this._messageBox) === "undefined") { throw "Invalid operation: not initialized."; }
		return this._messageBox;
	},

	init: function()
	{
		if (typeof (this._messageBox) === "undefined")
		{
			$("body").append("<div id='" + this._loaderId + "' style='display:none'><p id='" + this._loaderContentId + "'></p></div><div id='" + this._messageBoxId + "' style='display:none'><div id='" + this._messageBoxContentId + "'></div></div>");
			this._loader = $("#" + this._loaderId);
			this._loaderContent = $("#" + this._loaderContentId);
			this._messageBox = $("#" + this._messageBoxId);
			this._messageBoxContent = $("#" + this._messageBoxContentId);
		}
	},

	registerType: function(typeName, params)
	{
		if (arguments.length !== 2) { throw "Invalid number of arguments."; }
		this._types[typeName] = params;
	},

	show: function(msg, type, params)
	{
		if (arguments.length < 1 && arguments.length > 3) { throw "Invalid number of arguments."; }
		this.beginShow(type, params);
		this.endShow(msg);
	},

	beginShow: function(type, params)
	{
		if (arguments.length > 2) { throw "Invalid number of arguments."; }
		if (typeof (type) === "undefined") { if (this._autoReset === true) { this.set_type("default"); } }
		else { this.set_type(type); }

		if (typeof (this._messageBoxContent) === "undefined") { this.init(); }
		this._initParams(params);

		this._messageBox.attr("class", "");
		if (typeof (this._params["className"]) !== "undefined") { this._messageBox.addClass(this._params["className"]); }
		if (typeof (this._params["loadMessage"]) !== "undefined") { this._loaderContent.html(this._params["loadMessage"]); }

		this._showOverlay();
		this._showLoader();
		this._asyncShow = true;
	},

	endShow: function(msg)
	{
		if (arguments.length !== 1) { throw "Invalid number of arguments."; }
		if (typeof (this._asyncShow) === "undefined" || this._asyncShow !== true) { throw "Invalid operation: no aysnchronous show operation in progress"; }
		this._messageBoxContent.html(msg);
		this._hideLoader();
		this._messageBox.show();
		this._asyncShow = false;
	},

	hide: function()
	{
		if (arguments.length !== 0) { throw "Invalid number of arguments."; }
		this._messageBox.hide();
		if (this._asyncShow === true)
		{
			this._hideLoader();
			this._asyncShow = false;
		}
		this._hideOverlay()
	},

	_showLoader: function()
	{
		this._centerElement(this._loader);
		this._loader.show();
	},
	_hideLoader: function()
	{
		if (typeof (this._loader) !== "undefined")
		{
			this._loader.hide();
		}
	},

	_initParams: function(params)
	{
		if (arguments.length !== 1) { throw "Invalid number of arguments."; }
		this._params = this._types[this._type];
		if (typeof (this._params) === "undefined") { this._params = {}; }
		if (typeof (this._types["default"]) !== "undefined") { this._params = $.extend({}, this._types["default"], this._params); }
		if (typeof (params) !== "undefined") { $.extend(this._params, params); }
	},

	_keyExists: function(args, key)
	{
		if (arguments.length !== 2) { throw "Invalid number of arguments."; }
		if (typeof (args) === "undefined" || typeof (args[key]) === "undefined") { return false; }
		return true;
	},

	_createOverlay: function()
	{
		if (arguments.length !== 0) { throw "Invalid number of arguments."; }
		if ($("#" + this._overlayId).length === 0)
		{
			if (typeof document.body.style.maxHeight === "undefined")
			{
				if ($("#" + this._overlayFrameId).length === 0)
				{
					$("body").append("<iframe id='" + this._overlayFrameId + "'></iframe><div id='" + this._overlayId + "'></div>");
				}
			} else
			{
				$("body").append("<div id='" + this._overlayId + "'></div>");
			}
			this._centerElement(this._messageBox);
			this._overlay = $("#" + this._overlayId);
			this._overlayFrame = $("#" + this._overlayFrameId);
		}
	},

	_showOverlay: function()
	{
		if (arguments.length !== 0) { throw "Invalid number of arguments."; }
		if (typeof (this._overlay) === "undefined" || this._overlay.length == 0)
		{
			this._createOverlay();
		} else
		{
			this._overlay.show();
			this._overlayFrame.show();
			this._centerElement(this._messageBox);
		}
		if (this._params["modal"] !== true)
		{
			this._overlay.bind("click", { self: this }, this._onClickCloseEvent);
			$(document).bind("keyup", { self: this }, this._onKeyCloseEvent);
		}
		if (typeof (document.body.style.maxHeight) === "undefined")
		{
			$("body", "html").css({ height: "100%", width: "100%" });
			$("html").css("overflow", "hidden");
		}
	},

	_hideOverlay: function()
	{
		if (typeof (this._overlay) !== "undefined" && this._overlay.length > 0)
		{
			this._overlay.hide();
			this._overlayFrame.hide();
			this._overlay.unbind("click");
			$(document).unbind("keyup");

			if (typeof (document.body.style.maxHeight) === "undefined")
			{
				$("body", "html").css({ height: "auto", width: "auto" });
				$("html").css("overflow", "");
			}
		}
		return false;
	},

	_destroyOverlay: function()
	{
		if (this._overlay.length > 0)
		{
			this._hideOverlay(e);
			this._overlay.unbind("click");
			this._overlayFrame = $("#" + this._overlayFrameId);
			this._overlay = $("#" + this._overlayId);
			this._messageBox = $("#" + this._messageBoxId);
		}
		return false;
	},

	_centerElement: function(elem)
	{
		var elem = $(elem);
		var width = elem.outerWidth();
		var height = elem.outerHeight();
		elem.css({ marginLeft: '-' + parseInt((width / 2), 10) + 'px' });
		if (!(jQuery.browser.msie && typeof XMLHttpRequest == 'function'))
		{ // take away IE6
			elem.css({ marginTop: '-' + parseInt((height / 2), 10) + 'px' });
		}
	},

	_onClickCloseEvent: function(e)
	{
		if (arguments.length !== 1) { throw "Invalid number of arguments."; }
		e.data.self.hide();
		return false;
	},

	_onKeyCloseEvent: function(e)
	{
		if (e.keyCode == 27)
		{
			e.data.self.hide();
			return false;
		}
		return true;
	},

	zoomImage: function(e)
	{
		try
		{
			var image = $("img", this);
			if (image.length == 1)
			{
				if (messagebox.isImageBroken(image[0]))
					return false;

				var src = image.attr("src");
				src = src.replace(/\/thumb\/\d+x\d+/ig, '');
				
				var preloader = new Image();
				preloader.onload = function()
				{
					var title = image.attr("alt");
					var isShrunk = preloader.width > 800;

					var width = isShrunk ? 800 : preloader.width;
					var height = preloader.height * (width / (preloader.width == 0 ? 1 : preloader.width));
					var popupImage = $('<img src="' + preloader.src + '" alt="' + title + '" ' + (isShrunk ? 'width="' + width + 'px"' : '') + ' />');

					$("#MB_MessageBox").css("width", width);
					$("#MB_MessageBox").css("height", height + 30 /* header */);

					messagebox.show(popupImage);
					messagebox.setTitle(title);
				}
				preloader.src = src;
				messagebox.beginShow();
				return false;
			}
		}
		catch (e)
		{
			alert(e);
			return false;
		}
		return true;
	},

	isImageBroken: function(elem)
	{
		// During the onload event, IE correctly identifies any images that
		// weren't downloaded as not complete. Others should too. Gecko-based
		// browsers act like NS4 in that they report this incorrectly.
		if (!elem.complete)
		{
			return true;
		}

		// However, they do have two very useful properties: naturalWidth and
		// naturalHeight. These give the true size of the image. If it failed
		// to load, either of these should be zero.
		if (typeof elem.naturalWidth != "undefined" && elem.naturalWidth == 0)
		{
			return true;
		}

		// No other way of checking: assume it's ok.
		return false;
	},

	openAnchor: function(e)
	{
		var url = $(this).attr("href") || $(this).metadata().href;
		var title = $(this).attr("title");
		var content = $(this).metadata().content;
		var options = messagebox.getOptionsForAnchor(this);

		// Show static content popup
		if (content !== undefined)
		{
			var contentNode = document.getElementById(content);
			if (contentNode)
			{
				messagebox.show("<div>" + contentNode.innerHTML + "</div>", undefined, options);
				messagebox.setTitle(title);
			}
		}
		// Show popup with iframe of current url
		else if (typeof (url) !== "undefined" && url != "" && url != "#")
		{
			if (messagebox._iframeElem == null)
			{
				messagebox._iframeElem = $('<iframe frameborder="0" class="popupframe" src="' + url + '"></iframe>');
			} else
			{
				messagebox._iframeElem.attr("src", url);
			}
			messagebox.show(messagebox._iframeElem, undefined, options);
			messagebox.setTitle(title);
		}
		return false;
	},

	getOptionsForAnchor: function(elem)
	{
		var className = $.trim(elem.className.replace(this._classFinder, ""));
		var options = { className: className };
		return options;
	},

	setTitle: function(title)
	{
		$("#MB_PopupTitle").html(title);
	}
};

$(document).ready(function()
{
	messagebox.init();
	messagebox.registerType("modal", { "className": "MB_Type_DefaultModal", "modal": true, "loadMessage": "Loading..." });
	messagebox.get_content(true).before('<div class="MB_PopupHeader"><h2 id="MB_PopupTitle"></h2><a href="javascript:void(0)" title="Sluit dit venster" id="MB_PopupClose"><span>Sluiten</span></a></div>');
	$("#MB_PopupClose").live("click", function() { messagebox.hide(); return false; });
	$(".messagebox").live("click", messagebox.openAnchor);
	$(".zoomimage").live("click", messagebox.zoomImage);
});
