Element.implement({
	centre: function (parent) {
		this.setStyle('display', 'block');
	
		var size = this.getSize();
		var container = window.getSize();
		
		if (parent) {
			container = $(parent).setStyle('position', 'relative').getSize();
		}
		
		this.setStyles({
			'position': 'fixed',
			'top': (container.y - size.y) / 2,
			'left': (container.x - size.x) / 2
		});
		
		return this;
	},
	
	maximise: function (parent) {
		this.setStyle('display', 'block');

		this.store('original_size', this.getCoordinates());
		var container = window.getScrollSize();
		
		if (parent) {
			container = $(parent).setStyle('position', 'relative').getScrollSize();
		}
		
		this.setStyles({
			'position': 'fixed',
			'top': 0,
			'left': 0,
			'width': container.x,
			'height': container.y
		});
		
		return this;
	},
	
	restore: function () {
		return this.setStyles(this.retrieve('original_size'));
	},
	
	hide: function() {
		return this.setStyle('display', 'none');
	}
});

var PopupDialog = new Class({

	Implements: Options,

	dialogOpen: false,
	overlay: null,
	dialog: null,
	callback: null,
	closeCallback: null,

	options: {
		overlayId: 'pageOverlay',
		actionSelector: 'a[rel=action]'
	},

	initialize: function(dialog, options) {
		this.dialog = $(dialog);
		this.setOptions(options);
		
		this.overlay = new Element("div", { 'id': this.options.overlayId }).addEvent("click", this.closeDialog.bindWithEvent(this));
		$(document.body).adopt(this.overlay)

		window.addEvent('resize', this.repositionDialog.bindWithEvent(this));
		window.addEvent('scroll', this.repositionDialog.bindWithEvent(this));
		
		document.addEvent('keyup', function(e) {
			if (e.key == 'esc') {
				this.closeDialog();
			}
		}.bindWithEvent(this));
		
		this.dialog.getElements(this.options.actionSelector).addEvent('click', function (e) {
			e.stop();
			
			this.closeDialog();
			if (this.callback) this.callback(this);
		}.bindWithEvent(this));
	},

	repositionDialog: function() {
		if (this.dialogOpen) {
			this.overlay.restore().maximise();
			this.dialog.centre();
		}
	},
		
	openDialog: function() {
		this.dialogOpen = true;
		
		this.repositionDialog();
	},
	
	closeDialog: function() {
		this.dialogOpen = false;
		
		this.overlay.restore().hide();
		this.dialog.hide();
		
		if (this.closeCallback) this.closeCallback(this);
	}
});

