$(document).ready(
	function() {
		var paper = Raphael("container", 640, 480);
		var square = paper.rect(320, 240, 20, 20);
		
		angle = 45;
		
		square.attr({
			"fill":"#b34300",
			"id":"square",
			"currentx":parseInt($("#container").css("margin-left"), 10) - square.attr("x"),
			"currenty":parseInt($("#container").css("margin-top"), 10) - square.attr("y"),
			"angle": 0
		});
		
		function startDrag(e) {
			deltax = e.pageX - square.attr("currentx");
			deltay = e.pageY - square.attr("currenty");
			x = parseInt(square.attr("x")) + deltax;
			y = parseInt(square.attr("y")) + deltay;
			square.rotate(0 - angle);	//rotate back to 0, then move
			square.attr({
				"x":x,
				"y":y,
				"currentx":e.pageX,
				"currenty":e.pageY
			});
			square.rotate(angle);	//move finished, so re-rotate to angle
			$("#output").html("x:" + x + ", y:" + y);
		}
		
		function stopDrag(e) {
			$("#container").unbind("mousemove", startDrag);
			$("#container").unbind("mouseup", stopDrag);
		};
		
		$("#square").mousedown(function(e) {
			$("#square").attr({
				"currentx":e.pageX,"currenty":e.pageY
			});
			
			$("#container").bind("mousemove", startDrag);
			$("#container").bind("mouseup", stopDrag);
			
		});
		
		$("#rotate").click(function(e) {
			if(this.clicked == "undefined" || this.clicked == 0) {
				this.clicked = 1;
				square.rotate(angle);
				square.attr("angle", square.attr("angle") + angle);
				$("#rotate").html("Rotate");
			} else {
				this.clicked = 0;
				square.rotate(0 - angle);
				square.attr("angle", square.attr("angle") - angle);
				$("#rotate").html("Unrotate");
			}
			
		});
	}
);
