﻿var Dialog = {
	Page: function (sUrl, options) {
		var options = options ? options : {};

		var data = options.data ? options.data : {};
		var bJavaScript = options.loadJS ? options.loadJS : true;
		var iDialogWidth = options.width > 0 ? options.width : 704;

		var dialog = this;

		$.ajax({
			url: sUrl,
			data: data,
			cache: false,
			success: function (content) {
				if (content == "")
					UserSessionExpired();
				else {
					dialog.Content(content, iDialogWidth, function () {
						if (bJavaScript) {
							if (sUrl.indexOf(".asp") == -1)
								sUrl += "Default.asp";

							jQuery.getScript(sUrl + ".js");
						}

						if (options.success != undefined)
							options.success();
					});
				}
			}
		});
	},

	Content: function (content, iDialogWidth, callback) {
		if ($("#site-overlay").length == 0) {
			var iWndWidth = $(window).width();
			var iWndHeight = $(window).height();
			var iDocWidth = $(document).width();
			var iDocHeight = $(document).height();
			var iWndScrollTop = $(window).scrollTop();
			var iWidth = iWndWidth > iDocWidth ? iWndWidth : iDocWidth;
			var iHeight = iWndHeight > iDocHeight ? iWndHeight : iDocHeight;

			$("body").prepend($("<div>")
				.attr("id", "site-overlay")
				.css({ width: iWidth, height: iHeight, opacity: 0.65 })
			);

			$("body").prepend($("<div>")
							.attr("id", "dialog")
							.css({ left: (iWndWidth - iDialogWidth) / 2, top: iWndScrollTop + 50, width: iDialogWidth })
							.append($("<a>")
								.addClass("close")
								.click(function () { Dialog.Close() })
							)
							.append($("<div>")
								.addClass("body clear")
								.html(content)
							)
						);

			$(window).bind("resize", this.modalPosition);
			$(document).bind("keydown", this.modalShortCutKeys);
		}
		else
			$("#dialog .body").html(content);

		if (callback != undefined)
			callback();
	},

	Close: function () {
		$("#dialog").remove();
		$("#site-overlay").remove();

		$(window).unbind("resize", this.modalPosition);
		$(document).unbind("keydown", this.modalShortCutKeys);
	},

	modalPosition: function () {
		var iWndWidth = $(window).width();
		var iWndHeight = $(window).height();
		var iDocWidth = $(document).width();
		var iDocHeight = $(document).height();
		var iWidth = iWndWidth > iDocWidth ? iWndWidth : iDocWidth;
		var iHeight = iWndHeight > iDocHeight ? iWndHeight : iDocHeight;

		$("#site-overlay").css({ width: iWidth, height: iHeight });
		$("#dialog").css({ left: (iWndWidth - $("#dialog").width()) / 2 });
	},

	modalShortCutKeys: function (e) {
		switch (e.keyCode) {
			case 27:
				CloseModal();
		}
	}
};


function UserSessionExpired() {
	window.location.reload();
}
