Element.implement({
    tooltip: function(title, message, options) {

        if (!$type(message))
            return false;

        if ($type(this.tipbody)== "element")
            this.tipbody.dispose();

        var options = $merge({
            'eventStart':'mouseenter',
            'eventEnd':'mouseleave',
            'offsetx':0,
            'offsety':0,
			'direction':'top',
			'className':'fbTooltip',
			'hold':false,
			
			'flag_leaved':false,
			'flag_entered':false,
			'flag_tipbody_leaved':false,
			'flag_tipbody_entered':false
			
        }, options);

        var coords = this.getCoordinates();

        this.tipbody = new Element("div", {
            'class': options.className
        });
		var inner = new Element("div", {
			'class': 'tip-inner'
		}).inject(this.tipbody);
		inner.adopt(new Element("div", {
            'class':'tip-title',
            /*'html': title.replace(/ /g, "&nbsp;")*/
            'html': title
        })).adopt(new Element("div", {
            'class':'tip-center',
            'html': message
        })).adopt(new Element("div", {
            'class':'tip-text'
        }));
		this.tipbody.inject(document.body);
		
        this.tipbody.addEvent(options.eventEnd, function() {
            if (options.hold) {
				this.tipbody.dispose();
				this.tipbody = null;
				this.removeEvent(options.eventEnd);
			}
			options.flag_tipbody_entered=false;
			options.flag_tipbody_leaved=true;
        }.bind(this));
		
        this.addEvent(options.eventEnd, function() {
            if (!options.hold) {
				if ($type(this.tipbody) == "element") {
					this.tipbody.dispose();
					this.tipbody = null;
					this.removeEvent(options.eventEnd);
				}
			}
			options.flag_entered=false;
			options.flag_leaved=true;
        }.bind(this));

        var t = this.tipbody.getSize();
		
		if (options.direction=='top') {
	        this.tipbody.setStyles({
				'left':coords.left+(coords.width/2).round()-(t.x/2).round()+options.offsetx,
				'top':coords.top+options.offsety-t.y/*,
				'width':t.width*/
			});
		}
		else
		if (options.direction=='right') {
	        this.tipbody.setStyles({
				'left':coords.left+options.offsetx+t.x,
				'top':coords.top+(coords.height/2).round()-(t.y/2).round()+options.offsety
			});
		}
        return this;
    }
});

