/**
 * @author Thomas Sømoen
 * 
 * Gjør om title-taggen til en pen tooltip
 */
(function($) {
	$.fn.extend({
		tooltip:function(delay){
			if(delay == undefined){
				delay = 500;
			}
			return $(this).each(function(){
				$(this).hover(
					function(e){
						e.preventDefault();
						$('.tooltip').remove();
						var text = '';
						var offset = $(this).offset();
						var zIndex = $(this).layerPos();
						
						if($(this).attr('tooltip') == undefined){
							text = $.trim($(this).attr('title'));
							$(this).attr('tooltip',text);
							$(this).attr('title','');
						}else{
							text = $(this).attr('tooltip');
						}
						
						if($.trim(text).length > 0 && $(this).is('.active')){
							var template = $.template.fetch('.tooltip',{text:text});
								template
									.css('opacity',0)
									.css('z-index',zIndex)
									.removeClass('hidden')
									.appendTo($('body'));
								
								template
									.css('left',offset.left-3)
									.css('top',offset.top-template.height())
									.animate({opacity:1},'fast');
						}
					},
					function(e){
						$('.tooltip').fadeOut('fast',function(){
							$(this).remove();
						});
					}
				);
			});
		}
	});
	
	$(document).ready(function(){
		$('*').bind('mouseenter',function(e){
			var target = $(e.target).parents('[tooltip]');
			if(target.attr('tooltip') == undefined){
				$('.tooltip').fadeOut('fast',function(){
					$(this).remove();
				});
			}
		});
		$('a.active[title]').tooltip();
	});
})(jQuery);
