﻿var modalDialog;

(function() {
	var fx, top, center, overlay;
	
	window.addEvent('domready', function() {
		// Setup all of the elements needed for this
		$(document.body).adopt(
			$$([
				overlay = new Element("div", {id: "lbOverlay"}).addEvent("click", close),
				center = new Element("div", {id: "lbCenter"}),
				bottom = new Element("div", {id: "lbBottom"}).adopt(
					new Element("span", {id: "lbClose", html: "back"}).addEvent("click", close)
				)
			]).setStyle("display", "none")
		);
		
		// Setup the fade in/out effect
		fx = {
			overlay: new Fx.Tween(overlay, {property: "opacity", duration: 500}).set(0)
		};
		
	});
	
	modalDialog = {
		show: function(elId, _options) {
			options = $extend({
				overlayOpacity: 0.8,	// 1 is opaque, 0 is completely transparent (change the color in the CSS file)
				width: 300,				// Width of the box (in pixels)
				height: 225				// Height of the box (in pixels)
			}, _options || {});
			
			position();
			setup(true);
			
			// Start displaying the overlay
			fx.overlay.chain(showCenter).start(options.overlayOpacity);
			
			// Setup the content box and close button
			top = window.getScrollTop() + (window.getHeight() / 15);
			center.set('html', $(elId).innerHTML);
			
			center.setStyles({top: top, height: options.height});
			bottom.setStyle("top", top + options.height + center.getStyle('padding-top').toInt() + center.getStyle('padding-bottom').toInt());
			$$(center, bottom).setStyles({width: options.width, marginLeft: -(options.width / 2)});
			
		}
	}
	
	function showCenter() {
		$$(center, bottom).setStyles({display: ""});
	}
	
	function setup(open) {
		overlay.style.display = open ? "" : "none";

		var fn = open ? "addEvent" : "removeEvent";
		window[fn]("scroll", position)[fn]("resize", position);
	}
	
	function position() {
		overlay.setStyles({top: window.getScrollTop(), height: window.getHeight()});
	}
	
	function close() {
		for (var f in fx) fx[f].cancel();
		$$(center, bottom).setStyle("display", "none");
		fx.overlay.chain(setup).start(0);
	}
	
})();
