/*
 * 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 = 10;
        yOffset = 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>");                                 
        $("#preview")
            .css("top",(e.pageY - xOffset) + "px")
            .css("left",(e.pageX + yOffset) + "px")
            .fadeIn("fast");                        
    },
    function(){
        this.title = this.t;    
        $("#preview").remove();
    });    
    
	$("a.preview").mousemove(function(e){
        top_end = false;
        tp = (e.pageY - xOffset);
        lf = (e.pageX + yOffset);

        window_width = $(window).width();
        window_height = $(window).height();
        
        if(window.innerHeight+document.documentElement.scrollTop - $("#preview").height() < tp){
            tp = window.innerHeight+document.documentElement.scrollTop - $("#preview").height();
            top_end=true;
        }
        
        if(window_width < (lf+$("#preview").width())){

            if(!top_end){
                lf=(window_width-$("#preview").width() - 20);
                tp+=25;
            } 
            else {
                lf=(lf-$("#preview").width()-90);
            }
        }
        
		if (e.pageY - $(window).scrollTop() + $('#preview').height() >= $(window).height() ) {
			tp = $(window).height() + $(window).scrollTop() - $('#preview').height() + 15 ;
		} else {
			tp = e.pageY + 15;
		}
		
		if (e.pageX - $(window).scrollTop() + $('#preview').width() >= $(window).width() ) {
			lf = $(window).width() + $(window).scrollTop() - $('#preview').width() + 15 ;
		} else {
			lf = e.pageX + 15;
		}
		
        $("#preview")
  			.css("top",tp + "px")
			.css("left",lf + "px")
    });	
};



// starting the script on page load
$(document).ready(function(){
    imagePreview();
});
