/*
 * 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 */

   xOffset = 5;
   yOffset = 5;

   maxWidth=100;
   maxHeight=100;

		// these 2 variable determine popup's distance from the cursor
		// you might want to adjust to get the right result
    docWidth = $(document).width();
    docHeight= $(document).height();

	$(window).resize(function(){
	      docWidth = $(document).width(), // or $(window).width()
	      docHeight = $(document).height(); // or $(window).height()
	});


	/* END CONFIG */
	$("a.preview").hover(function(e){
        var d=$("#previewimg").attr('width');

        if($(document).width()>docWidth){
        	xl = e.pageX - (d + 50);
        }else{
        	xl = e.pageX + xOffset;
        }

		this.t = this.title;
		this.title = "";
		var c = (this.t != "") ? "<br/>" + this.t : "";
		$("body").append("<p id='preview'><img id='previewimg' src='"+ this.href +"' alt='Image preview' />"+ c +"<br><div id='imgcaption'></div></p>");
		$("#preview")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(xl) + "px")
			.fadeIn("fast");

    },
	function(){
		this.title = this.t;
		$("#preview").remove();
    });

	$("a.preview").mousemove(function(e){
        var pw=$("#previewimg").attr('width');
        var ph=$("#previewimg").attr('height');

        var tn_width;
        var tn_height;
        var x_ratio=maxWidth/pw;
        var y_ratio=maxHeight/ph;

	        if((pw<=maxWidth) && (ph<=maxHeight)){
	            tn_width=pw;
	            tn_height=ph;
	        }else if((x_ratio*ph) < maxHeight){
	                 tn_height 	=	x_ratio*ph;
	                 tn_width 	=	pw;
	        }else{
	                  tn_width	=	y_ratio*pw;
	                  tn_height	=	ph;
	        }

        //$("#previewimg").css("width",tn_width);
        //$("#previewimg").css("height",tn_height);


        var curx=e.pageX + pw;
        var cury=e.pageY + ph;

        if(curx>docWidth){
        	xl = e.pageX - (pw + 20);
        }else{
        	xl = e.pageX + xOffset;
        }

        if(cury>docHeight){
        	yl = e.pageY - (ph + 20);
        }else{
        	yl = e.pageY + yOffset;
        }


		$("#preview")

			.css("top",(yl) + "px")
			.css("left",(xl) + "px");
	});
};


// starting the script on page load
$(document).ready(function(){
	imagePreview();
});
