/* jQuery plugin for easy CSS tooltips
 *
 * Based on Tooltip scripts by Alen Grakalic (http://cssglobe.com)
 * For more info visit http://cssglobe.com/post/1695/easiest-tooltip-and-image-preview-using-jquery
 *
 * Extended by Senko Rasic to call arbitrary function which builds tooltip HTML
 *
 * Example plugin usage cases:
 *
 * 1) put a normal tooltip on all anchors having 'tooltip' class, creating a
 *    paragraph with id 'tooltip' to hold the tooltip
 *    
 *      $('a.tooltip').tooltip(function (el) {
 *          return el.anchor_title;
 *      });
 *
 * 2) image preview (image + optional caption) on anchors having 'preview' class,
 *    creating a paragraph with id 'preview' to hold the tooltip
 *    
 *      $('a.preview').tooltip(function (el) {
 *              var c = (el.anchor_title != "") ? "<br/>" + el.anchor_title : "";
 *              return "<img src='"+ el.href +"' alt='image preview' />"+ c;
 *      }, {'tooltipID': 'preview'});
 *
 *
 * 3) url preview (image + optional caption) on anchors having 'screenshot' class,
 *    creating a paragraph with id 'screenshot' to hold the tooltip
 *    
 *      $('a.screenshot').tooltip(function (el) {
 *          var c = (el.anchor_title != "") ? "<br/>" + el.anchor_title : "";
 *         return "<img src='"+ el.rel +"' alt='url preview' />"+ c;
 *      }, {'tooltipID': 'screenshot'});
 */

(function($) {
    function tooltip(el, fn, options) {
       
        el.mouseover(function(e) {
        
            this.anchor_title = this.title;
            this.title = '';
			   
            $('body').append(
            	'<div id="' + options.tooltipID + '">' + 
            		'<span class="copy">' + 
            			'<span class="text" style="position:relative;">' + fn(this) + '</span>' + 
            		'</span>' + 
            		'<div class="bg"></div>' + 
            	'</div>');
			
			$(".copy").width($(".text").width() + 50);
			
            $('#' + options.tooltipID)
                .css("top", (el.offset()['top']) - 42 + "px")
                .css("left", el.offset()['left'] - 7 + "px")
                .animate({
					opacity: 1,
					top: '-=' + 5 + 'px'
				}, options.effectTime);

			$('#' + options.bgImg).hide("blind", { direction: "vertical" }, options.effectTime);
        });
        
        el.mouseout(function(e) {
            $('#' + options.tooltipID)
			$('#' + options.bgImg).show("blind", { direction: "vertical" }, options.effectTime);	
			
			this.title = this.anchor_title;
			$('#' + options.tooltipID).remove();
        });
    }

    $.fn.tooltip = function(fn, options) {
        options = options || {};
        var defaults = {
            xOffset: -20,
            yOffset: -40,
            effectTime: 500,
            bgImg: 'bgImg',
            tooltipID: 'tooltip'
        };        

        return this.each(function() {
            tooltip($(this), fn, $.extend(defaults, options));
        });
    }
    
})(jQuery);