
var sounds = [];
var playing = false;
	
var SoundPlayer = function( tracks ) {

	var showAwaitingPlayable = function( id ) { document.getElementById( id ).src = './control_play.png'; };
	var showAwaitingStoppable = function( id ) { document.getElementById( id ).src = './control_stop.png'; };
	var showPlay = function( id ) { document.getElementById( id ).src = './control_play_blue.png'; };
	var showPause = function( id ) { document.getElementById( id ).src = './control_pause_blue.png'; };
	var showLoaded = function( id ) {
		showPlay( id );
		document.getElementById( id ).setAttribute( 'onclick', 'SoundPlayer().playSound( sounds[ this.id ], this.id );' );
		var stopper = document.getElementById( 'stop_' + id );
		stopper.setAttribute( 'onclick', 'SoundPlayer().stopSound( sounds[ \"' + track.id + '\" ], \"' + track.id + '\" );' );
		stopper.src = './control_stop_blue.png';
	}
	
	for ( var t in tracks ) {
		var track = tracks[ t ];
		
		var clickPlay = track.addTo.appendChild( document.createElement( 'img' ) );
		clickPlay.id = track.id;
		showAwaitingPlayable( track.id );
		
		var clickStop = track.addTo.appendChild( document.createElement( 'img' ) );
		clickStop.id = 'stop_' + track.id;
		showAwaitingStoppable( clickStop.id );
		
		sounds[ track.id ] = soundManager.createSound( 
			{ 
				id: track.id, 
				url: track.mp3,
				autoLoad: true,
				multishot: false,
				onload: function( success ) { showLoaded( track.id ); },
				onplay: function() { showPause( track.id ); },
				onresume: function() { showPause( track.id ); },
				onstop: function() { showPlay( track.id ); },
				onfinish: function() { showPlay( track.id ); }
			}
		);
	}
	
	return {
		playSound: function( sound, id ) {
			if ( !playing ) {
				showPause( id );
				sound.play();
			} else {
				sound.pause();
				showPlay( id );
			}
			playing = !playing;
		},
		
		stopSound: function( sound, id ) {
			if ( playing ) {
				sound.stop();
				sound.setPosition( 0 );
			}
			//showPlay( id );
		}
	}
}

var DrumPattern = function() {
	var detail = document.getElementById( 'detail' );
	
	function getNode( id ) {
		var n = document.getElementById( id );
		if ( !n ) {
			n = detail.appendChild( document.createElement( 'div' ) );
			n.id = id;
		}
		return n;
	}
	
	function removeContentFrom( e ) {
		while ( e && e.firstChild ) {
			e.removeChild( e.firstChild );
		}
	}
	
	return { 
		show: function( node ) {
			if ( !node.data ) {
				return;
			}
			detail.style.visibility = 'visible';
			removeContentFrom( detail );
			var pattern = eval( '(' + doAjaxSync( './drumpracticeupload.processor.php', 'action=getPattern&id=' + node.data.id ) + ')' );
			getNode( 'detail-name' ).innerHTML = pattern.uq;
			getNode( 'detail-notes' ).innerHTML = pattern.notes;
			for ( var s in pattern.sessions ) {
				var session = pattern.sessions[ s ];
				var sample = detail.appendChild( document.createElement( 'div' ) );
				if ( session.mp3 ) {
					var id_sample = node.data.id + '_' + session.id;
					SoundPlayer( [{ 'id': id_sample, 'mp3': session.mp3, 'addTo': sample }] );
				}
				sample.innerHTML += session.date;
				if ( session.notes ) {
					sample.innerHTML += ' ' + session.notes;
				}
			}
		},
		
		play: function( mp3, id_sample ) {
			document.getElementById( id_sample ).src = './control_pause.png';
			var sound = soundManager.createSound( { id: 'aSound', url: mp3 } );
			sound.play();
		},
	
		
		clear: function() {
			removeContentFrom( document.getElementById( 'tree' ) );
			removeContentFrom( detail );
			detail.style.visibility = 'hidden';
			removeContentFrom( document.getElementById( 'container' ) );
			removeContentFrom( document.getElementById( 'jitScript' ) );
		}
	}
};

function asPixels( v ) {
	return v + "px";
}

