/*
 * Url 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
 *
 * Edited: 7-25-2010 by Matt Kopala
 *   - lots of tweaks for initial display, keep image inside viewport, fix display for scrolled pages, etc.
 *   - added yucky global variables because I was in a hurry and my JS closure skills are rusty
 */

var waitImg;
var mImg;
var locX;
var locY;

// calculate the image location based on viewport dimensions, scroll offset, mouse location, and image dimensions
function getLoc(e, i) {
	xOffset = 20;
	yOffset = 20;

	var scrollY = $(window).scrollTop();

	var winHeight = $(window).height();
	var winWidth = $(window).width();

	var imgHeight = i ? i.height : $("#screenshot img").height();
	var imgWidth = i ? i.width : $("#screenshot img").width();

	var viewY = e.pageY - scrollY;

	//console.log([e.pageX, e.pageY, imgHeight, imgWidth, scrollY, winHeight, winWidth]);

	// Calculate X position
	if (e.pageX < xOffset) {
		imgLeft = 20;
	} else if (e.pageX + xOffset + imgWidth + 10 < winWidth - 20) {
		imgLeft = e.pageX + xOffset;
	} else if (e.pageX - imgWidth < 0) {
		imgLeft = 20;
	} else {
		imgLeft = e.pageX - imgWidth - xOffset;
	}

	// Calculate Y position
	if (viewY < yOffset + 20) {
		imgTop = 20 + scrollY;
	} else if (viewY - yOffset + imgHeight < winHeight - 20) {
		imgTop = viewY - yOffset + scrollY;
	} else if (viewY - imgHeight < 0) {
			imgTop = 10 + scrollY;
	} else if (viewY > winHeight - imgHeight + yOffset) {
		imgTop = winHeight - imgHeight - 20 + scrollY;
	} else {
		imgTop = viewY - imgHeight + yOffset + scrollY;
	}

	return {left: imgLeft, top: imgTop};
}
// Wait for image to load, get dimensions, then show it
function checkImageLoad() {
	var imgHeight = mImg.height;
	var imgWidth = mImg.width;

	if (imgHeight > 0) {
		loc = getLoc({pageX: locX, pageY: locY}, mImg);
		clearInterval(waitImg);

		var p = document.createElement('p');
		p.id = 'screenshot';
		p.appendChild(mImg);
		$("body").append(p);

		$("#screenshot")
			.css("height", (imgHeight - 34) + "px")
			.css("width", (imgWidth) + "px")
			.css("top", (loc.top) + "px")
			.css("left", loc.left + "px")
			.fadeIn("fast");						
	}
}

// Initial display of preview image when mouse hovers over image
function showImage(e) {
		locX = e.pageX;
		locY = e.pageY;
		mImg = new Image();
		mImg.src = this.rel;
		waitImg = setInterval(checkImageLoad, 10);
}

// Move the preview image as the mouse moves
function moveImage(e) {
	loc = getLoc(e);
	$("#screenshot")
		.css("top", (loc.top) + "px")
		.css("left", loc.left + "px");
}

// remove the image
function removeImage() {
	clearInterval(waitImg);
	$("#screenshot").remove();
}

// starting the script on page load
$(document).ready(function(){
	$("a.screenshot").hover(showImage, removeImage);
	$("a.screenshot").mousemove(moveImage);
});

