$(document).ready( function() {
	var paper = Raphael("container", 640, 480);
	var palette = paper.rect(0,0,640,60);
	
	palette.attr({fill:"#eee"});
	var stage = paper.rect(0, 60, 640, 420);
	stage.attr({"stroke-width": "0", "fill": "#b38439"});
	
	var mic = paper.image("microphone2.png", 5, 5, 15, 47);
	//var amp = paper.image("amp.png", 45, 5, 53, 45);
	//var keys = paper.image("keyboard.png", 95, 5, 137, 45);
	
	var selected = null;
	var current = null;
	
	var _clone = function(prototype)
	{
		var theItem = paper.image(
			prototype.attr("href"),
			prototype.attr("x"),
			prototype.attr("y"),
			prototype.attr("width"),
			prototype.attr("height")
		);
		theItem.attr({"angle": 0, "gx": 0, "gy": 0});
		
		current = theItem;
		selected = theItem;
		
		theItem[0].onmousedown = function(e)
		{
			theItem.attr({"gx": e.pageX, "gy": e.pageY});
			current = theItem;
			selected = theItem;
		}
		
		theItem[0].onmousemove = function(e)
		{
			if(current == theItem) {
				var delta = {"x": e.pageX - theItem.attr("gx"), "y":e.pageY - theItem.attr("gy")};
				theItem.attr({"gx": e.pageX, "gy": e.pageY});
				//get distance and angle of mouse movement
				var r = Math.sqrt(Math.pow(delta.x,2) + Math.pow(delta.y, 2));
				var a = theItem.attr("angle")*Math.PI/180 - Math.asin(delta.y/r);
				theItem.attr("x", Math.cos(a)*r + theItem.attr("x"));
				theItem.attr("y", Math.sin(a)*r - theItem.attr("y"));
			}
		}
		
		theItem[0].onmouseup = function(e)
		{
			current = null;
		}
		
		return theItem;
	}
	
	mic[0].onmousedown = function(e) {
		theMic = _clone(mic);
		theMic[0].onmousedown(e);
	}
	
	var current = null;
	stage[0].onmouseup = function(e) {
		current = null;
	};
	
	$("#handle").draggable({"containment":"parent", "axis":"x"});
	$("#pos").text('0');
	$("#handle").mousedown(
		function(e) {
			sliding = 1;
		}
	);
	$("#canvas").mousemove(
		function(e) {
			if(sliding) {
				var pos = $("#handle").css("left");
				var angle = (pos.substring(0, pos.length - 2)*2) - 180;
				$("#pos").text(angle);
				if(selected) {
					selected.rotate(angle - selected.attr("angle"));
					selected.attr("angle", angle);
				}
			}
		}
	);
	$("#canvas").mouseup(
		function(e) {
			if(sliding) {
				sliding = 0;
			}
		}
	)
});
