jQuery.fn.extend({
	draggableImage: function(imageHeight){
		return this.each(function(){
										  			
			var clicked = false;
			var current_x;
			var current_y;
			var target_x;
			var target_y;
			var backgroundPos_x = 0;
			var backgroundPos_y = 0;
			var drag_div = $(this);
			var animationTimeout = null;
			var animationInterval = 40;
			var trappableMargin = 60;
			var img_height = imageHeight;
			var img_width;
			
			//Set the hidden image as a bg image
			var bgimg = $(this).children('img');
			img_width = bgimg.width();
			img_height = bgimg.height();
			$(this).css('background-position', "0 0");
			$(this).css('background-repeat', "no-repeat");
			$(this).css('background-image', "url('"+bgimg.attr('src')+"')");
			bgimg.css('display', 'none');
			
			//Bind mouse down event
			$(this).mousedown(function(e){
				$(this).css('cursor', 'move');
				clicked = true;
				current_x = Math.round(e.pageX - $(this).eq(0).offset().left);
				current_y = Math.round(e.pageY - $(this).eq(0).offset().top);
				target_x = current_x;
				target_y = current_y;
			});
			
			//Bind the mouse up
			$(this).mouseup(function(e){
				$(this).css('cursor', 'default');
				clicked = false;
			});
			/*
			if(img_height < drag_div.height()){
				$('body').before(img_height);
				alert(img_height);
			}
			*/
			//Bind the mouse move
			var animateImageMovement = function() {				
				var movement_x = Math.round((target_x - current_x) / 5); // making it ease
				var movement_y = Math.round((target_y - current_y) / 5); // making it ease.
				backgroundPos_x += movement_x;
				backgroundPos_y += movement_y;
								
				if (img_height > drag_div.height()) {
					if (backgroundPos_y < 0 - (img_height - drag_div.height())){
						backgroundPos_y = 0 - (img_height - drag_div.height());
					}
					if (backgroundPos_y > 0){
						backgroundPos_y = 0;
					}
				}
				current_x += movement_x;
				current_y += movement_y;
				
				drag_div.css('background-position', 0 + "px " + backgroundPos_y + "px");
				
				if (movement_x == 0 && movement_y == 0) {
					clearInterval(animationTimeout);
					animationTimeout = null;
				}
			}
			$(this).mousemove(function(e){
				if (clicked) { //as we only want this to work while they have clicked	
					target_x = Math.round(e.pageX - $(this).eq(0).offset().left);
					target_y = Math.round(e.pageY - $(this).eq(0).offset().top);
					if (animationTimeout == null) animationTimeout = setInterval(animateImageMovement, animationInterval);
				}
			});
			
		});
	}
});
