/*
  jQuery image magnification plugin - ported from dojox.image.Magnifier class 
  from the Dojo Toolkit, released dual AFL/BSD license, free for use. 
  @author: Peter Higgins - dante@dojotoolkit.org

  @param: scale - scaling factor from small image to viewport
  @param: glassSize - w/h of the overlay

  @example $("img.mag").magnify({ scale:3 });
  @example $('img.zooooooom").magnify({ scale:10, glassSize:250 });
  @returns: jQuery
 
 */

jQuery.fn.magnify = function(args){
    return this.each(function(){

		// setup args
		if(!args.glassSize){ args.glassSize = 125; }
		if(!args.scale){ args.scale = 4; }

		// get our size
		var w = $(this).width();
		var h = $(this).height();
	
		// size the image
		var _zoomSize = {
			w: w * args.scale,
			h: h * args.scale
		};	
		
		// FIXME: how to scope in jQuery?
		var m = {
			// properties:
			srcNode: null,
			overlay: null,
			img: null,
			size: _zoomSize,
			
			_show:function(e){
				// show the overlay
				m.overlay.css({ visibility:"visible", display:"block" });
				m._position(e);
			},
			_hide:function(e){
				// hide the overlay
				m.overlay.css({ visibility:"hidden", display:"none" });
			},
			
			_position:function(e){
				// position the overlay under the mouse 
				var l = Math.floor(e.pageX - (w/2));
				var t = Math.floor(e.pageY - (h/2));
			
				$(m.overlay).css({
					top: t+"px",
					left: l+"px"
				});
				
				// and position the image inside the overlay relatively
				var _off = $(m.srcNode).offset({ scroll:true });
				var xOff = (e.pageX - _off.left) / w;
				var yOff = (e.pageY - _off.top) / h;
				var x = (m.size.w * xOff * -1)+(w * xOff);
				var y = (m.size.h * yOff * -1)+(h * yOff);
				$(m.img).css({
					top: y+"px",
					left: x+"px"
				});	
				
			}
		};
		
		// scoped! ;)
		m.srcNode = this;
		$(this).mouseover(m._show);

		// mmm a template system would be easy to do
		// add a node to the body and size and position it
		m.overlay = $("<div></div>")
			.appendTo("body")
			.addClass("glassNode")
			.mousemove(m._position)
			.mouseout(m._hide)
			.css({
				overflow:"hidden",
				width:args.glassSize+"px",
				height:args.glassSize+"px"		 
			});

		// add the scaled image to the floating container, and set it's size.
		m.img = $("<img src='"+this.src+"' class='glassInner' />")
			.appendTo(m.overlay)
			.css({
				position:"relative",
				top:0, left:0,
				width: _zoomSize.w + "px",
				height: _zoomSize.h + "px"
			});
    }); // jQuery
};
