/**
 * jqImgTip - jQuery plugin tooltip image previews
 * 	(http://dev.iceburg.net/jquery/jqImgTip/)
 *
 * Copyright (c) 2009 Brice Burgess <bhb@iceburg.net>
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 * @author: Brice Burgess
 * @version: 2009.01.25 +r1
 * @requires: jQuery v1.2 or later
 */
;(function($) {
$.fn.jqImgTip = function(o)
{
	var o = $.extend({
		offsetX: 20,
		offsetY: 20
	},o)
	s = 0; // serial used by cacheDimensios()
	
	return this.each(function(){
		this._jqIT = $.extend({
			wW: false, // window width
			wH: false, // window height
			iW: false, // image width
			iH: false, // image height
			s: s++
		},o);
		
		$(this).hover(function(e){
			var h = this._jqIT,
				tip = $('<div id="jqImgTip"><img src="'+this.href+'" alt="preview..." /></div>')
					.appendTo('body')
					.css({left: e.pageX + h.offsetX, top: e.pageY + h.offsetY})
					.fadeIn('slow');
			
			// hide title
			h.t = this.title;
			this.title = '';
			
			jqImgTip(e,h,tip);
		},
		function(){
			// restore title
			this.title = this._jqIT.t;
			
			// remove tooltip
			$('#jqImgTip').remove();
			
		}).mousemove(function(e){
			var tip = $('#jqImgTip');
			if (tip.length > 0) {
				jqImgTip(e, this._jqIT, tip);
			}
		});
	});
}

function jqImgTip(e,h,tip)
{
	if(!h.cached)
	{
		if(h.caching)
			return;
		h.caching = true;
		
		// cache the viewport dimensions
		h.wW = $(window).width();
		h.wH = $(window).height();
		
		// cache the image dimensions
		var clone = tip.clone().css({
			position: 'absolute',
			left: -9999,
			top: -9999})
			.attr('id','jqImgTip'+h.s)
			.appendTo('body')[0];
		
		(function resize(){
			var i = $('img',clone)[0];
			
			if	(
				 (i.naturalWidth && i.naturalWidth > 0) // FF
				 || i.complete // IE
				 || ($(i).height() > clone.scrollHeight) // case for Safari + Linux FF where native clone height is not immediately accurate
				) 
			{
				h.iW = $(i).width();
				h.iH = $(i).height();
				h.caching = false;
				h.cached = true;
				$(clone).remove();
				jqImgTip(e,h,tip);
			}
			else
			{
				setTimeout(resize,300);
			}
		})();
	}
	else
	{
		tip.css({
			left: e.pageX + (((h.iW + h.offsetY) > (h.wW - e.clientX)) ? -h.iW : h.offsetX),
			top: e.pageY + (((h.iH + h.offsetY) > (h.wH - e.clientY)) ? -h.iH : h.offsetY)
		});
	}
	
}

})(jQuery);

// starting the script on page load
$().ready(function(){
	$('a.imgTip').jqImgTip();
});