(function($) {
	$.fn.hoverPopup = function(options)
	{
		settings = jQuery.extend({
			popupId: "hoverPopup",
			popupCSS: {'border': '1px solid #000000', 'background': '#FFFFFF'},
			imgSmallFlag: "_t",
			imgLargeFlag: "_l",
			cursorTopOffset: 5,
			cursorLeftOffset: 30,
			loadingHtml: "<span style='padding: 5px;'>Loading</span>"
		}, options);
		
		popup = 
		$("<div />")
		.css(settings.popupCSS)
		.attr("id",settings.popupId)
		.css("position","absolute")
		.appendTo("body")
		.hide();
		
		$(this)
		.hover(setPopup,hidePopup)
		.mousemove(updatePopupPosition)
		.click(hidePopup);
		
		function setPopup(event) {
			var fullImgURL = $(this).attr("rel");
			$(this).data("hovered",true);
			
			var img=new Image();
			var imgParam = new Date();
			img.src=fullImgURL+'?t='+imgParam;
			img.onmouseout=function() {hidePopup()};
			img.onload=function() {
				$(popup)
				.empty()
				.append(img);
				
				var pH = $(popup).height();
				var wH = $(window).height() - 150;
				if(pH > wH) {
					var pW = $(popup).width() * (wH / pH);
					$(img).css('height',wH).css('width',pW);
				}
				
				$(popup).show();
				updatePopupPosition(event);
			};
			
			if($(this).data("cached")!=true) {
				$(popup).empty().append($(settings.loadingHtml));
				$(popup).show();
			}
		}
		
		function updatePopupPosition(event) {
			var windowSize=getWindowSize();
			var popupSize=getPopupSize();
			
			if(windowSize.width+windowSize.scrollLeft < event.pageX+popupSize.width + settings.cursorLeftOffset) {
				$(popup).css("left",event.pageX-popupSize.width-settings.cursorLeftOffset);
			} else { 
				$(popup).css("left",event.pageX+settings.cursorLeftOffset);
			}
			
			if(windowSize.height+windowSize.scrollTop < event.pageY+popupSize.height+settings.cursorTopOffset) {
				$(popup).css("top",event.pageY-popupSize.height - settings.cursorTopOffset);
			} else {
				$(popup).css("top",event.pageY+settings.cursorTopOffset);
			}
			
			if($(popup).position().top < windowSize.scrollTop) {
				$(popup).css("top",windowSize.scrollTop);
			}
		}
		
		function hidePopup(event) {
			$(this).data("hovered",false);
			$(popup).empty().hide();
		}
		
		function getWindowSize() {
			return {
				scrollLeft:$(window).scrollLeft(),
				scrollTop:$(window).scrollTop(),
				width:$(window).width(),
				height:$(window).height()
			};
		}
		
		function getPopupSize() {
			return {
				width:$(popup).width(),
				height:$(popup).height()
			};
		}
		
		return this;
	};
})(jQuery);