if (!BAGLAN) {
	var BAGLAN = {};
}

/**
Options for add():

@popup		- Popup element
@icon			- Icon element
@closing	- Element that closes the popup

*/

BAGLAN.Popup = function() {
	var popups = [];
	var current = null;
	
	function show(offset) {
		var options = popups[offset];
		var popup = $(options.popup);
		new Effect.Opacity($(options.icon),{from:1,to:0.5,duration:0.3});
		new Effect.Appear(popup,{duration:0.3,afterFinish:function(){
			var offset = popup.cumulativeOffset();
			popup.style.left = offset.left+'px';
			popup.style.top = offset.top+'px';
		}});
	}
	
	function hide(offset) {
		var options = popups[offset];
		new Effect.Fade($(options.popup),{duration:0.3});
		new Effect.Opacity($(options.icon),{from:0.5,to:1,duration:0.3});
	}

	return {
		add:function(options){
			var offset = popups.length;
			popups.push(options);
			
			// If window has title, set dragging handle to it. If not, make all the window dragging handle
			var title = $(options.popup).down('.popup-title');
			var handle = title?title:options.popup;
			new Draggable(options.popup,{handle:handle});

			$(options.icon).onclick = function(offset){return function(){
				if (current===offset)
				{
					// Click on the active (grayed) icon
					hide(current);
					current = null
					return false;
				}
				if (current!==null)
					hide(current);	// Hide if there's something to hide
				show(offset);
				current = offset;
				return false;
			}}(offset);
			
			$(options.closing).onclick = function(offset){return function(){
				hide(current);
				current = null;
				return false;
			}}(offset);
		}
	};
}();