$.widget("ui.floatingpanel", {
	_create: function() {
		$this = this;
		var container = $('<div />').attr('class', 'fieldset');
		var handle = $('<div />').attr('class', 'field floatinghandle');
		handle.append($('<span />').attr('class', 'ui-icon ui-icon-grip-dotted-vertical'));
		var content = $('<div />').attr('class', 'field');
		content.html(this.element.html());
		this.element.html('');
		container.append(handle).append(content);
		this.element.append(container);
		this.element.addClass('ui-corner-top ui-widget ui-widget-content');
		
		this.origTop = this.element.offset().top;
		this.left = this.element.offset().left;
		this.top = $(window).height() - this.element.outerHeight();
		
		this._applyFloatEvent();
		
		this.element.draggable({
			axis: 'x',
			containment: 'window'
		});
		
		$(window).resize(function() {
			$this.top = $(window).height() - $this.element.outerHeight();
			if (!$this._applyFloatEvent()) {
				if ($('#toolbarplaceholder').length == 0) {
					$this.element.after($('<p />').attr('id', 'toolbarplaceholder').css({height: $this.element.outerHeight()}));
				}
				$this.element.css({
					position: 'fixed',
					top: $this.origTop
				});
			}
		});
	},
	
	_applyFloatEvent: function() {
		$(document).unbind('scroll', this._scrollHandler);
		if (this.origTop > this.top) {
			if ($('#toolbarplaceholder').length == 0) {
				this.element.after($('<p />').attr('id', 'toolbarplaceholder').css({height: this.element.outerHeight()}));
			}
			this.element.css({
				position: 'fixed',
				top: this.top
			});

			$(document).scroll(this._scrollHandler);
			return true;
		}
		return false;
	},
	_scrollHandler: function(event) {
		$this.element.css({
			position: 'fixed',
			top: $this.top
		});
		var currentOffset = $this.element.offset();
		if (currentOffset.top >= $this.origTop) {
			$this.element.css({
				position: 'absolute',
				top: $this.origTop
			});
		}
	},
	refresh: function() {
		this.element.css({
			position: 'static'
		});
		this.origTop = this.element.offset().top;
		
		this._applyFloatEvent();
	}
});

