$(function()
{

	var	connections = [],
		updateConnections = function(conn, remove) {
			if (!remove) connections.push(conn);
			else {
				var idx = -1;
				for (var i = 0; i < connections.length; i++) {
					if (connections[i] === conn) {
						idx = i; break;
					}
				}
				if (idx !== -1) connections.splice(idx, 1);
			}
			if (connections.length === 10){
			var ok = true;
			for (var j = 0; j < connections.length; j++) {
					if (connections[j].sourceId.substring(1,3) !== connections[j].targetId.substring(1,3)) ok = false;
				}
			if (ok) $('#jplayer_well').jPlayer('play');
				else $('#jplayer_wrong').jPlayer('play');
			}
		};

	jsPlumb.ready(function() {

		var instance = jsPlumb.getInstance({
			DragOptions : { cursor: 'pointer', zIndex:2000 },
			EndpointHoverStyle: { fillStyle:"orange" },
			HoverPaintStyle: { strokeStyle:"orange" },
			Container:"main"
		});


		instance.doWhileSuspended(function() {

			instance.bind("connection", function(info, originalEvent) {
				updateConnections(info.connection);
			});
			instance.bind("connectionDetached", function(info, originalEvent) {
				updateConnections(info.connection, true);
			});

			instance.bind("connectionMoved", function(info, originalEvent) {
				updateConnections(info.connection, true);
			});

			var DropOptions = {
				tolerance:"touch"
			};

			var Color = "#f41c68";
			var Endpoint = {
				endpoint:["Dot", { radius:11 }],
				paintStyle:{fillStyle:Color },
				isSource:true,
				reattach:false,
				scope:"target",
				anchor: "Center",
				connectorStyle : {
					gradient:{stops:[[0, Color], [0.3, "#e2d18e"], [0.6, "#e2d18e"], [1, Color]]},
					lineWidth:4,
					strokeStyle:Color,
					dashstyle:"2 1"
				},
				isTarget:true,
				dropOptions : DropOptions
			};

			instance.addEndpoint(jsPlumb.getSelector(".target"), Endpoint);

		});

	});

});