/* --------------------------------------------------------------------
	Tooltip
-------------------------------------------------------------------- */

$(document).ready(function() {
	
	// vars
	var mouseX, mouseY, timer, docW, ttML, ttW, title;
	
	// set vars
	$(window)
		.resize(function() {
			docW = $(document).width();
		})
		.trigger('resize');
	
	$('body').mousemove(function(e) {
		mouseX = e.pageX;
		mouseY = e.pageY;
	});
	
	// add events to links with a title atribute. links with an emty title atributes are skipped.
	$("a[title!='']").live('mouseenter', function() {
			
		$(this)
			.bind({
				mouseenter: function() {
					// store and remove the title to prevent default behavior
					title = $(this).attr("title");
					$(this)
						.data("title", title)
						.attr("title", '');
				},
				click: function() {
					// hide tooltip
					clearTimeout(timer);
					hideTooltip(this);
				},
				mouseleave: function() {
					// hide tooltip
					clearTimeout(timer);
					hideTooltip(this);
				},
				mousemove: function() {
					// trigger show countdown until shown
					clearTimeout(timer);
					if ($tooltip.is(':hidden')) {
						timer = setTimeout(function() { showTooltip(); }, 750);
					}
				}
			})
			.trigger('mouseenter');
		
	});
	
	// create tooltip
	var $tooltip = $("<div/>", {
		id: "tooltip"
	}).appendTo("body").hide();
	
	// show tooltip
	function showTooltip() {
		// fill tooltip 
		$tooltip
			.text(title);
		
		// keep tooltip on the page 
		var ttW = $tooltip.width("auto").width();
		
		if (mouseX + ttW > docW) {
			$tooltip.css("left", "auto");
			$tooltip.css("right", "10px");
		} else {
			$tooltip.css("left", mouseX);
			$tooltip.css("right", "auto");
		}
		
		// and show	
		$tooltip
			.css("top", mouseY)
			.fadeIn('200');
	}
	
	// hide tooltip
	function hideTooltip(e) {
		$(e).attr('title', $(e).data('title'));
		$tooltip.hide();
	}
	
});
