/**
 * When clicking on an image, zoom it. Clicking on the zoomed image again un-zoomes it.
 */

(function($){
	$.fn.imagezoom = function(options) {
		var settings = $.extend({
			zoomContainer: "body",
			zoomOffsetX: 0,  /* If = 0, bottom RHS corner of the zoomed & original image overlap */ 
			zoomOffsetY: 0
		}, options || {});

//		var _self = this;
		
		/* The zoomed image is created by cloning the image <img> */
		var zoomImageClass = "imagezoom-zoomed";
		
		this.each(function(){
			$(this).hover(
					function() {
						$(this).css('cursor', 'pointer');
					},
					function() {
						$(this).css('cursor', 'auto');
					}
				);


			$(this).click(function(){
				var zoomedImage = $(this).clone().addClass(zoomImageClass).hide();
				zoomedImage.appendTo($(settings.zoomContainer));
				
				zoomedImage.click(function(){
					$(this).fadeOut("fast", function(){$(this).remove()});
				});
				
				/* Store the thumbnail attributes */
				var imagePosition = $(this).offset(); 
				var imageTop = imagePosition.top;
				var imageLeft = imagePosition.left;
				var imageWidth = $(this).width();
				var imageHeight = $(this).height();

				zoomedImage.width(imageWidth);
				zoomedImage.height(imageHeight);
				zoomedImage.css('left', imageLeft);
				zoomedImage.css('top', imageTop);
				zoomedImage.show();
				
				var imageAspect = 1;
				if (imageHeight > 0) // avoid divide by zero
				{
					imageAspect = imageWidth / imageHeight;
				}

				var zoomedWidth = 600; 
				var zoomedHeight = zoomedWidth / imageAspect; 
				var zoomedTop = imageTop
				   - 50;  // Move the zoomed image just for effect 
//				var zoomedTop = imageTop - (zoomedHeight - imageHeight)
//				   + 50;  // Move the zoomed image slightly lower just for effect 
				var zoomedLeft = imageLeft - (zoomedWidth - imageWidth) 
				   + 100 ;  // Move the zoomed image to the right just for effect 

				zoomedImage.animate({
					width: zoomedWidth,
					height: zoomedHeight,
					top: zoomedTop,
					left: zoomedLeft
				}, 300);
			});
			
			
		});

		return this;
	}
}) (jQuery);




