// Gooey SoundManger2 MP3 Player
soundManager.url = '/javascripts/soundmanager2.swf'
soundManager.debugMode = false;

var GooeyMP3 = Class.create();
GooeyMP3.prototype = {
	
	initialize: function(n) {
		this.n 				    = n;
		var self;
		this.track_id 		= n;
		this.mp3_file_url	= track_url[n];
		this.plyr 			  = $('gooey_mp3_player['+n+']');
		highlight_length  = 60; // seconds of highlight to play
		start_volume      = 50;
		// create song
		soundManager.createSound({id: this.track_id, url: this.mp3_file_url, autoLoad: false, stream: true,
		  whileplaying: function() {
    	  if (!full_track) {
    	    // fade out volume 2 seconds before end
      	  if (this.position > ((highlight_length - 5) * 1000)) {
      	    start_volume  = start_volume * 0.9;
      	    this.setVolume(start_volume);
      	  }
      	  // stop track after highlight_length
      	  if (this.position > (highlight_length * 1000)) {
      	    $('play['+n+']').src  = '/images/gooey_mp3/hi_play.png';
      	    this.stop();
      	    this.setPosition(0);
      	  }
    	  }
    	},
    	onfinish: function() {
    	  $('play['+n+']').src  = '/images/gooey_mp3/hi_play.png';
    	}
  	});
		soundManager.setVolume(this.track_id, start_volume);
		this.song 			  = soundManager.getSoundById(n);
		
	},
	
	// Basic player functions
	
	renderPlayer: function(n) {
		$('play['+n+']').observe('click', this.playpauseMusic);	
	},
	
	playpauseMusic: function(e){
		gooeyPlayer = e.findElement('div');
		var n 		  = $(gooeyPlayer).readAttribute('player_id');
		var song 	  = players[n].song;
		
		if (song.playState == 1) {
			// song is paused
			$('play['+n+']').src  = '/images/gooey_mp3/hi_play.png';
			song.stop();
		} else {
			// stop all other players
			soundManager.stopAll();
			track_id.each(function(t, index) {
    	  $('play['+t+']').src  = '/images/gooey_mp3/hi_play.png';
    	});
			$('play['+n+']').src  = '/images/gooey_mp3/hi_pause.png';
			song.play();
		}
		debugInfo("playing or pausing");
	}
	
};


var players = new Array();
soundManager.onload = function() {
	// Get all players on this page:
	track_id.each(function(s, index) {
	  if(s) {
			var n = s;
			var newPlayer 	= new GooeyMP3(n);
			players[n] 		  = newPlayer;
			players[n].renderPlayer(n);
		}
	});
}

// Debugging Functions
// TODO: Move to general functions
debugit = false;
function debuggery() {
	// set global variable to true
	debugit 			= true;
	var debugdiv		= document.createElement('div');
	debugdiv.id			= 'debugdiv';
	debugdiv.innerHTML 	= 'Debugger';
	document.body.appendChild(debugdiv);
}
function debugInfo(debug_msg) {
	if (debugit) {
		var debuginfo		= document.createElement('div');
		debuginfo.innerHTML = debug_msg;
		$('debugdiv').appendChild(debuginfo);
	}
}
/**** HOW TO USE ****
// within your script/function, collect debug info:
var debug_msg		= players[n].slide_state;
debugInfo(debug_msg);

// at the end of your javascript, call
debuggery();
*/
// End debugger
//debuggery();