var Tooltip = Class.create();
Tooltip.prototype = {
	initialize: function(el, options) {
		this.el = $(el);
		if (this.el.title.length == 0) {
			return;
		}
		
		this.initialized = false;
		this.setOptions(options);
		
		this.showEvent = this.show.bindAsEventListener(this);
		this.hideEvent = this.hide.bindAsEventListener(this);
		Event.observe(this.el, "mouseover", this.showEvent );
		Event.observe(this.el, "mouseout", this.hideEvent );

		this.content = this.el.title;		
		this.el.title = "";

		this.el.descendants().each(function(el){
			if(Element.readAttribute(el, 'alt'))
				el.alt = "";
		});
	},
	setOptions: function(options) {
		this.options = {
			backgroundColor: '#daeeee',
			width: 234,	
			delay: 250, 
			opacity: 1, 
			appearDuration: .25, 
			hideDuration: .25
		};
		Object.extend(this.options, options || {});
	},
	show: function(e) {
		if(!this.initialized)
			this.timeout = window.setTimeout(this.appear.bind(this), this.options.delay);
	},
	hide: function(e) {
		if(this.initialized) {
			this.appearingFX.cancel();
			new Effect.Fade(this.tooltip, {duration: this.options.hideDuration, afterFinish: function() { Element.remove(this.tooltip) }.bind(this) });
		}
		this._clearTimeout(this.timeout);
		
		this.initialized = false;
	},
	
	appear: function() {
		this.tooltip = Builder.node("div", {className: "tooltip", style: "display: none;" }, [
			Builder.node("div", {className: "boxcontent", style: "background-color:" + this.options.backgroundColor + 
				";"}, this.content), 
		]);
		document.body.insertBefore(this.tooltip, document.body.childNodes[0]);
		
		Element.extend(this.tooltip); // IE needs element to be manually extended
		this.tooltip.style.width = this.options.width + 'px'; // IE7 needs width to be defined
		
		var position = Element.cumulativeOffset(this.el);
		
		this.tooltip.style.left = "226px";
		this.tooltip.style.top = position.top + "px";
		
		this.initialized = true;
		this.appearingFX = new Effect.Appear(this.tooltip, {duration: this.options.appearDuration, to: this.options.opacity });
	},

	_clearTimeout: function(timer) {
		clearTimeout(timer);
		clearInterval(timer);
		return null;
	}
};


