/*************************************************************************************
Name: modalBox.js
Description: Creates a simple modal box
Author: John Kuiphoff

Instructions: 
1. Create a 'modalbox' div that contains your content and  set the display equal to 
   none in your HTML file.
2. Create a 'close' link within the modal box div.
3. Create an 'overlay' div and set the display equal to none in your HTML file.
4. To initialize the modal box, use the following syntax:
   var myModalBox = new Modalbox('IdOfModalBox', 'IdOfCloseButton', 'IdOfOverlay');
************************************************************************************/

// MODAL BOX CLASS
var Modalbox = Class.create(
{

	// CONSTRUCTOR (input: ID of modal box, ID of close button)
	initialize: function(modalBoxID, closeButtonID, overlayID)
	{
		this.modalBoxID = modalBoxID;
		this.closeButtonID = closeButtonID;
		this.overlayID = overlayID;
	},
	
	// DISPLAYS MODAL BOX
	showBox: function()
	{
		// Show Box
		$(this.modalBoxID).show();
		
		// Center Box
		this.centerBox();
		Event.observe(window, 'resize', this.centerBox.bind(this));
		Event.observe(window, 'scroll', this.centerBox.bind(this));
		
		// Show overlay
		Effect.Appear(this.overlayID, { duration: 0.4, from: 0.0, to: 0.25 });
		$(this.overlayID).setStyle({ position: 'fixed' });

		// Set up close handlers
		$(this.closeButtonID).observe('click', this.hideBox.bind(this));

	},
	
	// HIDES MODAL BOX
	hideBox: function()
	{
		// Hide Box
		$(this.modalBoxID).hide();
		
		// Hide Overlay
		Effect.Fade(this.overlayID, { duration: 0.4 });
		
		// Releases event handlers
		Event.stopObserving(window, 'resize', this.centerBox.bind(this));
		Event.stopObserving(window, 'scroll', this.centerBox.bind(this));
		$(this.closeButtonID).stopObserving('click', this.hideBox.bind(this));
		
	},
	
	// CENTERS MODAL BOX IN BROWSER WINDOW
	centerBox: function()
	{
		// Get browser dimensions
		var browserDimensions = document.viewport.getDimensions();

		// Get element dimensions
		var elementDimensions = Element.getDimensions(this.modalBoxID);
		
		// Get scroll dimensions
		var scrollDimensions = document.viewport.getScrollOffsets();
		
		// Calculate halfway points
		var setX = ( browserDimensions.width - elementDimensions.width ) / 2 + scrollDimensions[0];
		var setY = ( browserDimensions.height - elementDimensions.height ) / 2 + scrollDimensions[1];
		
		// Reposition element
		$(this.modalBoxID).setStyle({ position: 'absolute', left: setX+'px', top: setY+'px' });

	}

});