(function($){
	$.fn.extend({
		mcgZoom: function(options) {
			var windowDiv = null;
			var imageObject = null;
			
			options = options || {};
			
			var defaults = {
					"width": "360",
					"height": "320",
					"offset": "14",
					"imageURL": ""
			};
			
			var options = $.extend(defaults,options);
			
			imageObject = new Image();
			imageObject.src = options.imageURL;
			
			var zoomwindow = $(".zoomwindow");
			
			if(zoomwindow.size() > 0)
			{
				windowDiv = zoomwindow;
			}
			else
			{
				windowDiv = $(document.createElement("div")).addClass("zoomwindow").appendTo("body");
			}

			return this.each(function(){
				var obj = $(this);
				
				obj.bind("mouseenter",function(){
					var position = $(this).offset();
					var image = $(this).children(0);
					var width = image.width();
					
					var newTop = $(image).offset().top;
					var newLeft = position.left + width + parseInt(options.offset);
					
					windowDiv.css({
						"background-color": "white",
						"background-image": "url(" + options.imageURL + ")",
						"background-repeat": "no-repeat",
						"border": "4px solid #ccc",
						"width": options.width + "px",
						"height": options.height + "px",
						"top": newTop - 14 + "px",
						"left": newLeft + "px",
						"display":"block",
						"position":"absolute"
					});
				});
				
				obj.bind("mouseleave",function(){
					$(".zoomwindow").css({display:"none"});
				});
				
				obj.bind("mousemove",function(e){
					var image = $(this).children(0);
					var position = image.offset();
					var actualX = e.pageX - parseFloat(position.left);
					var actualY = e.pageY - parseFloat(position.top);
					
					var locationPercentageX = actualX / image.width();
					var locationPercentageY = actualY / image.height();
					
					var windowLocationX = locationPercentageX * imageObject.width;
					var windowLocationY = locationPercentageY * imageObject.height;
					
					var halfWidth = options.width * .5;
					var halfHeight = options.height * .5;
					
					if( windowLocationX < halfWidth)
					{
						windowLocationX = halfWidth;
					}
					
					if( windowLocationX > (imageObject.width - halfWidth))
					{
						windowLocationX = (imageObject.width - halfWidth)
					}
					
					if( windowLocationY < halfHeight )
					{
						windowLocationY = halfHeight;
					}
					
					if( windowLocationY > (imageObject.height - halfHeight))
					{
						windowLocationY = (imageObject.height - halfHeight);
					}
					
					var newLeft = (windowLocationX * -1) + (options.width * .5);
					var newTop =  (windowLocationY * -1) + (options.height * .5);
					
					$(".zoomwindow").css({
						"background-position": newLeft + "px " + newTop + "px"
					});
				});
			});
		}
	});
})(jQuery);
