/**
 * loupe - an image magnifier for jQuery
 * http://github.com/jdbartlett/loupe
 */
(function($) {
    $.fn.loupe = function(options) {
        if (!this.length) return this;
        options = $.extend({loupe:'loupe', width:200, height:150, small_width:0, 
            small_height:0, big_width:0, big_height:0, xlimit: -1        }, options || {});
        
        this.each(function() {              
            $(this).click(function(e){e.preventDefault();});
            var $this = $(this), loupe = null, big = null, small = null, time = null, past_x=0, past_y=0, past_limit = false,                   
            hide = function() {loupe.css('cursor', 'default');loupe.hide();},
            move = function(e) {
                var os = small.offset(), sW = options.small_width, sH = options.small_height, oW = options.width/2, oH = options.height/2;
                if (e.pageX > sW + os.left + 10 || e.pageX < os.left - 10 ||
                    e.pageY > sH + os.top + 10 || e.pageY < os.top - 10) return hide();
                if (time && clearTimeout(time)) time = null;
                loupe.css({left:e.pageX - oW, top:e.pageY - oH});
                var xpos = (-(((e.pageX - os.left) / sW) * options.big_width - oW)|0) + 'px';
                var ypos = (-(((e.pageY - os.top) / sH) * options.big_height - oH)|0) + 'px';
                loupe.css('background-position', xpos + ' ' + ypos);
                return e;
            };
            $this.mouseenter(function(e) {
                if (!small) small = $this.is('img') ? $this : $this.find('img:first');
                loupe = (loupe || (loupe = $('<div></div>').addClass(options.loupe)
                    .css({
                        width:options.width, height:options.height,
                        position:'absolute', overflow:'hidden',
                        background: '#cddbe9 url('+$this.attr($this.is('img') ? 'src' : 'href')+') 0px 0px no-repeat'
                    })
                    .mousemove(move).appendTo('body')
                )).show().css('cursor', 'none');
                move(e);

            }).mouseout(function() {time = setTimeout(hide, 10); return;});
        });
        return this;
    };
})(jQuery);

