function viewport() {
	return {
		x: $(window).scrollLeft(),
		y: $(window).scrollTop(),
		cx: $(window).width(),
		cy: $(window).height()
	};
}
 
this.imagePreview = function(){
	xOffset = 10;
	yOffset = 30;

	$("#gallery img").hover(function(e){
		var elParent = $(this).parent('a')[0];

		var c = (elParent.title != "") ? "<br/>" + elParent.title : "";
		
		var v = viewport();

		$("body").append("<p id='preview'><img src='"+ elParent.href +"' alt='" + this.alt + "' />"+ c +"</p>");
		
		var preview = $("#preview");
		var width = preview.width() + 24, height = preview.height() + 24;// css padding:5px
		
		var x = e.pageX;
		var y = e.pageY;

		Top = y - xOffset;
		Left = x + yOffset;

		// check horizontal position
		if (v.x + v.cx < Left + width) {
			Left -= width + (yOffset * 2);
		}

		// check vertical position
		if (v.y + v.cy < Top + height) {
			Top -= height - xOffset;
		}

		preview.css({"top":Top+"px","left":Left+"px"}).fadeIn("fast");
    },
	function(){
		$("#preview").remove();
    });

	$("#gallery img").mousemove(function(e){
		var v = viewport();
		var preview = $("#preview");
		var width = preview.width() + 12, height = preview.height() + 24;//
		
		var x = e.pageX;
		var y = e.pageY;

		Top = y - xOffset;
		Left = x + yOffset;

		// check horizontal position
		if (v.x + v.cx < Left + width) {
			Left -= width + (yOffset * 2);
		}
		// check vertical position
		if (v.y + v.cy < Top + height) {
			Top -= height + xOffset;
		}

		preview.css({"top":Top+"px","left":Left+"px"});
	});
};

$(document).ready(function(){
	imagePreview();
});
