var FormDialog = Class.create({
	
	initialize: function(formWrapper, triggers, cancelButtons) 
	{
		if (!$('overlay')) Element.insert(document.body, { bottom: '<div id="overlay"></div>' });

		Element.insert(document.body, { bottom: '<div id="dialog-'+formWrapper+'" class="dialogWrapper"><div class="dialog"></div></div>' });
		this.overlay 				= $('overlay');
		this.dialogWrapper			= $('dialog-'+formWrapper);
		this.dialog 				= this.dialogWrapper.down(); //$('dialog');
		this.selectElements			= $$('select');
		
		this.overlay.hide();
		
		this.dialog.appendChild($(formWrapper));
		
		this.dialogHeight = this.dialogWrapper.offsetHeight/2;
		this.dialogWrapper.hide();
		
		cancelButtons.each(function(button)
		{		
			switch(button.position)
			{
				case 'before':
					Element.insert(button.posElement, { before: button.button } );
					break;
				case 'top':
					Element.insert(button.posElement, { top: button.button } );
					break;
				case 'bottom':
					Element.insert(button.posElement, { bottom: button.button } );
					break;
				default:
					Element.insert(button.posElement, { after: button.button } );
					break;
			}
			
			Element.observe(button.buttonID, 'click', function(e)
			{
				this.hide();
				Event.stop(e);
				
			}.bind(this));
			
		}.bind(this));

		var links = $$(triggers);
		
		links.each(function(link) 
		{
			Element.observe(link, 'click', function(e) 
			{
				this.appear();
				Event.stop(e);
			}.bind(this));
			
		}.bind(this));
	},
	
	appear: function()
	{
		this.selectElements.each(function(selectElement)
		{
			if (!selectElement.hasClassName('show')) selectElement.hide();
		});
		
		var dialogTop = (document.viewport.getHeight()/2) - this.dialogHeight + document.viewport.getScrollOffsets()[1];
		this.dialogWrapper.style.top = dialogTop + 'px';
		
		var viewportHeight 	= document.viewport.getHeight();
		var bodyHeight		= document.body.offsetHeight;
		
		if (viewportHeight > bodyHeight) this.overlay.style.height = viewportHeight + 'px';
		else this.overlay.style.height 	= bodyHeight + 'px';
		
		new Effect.Appear('overlay',
		{
			duration: 		0.5,
			to: 			0.5, 
			afterFinish: 	function() 
			{
				new Effect.Parallel([new Effect.SlideDown(this.dialogWrapper), new Effect.Appear(this.dialogWrapper)], 
				{ 
				  	duration: 1
				});
			}.bind(this)
		});
	},
	
	hide: function()
	{
		new Effect.Parallel([new Effect.SlideUp(this.dialogWrapper), new Effect.Fade(this.dialogWrapper)], 
		{ 
		  	duration: 		1,
			afterFinish: 	function() 
			{
				new Effect.Fade(this.overlay, 
				{ 
					duration: 		0.3,
					afterFinish:  	function()
					{
						this.selectElements.each(function(selectElement)
						{
							selectElement.show();
						});
					}.bind(this)
				});
			}.bind(this)
		});
	}
});

