/**
 * Class to handle popups.
 **/
Htk.Popup = new Class
({
	Extends: Htk.Widget
	,Tag: 'htk-popup'

	,child: null
	,parent: null

	,initialize: function ()
	{
		this.createElement ('div');
		this.node.className = 'htk-popup';
	}

	,setChild: function (child)
	{
		this.setChildNode (child.getNode ());
	}

	,setChildNode: function (childNode)
	{
		Vn.Node.removeChilds (this.node);
		this.node.appendChild (childNode);
	}

	,show: function (parent)
	{
		document.body.appendChild (this.node);
		
		this.node.addEventListener ('mousedown', this.stopEvent);
		
		this.hideHandler = this.hide.bind (this);
		document.addEventListener ('mousedown', this.hideHandler);
		
		this.parent = parent;
		this.reset ();
	}
	
	,reset: function ()
	{
		if (!this.parent)
			return;
	
		var spacing = 5;
		var rect = this.parent.getBoundingClientRect ();
		var left = rect.left;
		var top = rect.top + spacing + this.parent.offsetHeight;

		var width = this.node.offsetWidth;
		var height = this.node.offsetHeight;

		if (left + width > Vn.Browser.getInnerWidth ())
			left -= width - this.parent.offsetWidth;
		if (top + height > Vn.Browser.getInnerHeight ())
			top -= height + this.parent.offsetHeight + spacing * 2;

		if (left < 0)
			left = 0;
		if (top < 0)
			top = 0;	
		
		this.node.style.top = (top) +'px';
		this.node.style.left = (left) +'px';
	}
	
	,showCenter: function ()
	{
		this.parent = null;
	
		this.background = document.createElement ('div');
		this.background.className = 'htk-background';
		document.body.appendChild (this.background);
	
		document.body.appendChild (this.node);
		
		var width = this.node.offsetWidth;
		var height = this.node.offsetHeight;

		this.node.style.top = '50%';
		this.node.style.left = '50%';
		this.node.style.marginLeft = (-this.node.offsetWidth / 2) +'px';
		this.node.style.marginTop =  (-this.node.offsetHeight / 2) +'px';

	}

	,hide: function ()
	{
		if (this.background)		
			Vn.Node.remove (this.background);
	
		this.node.removeEventListener ('mousedown', this.stopEvent)
		document.removeEventListener ('mousedown', this.hideHandler);
		Vn.Node.remove (this.node);
		this.parent = null;
		this.signalEmit ('closed');
	}
	
	,stopEvent: function (event)
	{
		event.stopPropagation ();
	}
});