/*
 * jQuery Image Tooltip Plugin
 *
 * Copyright (c) 2009 Erik Nedwidek, Lighthouse I.T. Consulting, Inc. (www.lighthouseitc.com)
 * Dual licensed under the MIT and GPL v2 (or later) licenses.
 * 
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html#SEC1
 * 
 * Based on Alen Grakalic tutorial @ http://cssglobe.com/post/1695/easiest-tooltip-and-image-preview-using-jquery
 * 
 * Requires Dimensions Plugin if used with jQuery < 1.2.6
 * $Revision: 37 $
 * $Date: 2009-06-04 14:04:54 -0400 (Thu, 04 Jun 2009) $
 * $Author: nedwidek $
 * $Id: jquery.imagetooltip.js 37 2009-06-04 18:04:54Z nedwidek $
 */

 $.fn.ImageTooltip = function(options) {
    var defaults = {
        style: 'ImageTooltip',
		preload: false,
        cursorOffsetX: 30,
        cursorOffsetY: 10,
        bottomBuffer: 15,
        fadeIn: "fast"
    };

    var opts = $.extend(defaults, options);

    var previewID = opts.style + "-preview";
	
	if (opts.preload) {
		$("a." + opts.style).each(function() {
			jQuery("<img>").attr("src", this.href);										 
		});
	}

    $("a." + opts.style).hover(function(event) {
        // Capture the caption and supress the title tooltip
		this.caption = this.title;
		this.title = "";
        var tooltipHtml = '<div id="' + previewID + '"><img class="' + opts.style + '" src="' + this.href + '" />';	
		var captionHtml = (this.caption != "") ? '<div class="' + opts.style + '-caption">' + this.caption + "</div>" : "";
        tooltipHtml += captionHtml + "</div>";
		
		$("body").append(tooltipHtml);
		
		var yPos = event.pageY - opts.cursorOffsetY;
		var previewHeight = $("#" + previewID).height();
		var win = $(window);
		
		var overflow = (event.pageY + opts.cursorOffsetY + previewHeight + opts.bottomBuffer) - (win.scrollTop() + win.height()); 
		if ( overflow > 0 ) {
			yPos = event.pageY - overflow - opts.bottomBuffer;
		}
		
		$("#" + previewID)
			.css("top", (yPos) + "px")
			.css("left",(event.pageX + opts.cursorOffsetX) + "px")
			.fadeIn(opts.fadeIn);						
    },
	function(){
		this.title = this.caption;	
		$("#" + previewID).remove();
    });	
	$("a." + opts.style).mousemove(function(event){
		var yPos = event.pageY - opts.cursorOffsetY;
		var previewHeight = $("#" + previewID).height();
		var win = $(window);
		
		var overflow = (event.pageY + opts.cursorOffsetY + previewHeight + opts.bottomBuffer) - (win.scrollTop() + win.height()); 
		if ( overflow > 0 ) {
			yPos = event.pageY - overflow - opts.bottomBuffer;
		}
				
		$("#" + previewID)
			.css("top",(yPos) + "px")
			.css("left",(event.pageX + opts.cursorOffsetX) + "px");
	});
};

