// jQuery image magnifier; jdbartlett's rewrite of Chris Iufer's jLoupe
// code: http://gist.github.com/252303 - demo: http://jsbin.com/olado3
// NOTE: this eventually became: http://github.com/jdbartlett/loupe
(function($) {
	$.fn.loupe = function(options) {
		if (!this.length) return this;
		options = $.extend({
			loupe: 'loupe',
			width: 200,
			height: 150
		}, options || {});
		
		this.each(function() {
			var $this = $(this), loupe = null, big = null, small = null;
			
			$this.mouseenter(function() {
				if (!small) small = ($this.is('img') ? $this : $this.find('img:first'));
				loupe = (loupe || (loupe = $('<div></div>').addClass(options.loupe).css({
					width:options.width+'px', height:options.height+'px',
					position:'absolute', overflow:'hidden'
				}).append(big = $('<img src="' + $this.attr('href') + '" />').css({
					position:'absolute'
				})).appendTo('body'))).show();
			}).mouseleave(function() {
				if (loupe) loupe.hide();
			}).mousemove(function(e) {
				if (loupe) {
					loupe.css({
						left:e.pageX+10, top:e.pageY+10
					});
					
					var offset = small.offset();
					big.css({
						left: -(((e.pageX - offset.left) / small.width()) * big.width() - (options.width/2))|0,
						top: -(((e.pageY - offset.top) / small.height()) * big.height() - (options.height/2))|0
					});
				}
			}).click(function() {
				return false;
			});
		});
		
		return this;
	}
})(jQuery);