//= require <mootools-core-1.3-full-nocompat>
//= require <uiframework/UIComponent>
//= require <findsalons/Shell>
//= require <uiframework/UICEvent>
var FindSalons = function()
{
	this.Extends = UIComponent;
	// Children
	/**
	 * The Shell instance
	 * 
	 * @type Shell
	 */
	this.shell = null;
	// Properties
	this.previousWidth = 0;
	this.previousHeight = 0;
	this.maxWidth = 1280;
	this.minWidth = 1000;
	this.minHeight = 700;
	this.maxHeight = undefined;
	this.windowRect = null;
	this.modal = null;

	/**
	 * Handles the window resize event that leads to subsequent calls to
	 * updateDisplayList()
	 */
	this.windowResizeHandler = function()
	{
		var rect = this.windowRect = $(window).getSize();
		// Get the width and height
		var w = Math.min(this.maxWidth, Math.max(this.minWidth, rect.x));
		var h = Math.max(rect.y, this.minHeight);

		this.shell.setActualSize(w, h);
		this.previousWidth = rect.x;
		this.previousHeight = rect.y;
		
		this.updateDisplayList(w, h)
		// -----------------------------------
		// Center the shell
		this.shell.move(Math.max((rect.x - w) / 2, 0), 0);
	};
	
	this.updateDisplayList = function(w, h)
	{
		if (this.modal && this.modal.parent)
			this.modal.setActualSize(w, h);
	};

	this.createChildren = function()
	{
		this.parent();

		this.shell = new Shell();
		this.shell.createChildren();
	};

	this.childrenCreated = function()
	{
		$(window).addEvent('resize', this.windowResizeHandler.bind(this));
		this.shell.childrenCreated();
		this.windowResizeHandler();
	};

	this.initializationComplete = function()
	{
		this.shell.initializationComplete();
		this.parent();
	};

	this.width = function()
	{
		return this.windowRect.x;
	};

	this.height = function()
	{
		return this.windowRect.y;
	};

	/**
	 * Overridden to divert adding children to the body
	 */
	this.addingChild = function(actualChild /* Element */, child /* UIComponent */, where /* String */)
	{
		if (!$(document.body).contains(actualChild))
		{
			$(document.body).grab(actualChild, where);
			child.parentComponent = this;
			child.dispatchEvent(new UICEvent("added", false, false, null));
		}
	};

	this.removingChild = function(actualChild /* Element */, child /* UIComponent */)
	{
		if ($(document.body).contains(actualChild))
		{
			actualChild.dispose();
			child.dispatchEvent(new UICEvent("removed", false, false, child));
		}
	};
	
	/**
	 * Lazy creation and access to the modal shield.
	 */
	this.showModal = function(show/*Boolean */)
	{
		if (!this.modal && show)
			this.modal = new UIComponent("div", {styles:{"z-index":10, "background-color":"#000000", "opacity":0.0}});
		else if (this.modal && !show)
		{
			this.modal.set("opacity", 0.0);
			this.removeChild(this.modal);
		}
			
		if (show)
		{
			this.addChild(this.modal);
			this.modal.fade(.50);
		}
	}
};
FindSalons = new Class(new FindSalons());
