/*
  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) {
      if(!args.glassSize){ args.glassSize = 125; }
      if(!args.scale){ args.scale = 4; }
    } else args = { 'glassSize' : 300, 'scale' : 2.5 };
    
    // 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 - (args.glassSize/2));
	var t = Math.floor(e.pageY - (args.glassSize/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);
	var yOff = (e.pageY - _off.top);
	var x = -xOff * args.scale + args.glassSize/2;
	var y = -yOff * args.scale + args.glassSize/2;
	$(m.img).css({
	  top: y+"px",
	  left: x+"px"
	});	
	
      }
    };
    
    // scoped! ;)
    m.srcNode = this;
    this._magnifier = m;
    $(this).mouseover(m._show);
    
    $(".glassNode").empty().remove();

    // 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
};

jQuery.fn.unmagnify = function(args){
  return this.each(function(){
    if (this._magnifier) {
      m = this._magnifier;
      m._hide();
      $(this).unbind('mouseover');
      this._magnifier = null;
      $(".glassNode").empty().remove();
    }
  });
};