// manager of misc remote floats

window.Float = {

	list : [],
	hook : false,


	vis : function(container) {
		var
			displays = [ 'none', 'block' ],
			now = ( $(container).style.display === 'block' )
		;

		now = 0 + !now;
		this.hide(this.list.remove(container));

		if ( $(container).setPosition ) {
			$(container).setPosition();
		}

		$(container).setStyle('display', displays[now]);
		this.list[ 1 === now ? 'include' : 'remove' ]($(container).id);
	},


	hide : function(what) {
		var _this = this;
		var list = $defined(what) ? what : this.list ;

		if ( $defined(list.length) && 0 !== list.length ) {
			$$(list).each(function(el) {
				el.setStyle('display', 'none');
				_this.list.remove(el.id);
			});
		}

		return false;
	},

	
	getContent : function(container, post, stay) {
		var
			url = '/js/float/get/' + container,
			container_obj = $(container),
			_this = this;
		;

		var ajax_options = {
			method: 'get',
			onComplete: function(response) {
				if ( '' === response.trim() ) {
					this.cancel();
				} else {
					container_obj.setHTML(response);
					this.evalScripts();

					if ( !$defined(stay) || true !== stay ) {
						_this.vis.delay(5, _this, container);
					}
				}
			},
			data: Object.toQueryString( $merge({DEBUG_MODE: 0, _rnd: Math.random()}, post) )
		};
		(new Ajax(url, ajax_options)).request();
	},


	toggle : function(container, event, post, refresh) {
		var _this = this;

		if ( event ) { event = new Event(event); event.stop(); }

		if ( !$(container) ) {
			var div = new Element('DIV', { 'class' : 'popup', 'id' : container });
			document.body.appendChild(div);
		}
		
		if ( !$(container)._dnc ) { // cancels popup closing while layer clicking 
			$(container)._dnc = function(event) { event = new Event(event); event.stopPropagation(); }
			$(container).addEvent('click', $(container)._dnc);
		}

		if ( '' === $(container).innerHTML.trim() || (undefined !== refresh && true === refresh) ) {
			this.getContent(container, post);
		} else {
			this.vis(container);
		}

		if ( false === this.hook ) {
			$(document.body).addEvent('click', function(event) {
				_this.hide();
				if($defined($(container)) && $(container).documentClickCallback) {
					$(container).documentClickCallback();
				}
			});

			this.hook = true;
		}

		return false;
	}
}

document.addEvent('keyup', function(event){
	event = new Event(event);
	if (event.code == Event.keys.esc) {
		window.Float.hide();
	}
});
