// Initialize.
function init_tooltip() {

	// Does element exist?
	if (!$('.tooltip').length) {

		// If not, exit.
		return;
	}

	// Insert tooltip (hidden).
	$('body').append('<div id="tooltip"><div id="tooltip_inner"></div></div>');

	// Empty variables.
	var $tt_title, $tt_alt, $tt_src;

	var $tt = $('#tooltip');
	var $tt_i = $('#tooltip_inner');

	// Watch for hover.
	$('.tooltip').hover(function() {
        //$('.tooltip').mouseover(function() {
		// Store title, empty it.
		if ($(this).attr('title')) {
			$tt_title =  $(this).attr('title');
			$(this).attr('title', '');
		}

		// Store alt, empty it.
		if ($(this).attr('alt')) {
			$tt_alt = $(this).attr('alt');
			$(this).attr('alt', '');
		}
		if ($(this).attr('src')) {
			$tt_src = $(this).attr('src');
			$(this).attr('src', '');
		}

		// Insert text.
                $tt_i.html('<p class="left">' + $tt_src + '</p><p class="right">' + $tt_title + '<br><span class="footer">' + $tt_alt + '</span></p><div class="clear"></div>' );

		// Show tooltip.
		$tt.show();
	},
	function() {

		// Hide tooltip.
		$tt.hide();

		// Empty text.
		$tt_i.html('');

		// Fix title.
		if ($tt_title) {
			$(this).attr('title', $tt_title);
		}

		// Fix alt.
		if ($tt_alt) {
			$(this).attr('alt', $tt_alt);
		}
		if ($tt_src) {
			$(this).attr('src', $tt_src);
		}

	// Watch for movement.
	}).mousemove(function(ev) {


		// Tooltip coordinates.
		var $tt_x = $tt.outerWidth();
		var $tt_y = $tt.outerHeight();
                //alert ($tt_x + ' ' +  $tt_y);
                //
		// Event coordinates.
		var $ev_x = ev.pageX;
                var $ev_y = ev.pageY-$tt_y;

		//var $ev_y = ev.pageY;



		// Body coordinates.
		var $bd_x = $('body').outerWidth();
		var $bd_y = $('body').outerHeight();
                
		// Move tooltip.
		$tt.css({
			'top': $ev_y + $tt_y > $bd_y ? $ev_y - $tt_y : $ev_y,
                        //'top': $ev_y < 110 ? ev.pageY : $ev_y,
			'left': $ev_x + $tt_x + 20 > $bd_x ? $ev_x - $tt_x - 10 : $ev_x + 15,
                        'background': $ev_x + $tt_x + 20 > $bd_x ? 'url(fileadmin/images/background_tooltip_top_right.gif) no-repeat bottom' : 'url(fileadmin/images/background_tooltip_top_left.gif) no-repeat bottom'
		});
                //alert($bd_y);
	});
}

// Kick things off.
$(document).ready(function() {
	init_tooltip();
});
