// jussi's own popup image jQuery thingy.
// this is quite a mess, sorry!
$(document).ready(function() {
	// so, the thumbnail is pressed
	$(".popup-image-link").click(function(e) {

		// prevent anchor default action
		e.preventDefault();
		
		// checking if the pop image is already there
		if ($("#popup-image").length==0) {
		
			// if not, append the pop image proper html
			$("body").append("<div id='popup-image'><img src='"+ this.href +"' alt='' /><div id='popup-image-close'></div> </div");
		}
			
			// the dimensions of the image to be loaded
			var image_width;
			var image_height;
			// must load it beforehand to get the correct dimensions
			$("<img/>")  // making in memory copy of the image
    			.attr("src", this.href)
    			.load(function() {
    				// the image is now loaded, fetching the dimensions
        			image_width = this.width;   // note: $(this).width() will not
        			image_height = this.height; // work for in memory images.
        		
        			// the absolute coordinates for the image (centered)
        			var image_x = ($(window).width()-image_width)/2;	
					var image_y = window.pageYOffset + ($(window).height()-image_height)/2
					// the absolute coordinates for the close icon
					var close_x = image_width - $("#popup-image-close").width()/2;	
					var close_y = 0 - $("#popup-image-close").height()/2;
					// setting the close icon coordinates
					$("#popup-image-close").css("top",(close_y) + "px");
					$("#popup-image-close").css("left",(close_x) + "px");
					// setting the image coordinates
					$("#popup-image")
						.css("top",image_y + "px")
						.css("left",(image_x) + "px")
						//and finally showing it
						.show(100, function() {
							// in the callback function, bind the click anywhere to close the image behaviour
							$('body').unbind();
							$('body').bind('click',function(e) {
								// close the image if clicked and unbind the click anywhere behaviour
        						$("#popup-image").hide();
        						$('body').unbind();
							});
  						});	

    			});
		
	});

});

// that's it!
