// Author Jökull Sólberg Auðunsson. Copyright Poke 2007.

jQuery.fn.panZoom = function() {
	
	return this.each(function(){
		
		var that = $(this),
			small = that.find(".small"),
			big = that.find(".big"),
			small_dimensions = [small.innerWidth(), small.innerHeight()];
		
		that.css({
			overflow: "hidden",
			cursor: "pointer",
			width: small_dimensions[0],
			height: small_dimensions[1]
		});
		
		big.show(); // Display now in order to expose dimensions in DOM
		var big_dimensions = [big.innerWidth(), big.innerHeight()];

		that.click(function(e){ // Capture e to get the pageX/Y
			
			that.unbind('click');
			
			var click_coordinates = [
					Math.round(e.pageX-small.offset().left),
					Math.round(e.pageY-small.offset().top)
				],
				big_coordinates = [ // Not the corresponding click coordinates but the top and left offset
					Math.round(big_dimensions[0]/small_dimensions[0]*click_coordinates[0]-click_coordinates[0]),
					Math.round(big_dimensions[1]/small_dimensions[1]*click_coordinates[1]-click_coordinates[1])
				];
				
			if( big_coordinates[0] > big_dimensions[0]-small_dimensions[0] ){
				big_coordinates[0] = big_dimensions[0]-small_dimensions[0];
			}
			if( big_coordinates[1] > big_dimensions[1]-small_dimensions[1] ){
				big_coordinates[1] = big_dimensions[1]-small_dimensions[1];
			}
			
			small.css({position:"absolute"}).animate({
				width: big_dimensions[0]+"px",
				height: big_dimensions[1]+"px",
				left: -big_coordinates[0]+"px",
				top: -big_coordinates[1]+"px"
			},600,"easeOutCirc",function(){
				big.show().css({
					position: "absolute",
					left: -big_coordinates[0]+"px",
					top: -big_coordinates[1]+"px",
					cursor: "move"
				}).draggable({ // jQuery ui.draggable.js
					drag: function(e, ui){ // Callback to make sure we don't drag beyond image limits
						var leftMax = big_dimensions[0] - small_dimensions[0];
						var topMax  = big_dimensions[1] - small_dimensions[1];
						if( ui.position.left > 0 )				ui.draggable.pos[0] = 0;
						if( ui.position.top  > 0 ) 				ui.draggable.pos[1] = 0;
						if( ui.position.left + leftMax < 0 )	ui.draggable.pos[0] = 0 - leftMax;
						if( ui.position.top  + topMax  < 0 )	ui.draggable.pos[1] = 0 - topMax;
					}
				});
			}).hide();
			
			$(".exit").click(function(){ // Reset to pre-zoom stage
				big.css({position:"static"}).hide();
				small.show().css({
					top: "0px",
					left: "0px",
					width: small_dimensions[0]+"px",
					height: small_dimensions[1]+"px"
				});
				that.panZoom();
				return false;
			});
			
		});
		
	});
	
};