var DrumPatternNetwork = function() {

	var w = screen.availWidth / 1.5;
	var h = screen.availHeight - 200;

	function setupElements() {
		var detail = document.getElementById( 'detail' );
		var container = document.getElementById( 'container' );
		var centerContainer = container.appendChild( document.createElement( 'div' ) );
		var infovis = centerContainer.appendChild( document.createElement( 'div' ) );
				
		detail.style.width = asPixels( screen.availWidth - w - 125 );
		
		container.style.width = asPixels( w );
		container.style.height = asPixels( h );
		
		centerContainer.id = 'center-container';
		centerContainer.style.width = asPixels( w );
		centerContainer.style.height = asPixels( h );
		
		infovis.id = 'infovis';
		infovis.style.width = asPixels( w );
		infovis.style.height = asPixels( h );
	}
	
	function styleLabel( domElement, node ) {
		var style = domElement.style;
		style.display = '';
		style.cursor = 'pointer';
		style.color = 'white';
		if ( domElement.innerHTML === "all patterns" ) {
			style.fontSize = "1em";
			style.color = "#cccccc";
			style.fontWeight = "bold";
		} else if (node._depth == 0 ) {
			style.fontSize = "0.9em";
			style.fontWeight = "bold";
		} else if (node._depth <= 1) {
			style.fontSize = "0.8em";
		} else if (node._depth == 2) {
			style.fontSize = "0.7em";
			style.color = "black";
		} else {
			style.fontSize = "0.7em";
			style.color = "#494949";
		}
		var left = parseInt(style.left), w = domElement.offsetWidth;
		style.left = (left - w / 2) + 'px';
	}
	
	function styleBackground( canvas, ctx ) { // create a background canvas and plot concentric circles in it.
		var times = 6, 
				d = 100, 
				pi2 = Math.PI * 2;
				
		ctx.strokeStyle = "#cccccc";
		for (var i = 1; i <= times; i++) {
			ctx.beginPath();							
			ctx.arc(0, 0, i * d, 0, pi2, true);
			ctx.stroke();
			ctx.closePath();
		}
	}
	
	function createCanvas() {
		return new Canvas( 'mycanvas', 
				{ 
					'injectInto': 'infovis', 'width': w, 'height': h, 'backgroundCanvas': 
					{ 
						'styles': { 'strokeStyle': '#555' }, 
						'impl': { 'init': function() {}, 'plot': styleBackground }
					}
				}
		);
	}

	return {
		load: function( json ) {
			setupElements();
	
			var rgraph = new RGraph( createCanvas(), { 
					Node: { color: 'red' }, 
					Edge: { color: 'blue' }, 
					onBeforeCompute: function( node ) {
							DrumPattern().show( node );
					},
					onAfterCompute: function() {}, //Log.write("done");
					onCreateLabel: function( domElement, node ) { //This method is called once, on label creation. And a click handler to move the graph.
						domElement.innerHTML = node.name;
						domElement.onclick = function() {
							rgraph.onClick( node.id );
						};
					},
					onPlaceLabel: styleLabel //This method is called each time a label is plotted.
				} 
			);
	    
			rgraph.loadJSON( json );
			rgraph.refresh();
		}
	}
}


var DrumPatternDisplaySelect = function() {
	var url = "./_drumpracticetree.php";
	var loading = document.getElementById( 'loading' );
	
	function request( what ) {
		return "action=" + what;
	}
	
	function buildTreeFrom( o ) {
		var tree = new YAHOO.widget.TreeView( 'tree', eval( '(' + o + ')' ) );
		tree.subscribe( 'labelClick', function( node ) { 
			DrumPattern().show( node ); 
		} );
		tree.render();
		endLoading();
	}
	
	function startLoading() {
		loading.style.top = asPixels( ( screen.availHeight / 2 ) - 15 );
		loading.style.top = asPixels( ( screen.availHeight / 2 ) + 15 );
		loading.style.visibility = 'visible';
	}
	
	function endLoading() {
		loading.style.visibility = 'hidden';
	}
	
	function loadScript( src, id ) {
		var e = document.createElement( 'script' );
		e.id = id;
		e.src = src;
   		e.type = 'text/javascript';
   		document.body.appendChild( e );
	}

	return {
		"diary": function() {
			startLoading();
			buildTreeFrom( doAjaxSync( url, request( "diary" ) ) );
		},
		
		"tree": function() {
			startLoading();
			buildTreeFrom( doAjaxSync( url, request( "tree" ) ) );
		},
		
		"graph" : function() {
			startLoading();
			loadScript( '../jit/jit.js', 'jitScript' );
			if ( !Canvas ) {
				loadScript( '../jit/Extras/excanvas.js', 'excanvas' );
			}
			DrumPatternNetwork().load( eval( '(' + doAjaxSync( url, request( "graph" ) ) + ')' ) );
			endLoading();
		}
	}
}