/*
 * Helper functions for wz_tooltip.js in KlasCement.
 * Some functionality depends on the Prototype JavaScript framework.
 */

var tt_ajax_url;
var tt_ajax_timeout;
var tt_eventX, tt_eventY;
var tt_arg;

/**
 * Show a tooltip with content retrieved by an AJAX request.
 *  
 * @param url	URL for the AJAX request
 * @param e		The event that triggered this function
 */
function show_tooltip(url, e) {
	tt_ajax_url = url;
	// retain mouse position (MSIE & Webkit lose it after the AJAX request)
	// from http://www.quirksmode.org/js/events_properties.html#position
	if (!e) var e = window.event;
	if (e.pageX || e.pageY) {
		tt_eventX = e.pageX;
		tt_eventY = e.pageY;
	}
	else if (e.clientX || e.clientY) {
		tt_eventX = e.clientX + document.body.scrollLeft
			+ document.documentElement.scrollLeft;
		tt_eventY = e.clientY + document.body.scrollTop
			+ document.documentElement.scrollTop;
	}
	// store any optional arguments to apply to Tip()
	tt_arg = $A(arguments).slice(2);
	// ensure even number of optional arguments
	if (tt_arg.length & 1) {
		tt_Err("Incorrect call of show_tooltip().\n"
			+ "Each command must be followed by a value.", true);
		return false;
	}
	// shift delay from tooltip display to AJAX request
	var d_off = tt_arg.indexOf(DELAY);
	var delay = d_off & 1 ? config.Delay : tt_arg[d_off+1];
	d_off & 1 ? tt_arg.push(DELAY, 0) : tt_arg[d_off+1] = 0;
	tt_ajax_timeout = window.setTimeout('tt_ajax_request()', delay);
}

/**
 * Helper function that carries out the actual AJAX request.
 */
function tt_ajax_request() {
	new Ajax.Request(tt_ajax_url, {
		method: 'get',
		onSuccess: function(transport) {
			tt_arg.unshift(transport.responseText);
			Tip.apply(null, tt_arg);
			// ensure correct tooltip position for MSIE & Webkit
			// (won't work with extension with OnMoveBefore function)
			tt_musX = tt_eventX;
			tt_musY = tt_eventY;
			tt_SetTipPos(tt_Pos(0), tt_Pos(1));
			tt_ExtCallFncs([tt_musX, tt_musY], "MoveAfter");
		}
	});
}

/**
 * Hide a tooltip.
 */
function hide_tooltip() {
	window.clearTimeout(tt_ajax_timeout);
	UnTip();
}
