/**
 * Assigns tooltips to a DOM element based on the element's TITLE attribute or
 * the value assigned to it in the global tooltips array keyed on either the FOR
 * or ID attribute.
 * Requires 'prototype.js' and the script.aculo.us library 'builder.js'.
 * @version   2009-10-15
 */

/*global Class, $$, Builder, window, document, tooltips */
var ToolTip = Class.create();
ToolTip.prototype = {
	tipObj: undefined,
	tipsArray: [],
	tipTimeout: null,
	initialize: function() {
		this.tipsArray = [];
		var body = $$('body')[0];
		this.tipObj = body.appendChild( Builder.node( 'div', { id: 'tooltip' } ) );
		this.setupToolTips();
	},
	// Bind handlers to tooltip elements
	setupToolTips: function() {
		var i = 0;
		var that = this;
		$$('.tooltip').each( function( el ) {
			el.observe( 'mouseover', ( function( ev ) {
				ev.stop();
				that.handleMouseOver( ev );
			} ).bind( this ) );
			el.observe( 'mousemove', ( function( ev ) {
				ev.stop();
				that.handleMouseMove( ev );
			} ).bind( this ) );
			el.observe( 'mouseout', ( function( ev ) {
				ev.stop();
				that.handleMouseOut( ev );
			} ).bind( this ) );
			if (typeof( tooltips ) !== "undefined") {
				that.tipsArray[i] = tooltips[el.getAttribute( 'for' )] || tooltips[el.getAttribute( 'id' )] || el.title;
			} else {
				that.tipsArray[i] = el.title;
			}
			el.tip = i++;
			if (el.title) {
				el.removeAttribute( 'title' );
			}
		} );
	},
	// Setup and show the tool tip container on mouseover
	handleMouseOver: function( ev ) {
		var target = ev.findElement( '.tooltip' );
		if (target) {
			this.tipTimeout = this.showToolTip.delay( 0.6, this.tipObj, this.tipsArray[target.tip] );
			// Disable browser handling of images's ALT attribute
			var image = ev.findElement( '.tooltip img' );
			if (image) {
				image.alt = "";
			}
		}
	},
	// Move the tool tip container with the cursor
	handleMouseMove: function( ev ) {
		var target = ev.findElement( '.tooltip' );
		if (target) {
			this.tipObj.style.left = (ev.pointerX() + 10) + 'px';
			this.tipObj.style.top = (ev.pointerY() + 10) + 'px';
		}
	},
	// Hide the tool tip container on mouseout 
	handleMouseOut: function() {
		window.clearTimeout( this.tipTimeout );
		this.tipObj.style.visibility = "hidden";
	},
	// Display the tool tip
	showToolTip: function( el, tip ) {
		el.update( tip );
		el.style.visibility = "visible";
	}
};
document.observe( 'dom:loaded', function() { (new ToolTip()); } );

