var Dialog = {
	dialogwidth: 400,
	defaultwidth: 400,
	init: function(dialogwidth)
	{
		if (dialogwidth) {this.dialogwidth = dialogwidth;}
		this.overlay = new Element('div').setProperty('id', 'dlgOverlay').setStyles({display: 'none'}).injectInside(document.body);
		this.container = new Element('div').setProperty('id', 'dlgContainer').setStyles({width: this.dialogwidth,  height: '100px', margin: '40px auto', display: 'none'}).injectInside(document.body);
		this.content = new Element('div').setProperty('id', 'dlgContent').injectInside(this.container);
		this.closelabel = new Element('a').setProperty('id', 'dlgClose').injectInside(this.container);
		this.overlay.setStyle('height',  window.getHeight());
		this.container.setStyles({'margin-left': (window.getWidth() - this.dialogwidth) / 2 + 'px'})

		window.addEvent('resize', function(){
			this.overlay.setStyles({top: window.getScrollTop()+'px', height: window.getHeight()+'px'});
			this.container.setStyles({'margin-left': (window.getWidth() - this.dialogwidth) / 2 + 'px'})
		}.bind(Dialog));

		window.addEvent('scroll', function(){
			this.overlay.setStyles({top: window.getScrollTop()+'px', height: window.getHeight()+'px'});
		}.bind(Dialog));

		this.overlay.addEvent('mousedown', function(e){e.stop();})
		
		this.closelabel.set('text','Close');

		this.closelabel.addEvent('click', function(){ Dialog.hide();});
		
	},

	show: function(fragmentURL, dialogwidth)
	{
		
		this.dialogwidth = (dialogwidth) ? dialogwidth : this.defaultwidth;		
		this.container.setStyles({width: this.dialogwidth});
		this.container.setStyles({'margin-left': (window.getWidth() - this.dialogwidth) / 2 + 'px'})
		this.overlay.setStyles({'display':'block', 'opacity':'0'});
		this.overlay.fade(0.7);

		this.container.setStyles({'display':'block', 'opacity':'0'});


		var req = new Request({url:fragmentURL,
			onSuccess: function(html, xml) {
				//Clear the text currently inside the results div.
				this.content.set('text', '');
				//Inject the new DOM elements into the results div.
				this.content.innerHTML = html;
				window.scrollTo(0,0);
				this.container.setStyle('height', $('dlgContent').getHeight());
				this.container.fade(1);
			}.bind(Dialog),
			//Our request will most likely succeed, but just in case, we'll add an
			//onFailure method which will let the user know what happened.
			onFailure: function() {
				this.content.set('html', '<h2>Error</h2><p>Unable to load the dialog fragment.</p>');
				window.scrollTo(0,0);
				this.container.setStyle('height', $('dlgContent').getHeight());
				this.container.fade(1);
			}.bind(Dialog),
			evalScripts: true


		}).send();


		$('dlgContainer').setStyles({'display':'block'});
	},

	hide: function()
	{
		$('dlgContainer').setStyles({'display':'none'});
				$('dlgOverlay').fade('out');
				$('dlgContent').set('text', '');

	}
};

window.addEvent('domready', Dialog.init.bind(Dialog));
