// =============================================================================
//
// jceMP3 Plugin for jQuery 1.2.1
// By Michael Smith
// Mark Stickley
// Mike Thirlwell
//
// =============================================================================

	// Global vars

var soundplayerImgPath = "/images/site" ; // Definitely change this.
	
var currPos = -1;
var soundplayer;
var statusMsg;

// DO NOT CHANGE ANYTHING BELOW THIS LINE ======================================

	// Declare the jceMP3 Plugin
$.fn.jceMP3 = function(settings) {

		// Setup some default settings, and override the defaults with whatever is passed in
	var settings = $.extend({
		restart: false,
		fastForward: false,
		rewind: false,
		detatch: false,
		container: this.attr("id"),
		loadfile: false,
		autoplay: false,
		hideButtonsWhileLoading: false,
		soundplayerFlashLocation: "/flash/soundplayer.swf",
		updateInterval: 100
	},settings) ;
	
		// Initialise the flash movie component and jceMP3
	$.jceMP3.initFlash(settings) ;
	$.jceMP3.initMP3(settings) ;
	
		// Attach a click event that will play the song for anything with a class of jceMP3
	$(".jceMP3").each( function() {
		$(this).click( function() {
			currSong = $(this).attr("href").replace(/\/song\//,"") ;
			$.jceMP3.loadAndPlayTrack($(this).attr("href")) ;
			$.jceMP3.switchPlayPauseTo('pause') ;
			return false ;
		}) ;
	}) ;
	
		// Attach the click events to the playhead
	$("#playpause").click( function() { $.jceMP3.playPause($(this).attr("href")) ; return false ; }) ;
	$("#stopplayer").click( function() { $.jceMP3.stopTrack() ; return false ; }) ;
	(settings.rewind ? $("#rewindplayer").click( function() { $.jceMP3.movePlayerPos(-5) ; return false ; }) : false) ;
	(settings.fastForward ? $("#fastforwardplayer").click( function() { $.jceMP3.movePlayerPos(+5) ; return false ; }) : false) ;
	(settings.restart ? $("#restartplayer").click( function() { $.jceMP3.stopTrack() ; $.jceMP3.playPause('play') ; return false ; }) : false); 
	(settings.detatch ? $("#detatchplayer").click( function() { settings.detatch() ; return false ; }) : false); 
	
		// If loadfile is passed ...
	if (settings.loadfile) {
	
			// Hide buttons if appropriate.
		if (settings.hideButtonsWhileLoading) {
			$('#'+settings.container+' .controls').hide() ;
		}
		
		// Load and (optionally) play the track.
		setTimeout(function() {
			if (settings.autoplay) {
				$.jceMP3.loadAndPlayTrack(settings.loadfile) ;
			} else {
				$.jceMP3.loadTrack(settings.loadfile) ;
			}
		},1000) ;
	}
	
		// Don't break the chain!
	return this ;
}

$.jceMP3 = {
	initFlash: function(settings) {
		var pid = Date().replace(/[^a-z0-9]+/gi,'') ; // generate a unique id for ie to prevent caching.
		var so = new SWFObject(settings.soundplayerFlashLocation+"?pid="+pid, "soundplayer", "0", "0", "8.0.15", "#FFFFFF", true) ;
		so.addParam("allowScriptAccess", "always") ;
		$("#"+settings.container).append('<div id="mp3player"></div>') ;
		so.write('mp3player') ;
	},
	initMP3: function(settings) {
			// Append the player to the element that jceMP3 is called on
		$("#"+settings.container).append('<div id="playhead" class="musicplayer">'+
										 '<div class="screen">'+
										 '<p id="info">No song information available</p>'+
										 '<span id="status"></span>'+
										 '<div id="loadProgressContainer"><div id="loadProgressIndicator"></div></div>'+
										 '<div id="songProgressContainer"><div id="songProgressIndicator"></div></div>'+
										 '<span id="position"></span>'+
										 '</div>'+
										 '<div class="controls">'+
										 '<p>'+
										 '<a id="playpause" href="play" title="Play/Pause">[ Play ]</a>'+
										 '<a id="stopplayer" href="stop" title="Stop">[ Stop ]</a>'+
										 (settings.rewind ? '<a id="rewindplayer" href="rewind" title="Rewind">[ Rewind ]</a>' : '')+
										 (settings.fastForward ? '<a id="fastforwardplayer" href="fastforward" title="Fast forward">[ Fast forward ]</a>' : '')+
										 (settings.restart ? '<a id="restartplayer" href="restart" title="Restart">[ Restart ]</a>' : '')+
										 (settings.detatch ? '<a id="detatchplayer" href="detatch" title="Detatch">[ Detatch ]</a>' : '')+
										 '</p>'+
										 '</div>'+
										 '</div>') ;

		soundplayer = $('#soundplayer').get(0) ;
		
			// If the soundplayer hasn't initialised yet, set a timeout of 1 second to set it up again
		if(!soundplayer){
			setTimeout('$.jceMP3.initMP3(settings)', 1000);
		} else {
				// If it is ready, update the info of the player 10 times a second, but start it after a second to ensure that the flash movie is definiately setup (causes problems if you dont do this)
			setTimeout(function() {
				setInterval('$.jceMP3.updatePlayhead()', settings.updateInterval);
				$("body").attr("onunload","$('#soundplayer').remove();") ;
			},1000) ;
		}		
	},
	updatePlayhead: function() {
		if(soundplayer){
			soundplayer.update_status() ;
		}
	},
	loadTrack: function(trk) {
		if(soundplayer){
			soundplayer.load_sound(trk);
			$.jceMP3.switchPlayPauseTo('play');
		}
	},
	loadAndPlayTrack: function(trk) {
		if(soundplayer){
			soundplayer.load_and_play_sound(trk);
			$.jceMP3.switchPlayPauseTo('pause');
		}
	},
	stopTrack: function() {
		if(soundplayer){
			soundplayer.play_sound_from(0) ;
			setTimeout('soundplayer.stop_sound();',100);
			$.jceMP3.switchPlayPauseTo('play');
		}
	},
	playPause: function(option) {
		if(soundplayer){
			if(option=='play'){
				soundplayer.play_sound();
				$.jceMP3.switchPlayPauseTo('pause');
			}
			else if(option=='pause'){
				soundplayer.pause_sound();
				$.jceMP3.switchPlayPauseTo('play');
			}
		}
	},
	switchPlayPauseTo: function(option) {
		if(option=='pause') {
			$("#playpause").attr("href","pause").text("[ Pause ]").css("background-image","url("+soundplayerImgPath+"/player-pause.png)") ;
		}
		else if(option=='play') {
			$("#playpause").attr("href","play").text("[ Play ]").css("background-image","url("+soundplayerImgPath+"/player-play.png)") ;
		}
		return false ;				
	},
	movePlayerPos: function(amountToMoveInSecs) {
		soundplayer.play_sound_from(currPos + amountToMoveInSecs) ;
		return false ;
	},
	setInfo: function(v) {
		var songInfo = v.split("|") ;
		var text = new Array() ;
		if (songInfo[0] != 'undefined') text.push(songInfo[0]) ;
		if (songInfo[1] != 'undefined') text.push(songInfo[1]) ;
		text = text.join("<br />") ;
		if (text == '') text = 'No song information available' ;
		$("#info").html(text);
	},
	setStatus: function(v) {
		var pc_loaded = soundplayer.get_sound_pc_loaded() ;
		$("#status").text(v) ;
		
		if (pc_loaded == -1) {
			$("#loadProgressIndicator").css("width","0") ;
		}
		else if (pc_loaded == 100) {
			$("#loadProgressIndicator").css("width","100%") ;
			$('.controls').show() ;
		}
		else {
			$("#loadProgressIndicator").css("width",pc_loaded + "%") ;
		} 
	},
	setPos: function(p,l) {
		currPos = Math.floor(p / 1000) ;
		pMinutes = Math.floor(p / 1000 / 60) ;
		pSeconds = Math.floor((p / 1000 / 60 - Math.floor(p / 1000 / 60)) * 60) ;
		if (pSeconds.toString().length == 1) pSeconds = "0" + pSeconds.toString() ;
		lMinutes = Math.floor(l / 60) ;
		lSeconds = Math.floor((l / 60 - Math.floor(l / 60)) * 60) ;
		if (lSeconds.toString().length == 1) lSeconds = "0" + lSeconds.toString() ;
		$("#position").text(pMinutes + ":" + pSeconds + " / " + lMinutes + ":" + lSeconds) ;
		percentage = Math.floor(p / 1000 / l * 100) ;
		$("#songProgressIndicator").css("width",percentage + "%") ;
		if (percentage == 100) $.jceMP3.stopTrack() ;
	}
}



/*
Notes on functionality:
There are several functions available to the soundplayer, called like this:
soundplayer.function_name(arg1, arg2, ...);

These functions are:
load_sound(url) - loads a sound file
load_and_play_sound(url) - loads a sound file and plays it on a successful load
get_sound_position() - returns the position (seconds, rounded down) of the playhead
get_sound_pc_loaded() - returns the percentage loaded of the current loading sound. Returns -1 if the sound is not loading
get_sound_vol() - returns the current volume (1-100)
get_sound_repeat() - returns true or false on whether the sound is set to repeat
get_sound_status() - returns the current status message (Eg Loaded, Stopped, ...)
get_sound_length() - returns the length in seconds of the sound
set_sound_vol(vol) - sets the sounds volume to vol (1-100)
set_repeat(rep) - sets the sound to repeat or not to repeat depending on the value of rep (boolean)
play_sound() - plays sound from the beginning (or from the point at which it was paused, if it was indeed paused)
play_sound_from(pos) - plays sound from pos second into the file
stop_sound() - stops playback and resets the play head to the start (so play_sound will always start at the beginning)
pause_sound() - stops playback and sets a pause pointer (so play_sound will start playing where it left off)

*/

