/***** Popup window *****/
var PopupWindow = Class.create();

PopupWindow.prototype = {
	initialize: function (id, class_name, style) {
		this.FrameClass = "quick_search_box";
		this.AutoAdjust = false;
		this.FrameStyle = {
			top: 55 + "px",
			left: 250 + "px",
			width: 560 + "px"
		};
		this.Id = "";
		this.Parent = {Id: "", ToClose: true};

		this.CloseClass = "popup_close_button";
		if (id != "") {
			this.Id = id;
		}
		if (class_name != "") {
			this.FrameClass = class_name;
		}
		this.FrameStyle = $H(this.FrameStyle).merge(style);
	},

	setParent: function (parent) {
		this.Parent.Id = parent.Id;
		this.Parent.ToClose = parent.ToClose;
	},

	show: function(title, body, effect) {
		if (this.Parent.Id != "") {
			if (this.Parent.ToClose) {
				new Effect.Fade(this.Parent.Id);
			} else {
				new Effect.Opacity(this.Parent.Id, {duration:0.5, from:1.0, to:0.5});
			}
		}

		var frame_div = $(document.createElement("DIV"));
		if (this.Id != "") {
			frame_div.id = this.Id;
		}
		frame_div.addClassName(this.FrameClass);
		if (this.AutoAdjust) {
			this.adjustPosition();
		}
		frame_div.setStyle(this.FrameStyle);

		var close_div = $(document.createElement("DIV"));
		close_div.addClassName(this.CloseClass);
		close_div.setStyle({width: this.FrameStyle.width});

		var close_a = $(document.createElement("A"));
		close_a.href = "javascript: void(0)";
		close_a.update('<img src="http://seamap.env.duke.edu/prod/mapservice/googlemaps/skins/icons/icon_close_popup.gif" border=0>');
		close_a.observe('click', this.close.bindAsEventListener(this));
		close_div.appendChild(close_a);

		var body_div = $(document.createElement("DIV"));
		body_div.update(body);

		frame_div.appendChild(close_div);
		frame_div.appendChild(body_div);

		document.getElementsByTagName("BODY")[0].appendChild(frame_div);

		if (effect) {
			new Effect.Appear(frame_div, {duration:1.0});
		} else {
			frame_div.show();
		}

		this.PopupDiv = frame_div;
		return this.Id;
	},

	close: function () {
		$(this.PopupDiv).hide();

		if (this.Parent.Id != "") {
			if (!this.Parent.ToClose) {
				new Effect.Opacity(this.Parent.Id, {duration:0.5, from:0.5, to:1.0});
			}
		}
		this.destroy();
	},

	destroy: function () {
		this.PopupDiv.remove();
	},

	adjustPosition: function () {
		// Adjust top and left so that the popup window stays in the visible area of the browser.
		var style = this.FrameStyle;
		if (style.height && !isNaN(parseInt(style.height))) {
			var height = parseInt(style.height);
		} else {
			var height = 0;
		}
		var top = Math.max(0, Math.min(parseInt(style.top), gWinH - height));
		var left = Math.max(0, Math.min(parseInt(style.left), gWinW - parseInt(style.width) - 50));	// 50 is a arbitrary buffer
		this.FrameStyle = $H(this.FrameStyle).merge({top: top + "px", left: left + "px"});
	}
}