(function($) {
	$.fn.zoomBox = function(o)
	{
		return this.each(function(o){
			new $zb(this, o);
		});
	};
	var defaultOptions = 
	{
		className: "zoomBox"
	};
	$.zoomBox = function(e, o)
	{
		this.options = $.extend({}, defaultOptions, o || {});
		
		this.root = $(e);
		this.smallImage = this.root.find('.smallImage');
		this.largeImage = this.root.find('.largeImage');
		this.imageSlide = this.largeImage.wrap('<div class="'+this.options.className+'Slide"></div>').parent();
		this.imageSlide.css('display', 'none').css('position', 'relative');
		this.largeImage.css('display', 'block');
		var self = this;
		this.largeImage.find('img').each(function() {
			var img = this;
			var func = function()
			{
				var root = self.root.get(0);
				self.fullWidth = img.width;
				self.fullHeight = img.height;
				self.scaleFactor = { 'x': (img.width - root.clientWidth) / root.clientWidth, 
						'y': (img.height - root.clientHeight) / root.clientHeight };
			}
			if(this.width > 0)
				func();
			else
				$(this).load(func);
		});
		this.offset = this.root.offset;
		if(this.smallImage.length == 0 || this.largeImage.length == 0)
			throw("One of the required images is missing.");
		
		this.root.addClass(this.options.className);
		this.setup();
	}
	$zb = $.zoomBox;
	$zb.fn = $zb.prototype = {
		zoomBox: "0.1.0"
	};
	$zb.fn.extend = $zb.extend = $.extend;
	
	$zb.fn.extend({
		setup: function()
		{
			var self = this;
			var activateFunc = function(e) { self.activate(e, this); };
			var moveFunc = function(e) { self.mouseMove(e, this); };
			var deactivateFunc = function(e)  { self.deactivate(e, this); };
			this.root.mouseenter(activateFunc).mousemove(moveFunc).mouseleave(deactivateFunc);
		},
		activate: function(e, element)
		{
			this.smallImage.css('display', 'none');
			this.imageSlide.css('display', 'block');
		},
		mouseMove: function(e, element)
		{
			var pos = this.relativePosition(e);
			this.imageSlide.css('left', (-1 * pos.x ) + "px" ).css('top', (-1 * pos.y) + "px");
		},
		deactivate: function(e, element)
		{
			this.smallImage.css('display', 'block');
			this.imageSlide.css('display', 'none');
		},
		relativePosition: function(e)
		{
			var offset = this.root.offset();
			return { 
			'x': (e.pageX - offset.left) * this.scaleFactor.x, 
			'y': (e.pageY - offset.top) * this.scaleFactor.y
			} ;
		}
	});
	

})(jQuery);
