// Tooltips Class
// A superclass to work with simple CSS selectors
var Tooltips = Class.create();
Tooltips.prototype = {
	initialize: function(selector, options) {
		var tooltips = $$(selector);
		tooltips.each( function(tooltip) {
			new Tooltip(tooltip, options);
		});
	}
};
// Tooltip Class
var Tooltip = Class.create();
Tooltip.prototype = {
	initialize: function(el, options) {
		this.el = $(el);
		this.tooltip = this.el.down('.tooltip');
		this.is_active = false;
		this.timeout = null;

		this.setOptions(options);

		Event.observe(this.el, "mouseover", this.show.bindAsEventListener(this, 'root'));
		Event.observe(this.el, "mouseout", this.prepareHide.bindAsEventListener(this, 'root'));

		Event.observe(this.tooltip, "mouseover", this.show.bindAsEventListener(this, 'child'));
		Event.observe(this.tooltip, "mouseout", this.prepareHide.bindAsEventListener(this, 'child'));
	},
	setOptions: function(options) {
		this.options = {
			hideDelay: 300,
			showDuration: 0.25,
			hideDuration: 0.25
		};
		Object.extend(this.options, options || {});
	},

	show: function(evt, target) {
		if(!this.is_active)
		{
			this.is_active = true;
			this.tooltip.show();
			this.el.setStyle({zIndex: '1000'});
		}
		else
		{
			this._clearTimeout(this.timeout);
		}
	},

	prepareHide: function(evt, target) {
		if(this.is_active)
		{
			this.is_active = false;
			this.timeout = window.setTimeout(this.hide.bind(this), this.options.hideDelay);
		}
	},

	hide: function() {
		if(!this.is_active)
		{
			this.tooltip.hide();
			this.el.setStyle({zIndex: '0'});
			this._clearTimeout(this.timeout);
		}
	},

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

