$(document).ready(function(){
function log10(val) {
  return Math.log(val) / Math.log(10);
}

	$("a.jq_hide").text('');
	
	var ship_origin_x, ship_origin_y, dragging;
	$("img#ship").load (function(){
		ship_origin_x = $(this).offset().left;
		ship_origin_y = $(this).offset().top;
	});
	
	$(window).resize(function() {
		ship_origin_x = $("img#ship").offset().left;
		ship_origin_y = $("img#ship").offset().top;
	});
	
	$("img#ship").mousedown ( function (mouse_e) { 
		var ship_p = $("img#ship").offset();
		var init_diff_x = mouse_e.offsetX;
		var init_diff_y = mouse_e.offsetY;
		var ship_origin_x = ship_p.left;
		var ship_origin_y = ship_p.top;
	$(document).mousemove(function (mouse_e2) {			

		/*current mouse position (with image dragged)*/
		coord_x = mouse_e2.pageX - init_diff_x;
		coord_y = mouse_e2.pageY - init_diff_y;
		
		/*how far the dragging pointer is from the initial position*/
		dY = ship_origin_y - coord_y;
		dX = coord_x - ship_origin_x;

		distance = Math.sqrt( Math.pow(dY,2) + Math.pow(dX,2) );
		rate = ((215-distance)/215);
		rate = rate*100;
		rate = log10(rate)/2;
		
		coord_x_2 = ship_origin_x + (dX * rate);
		coord_y_2 = ship_origin_y - (dY * rate);
		$("img#ship").offset({ top: (coord_y_2), left: (coord_x_2)});

		if(dY < 0 || dX < 0) {
			$("img#ship").offset({ left: ship_origin_x, top: ship_origin_y});
			$(document).unbind();
		}

		if(dY > dX) {
			$("img#ship").offset({ left: (ship_origin_x + (dY * rate))});
		}
		
		if(dX > dY) {
			$("img#ship").offset({ top: (ship_origin_y - (dX * rate))});
		}
		
		if ( distance > 150 ) {
			$("img#ship").animate({ left: '+=2000', top: '-=2000'}, 4000);
			$(document).unbind();
		}

		$("#output").text( rate );

		$(document).mouseup ( function() { 
			$("img#ship").offset({ left: ship_origin_x, top: ship_origin_y });
			$(document).unbind();
		});
	});
		return false;
	} );
})
