(function($){
	

	$.imgzoom_cache = {};
	$.imgzoom_cache.data = {};
	$.imgzoom_cache.add = function(src){			
		if( $.imgzoom_cache.data[src] == undefined ){
			$.imgzoom_cache.data[src] = new Image();
			$.imgzoom_cache.data[src].src = src;
		}		
	}
	$.imgzoom_cache.get = function(src){
		if( $.imgzoom_cache.data[src] == undefined ){
			$.imgzoom_cache.add(src);
		}		
		return $.imgzoom_cache.data[src];
	}
	
	$.fn.imgZoom = function(options){
		return this.filter('img').each(function(){
		
			var settings = $.extend({
					target: 	null, // Где будет расологаться большая фотка
					targetWidth: 200,
					targetHeight: 200,
					targetTop: 0,
					targetLeft: 0
				}, options || {});
				
			var t = $(this);			
			$.imgzoom_cache.add( t.attr('alt') );				
										
			t.hover(function(){
				
				if( ! settings.target ){
					settings.target = $('<div class="imgzoom-target"></div>');
					settings.target.css({
						position: 'absolute',
						top: settings.targetTop,
						left: settings.targetLeft
					}).appendTo('body');
				}else{
					settings.target.show();
				}
												
				var sImg = {};
					sImg.width = t.width();
					sImg.height = t.height();
					sImg.top = t.offset().top;
					sImg.left = t.offset().left;
					sImg.center = {};
					sImg.center.top = sImg.top + sImg.height/2;
					sImg.center.left = sImg.left + sImg.width/2;
								
				var bImg = {};
					bImg.width = $.imgzoom_cache.get(t.attr('alt')).width;
					bImg.height = $.imgzoom_cache.get(t.attr('alt')).height;
					bImg.top = 0;
					bImg.left = 0;
					bImg.center = {};
					bImg.center.top = bImg.top + bImg.height/2;
					bImg.center.left = bImg.left + bImg.width/2;
								
				var scalex =  bImg.width/sImg.width ;
				var scaley =  bImg.height/sImg.height;
				
				
				var target = {};
					target.hight = settings.target.innerHeight();
					target.width = settings.target.innerWidth();
					target.center = {};
					target.center.top = target.hight / 2;
					target.center.left = target.width / 2;
				
				var bigImage = $($.imgzoom_cache.get(t.attr('alt'))).clone().css({
					position: 'absolute',
					top: 0,
					left: 0
				}).appendTo(settings.target);
				
				$(document.body).mousemove(function(e){
				
					var mouse = new MouseEvent(e);
										
					var sy = target.center.top - (( mouse.y - sImg.top ) * scaley);
					var sx = target.center.left -(( mouse.x - sImg.left ) * scalex);
					bigImage.css({
						top: Math.round(sy),
						left: Math.round(sx)
					});
				});
			}, function(){
				settings.target.html('').hide();
				
			});	
		
		});		
	}
})(jQuery);

function MouseEvent(e) {
this.x = e.pageX
this.y = e.pageY
}
