/*
 * Image preview script 
 * powered by jQuery (http://www.jquery.com)
 * 
 * written by Alen Grakalic (http://cssglobe.com)
 * 
 * for more info visit http://cssglobe.com/post/1695/easiest-tooltip-and-image-preview-using-jquery
 *
 */
 
this.imagePreview = function(){	
	/* CONFIG */

		captionSize = 30;
		widthOffset = 10;
		heightOffset = 30;
		
		// these 2 variable determine popup's distance from the cursor
		// you might want to adjust to get the right result
		
	/* END CONFIG */
	$("a.preview").hover(function(e){
		this.t = this.title;
		this.title = "";	
		var c = (this.t != "") ? "<br/>" + this.t : "";
		$("body").append("<p id='preview'><img src='"+ this.href +"' alt='Image preview' />"+ c +"</p>");
		showPopup(e).fadeIn();
    },
	function(){
		this.title = this.t;	
		$("#preview").remove();
    });	
	$("a.preview").mousemove(function(e){
		showPopup(e);
	});	
	
	function showPopup(event) {
		var windowHeight = $(window).height();
		var scrollTopPosition = $(window).scrollTop();
		
		var windowWidth = $(window).width();
		var scrollLeftPosition = $(window).scrollLeft();
		
		var currentHeight = windowHeight + scrollTopPosition;
		var currentWidth = windowWidth + scrollLeftPosition;
		var imageHeight = $("#preview img").attr("height") + captionSize;
		var imageWidth = $("#preview img").attr("width");
		var mouseHeight = event.pageY;
		var mouseWidth = event.pageX;
		if(mouseHeight + imageHeight + heightOffset > currentHeight) {
			// display in the middle
			var topOffset = ((windowHeight / 2) + scrollTopPosition ) - (imageHeight / 2);
		} else {
			// display it next to the mouse (bottom position)
			var topOffset = mouseHeight + heightOffset;
		}
		
		if(mouseWidth + imageWidth + widthOffset > currentWidth) {
			// display in the middle
			var leftOffset = ((windowWidth / 2) + scrollLeftPosition ) - (imageWidth / 2);
		} else {
			// display it next to the mouse (bottom position)
			var leftOffset = mouseWidth + widthOffset;
		}
		
		
		var preview = $("#preview");
		preview.css("top",topOffset + "px");
		preview.css("left",leftOffset + "px");
		return preview;
	}
};