/**
 * AL_Playa is an audio playback plugin, created for Integrative Trauma Treatment.
 */	
var AL_Playa=function(player) {
	// variables
	this.player=player;
	this.sound=false;	
	this.loaded=false;
	this.playing=false;
	this.progressBar=false;
	this.elapsedTime=false;
	this.duration=0;
	this.ufiles='ufiles/';	

	/**
	 * Pauses every other player in the DOM, and plays whatever sound file has been loaded into this SM2 instance.
	 *
	 * @return `true` if the play command was successful, does not check if track is playing
	 */
	this.play=function() {
		var self = this;
		var buffer = 1000;
		
		soundManager.onready(function() {
			if (self.loaded && self.sound) {
				soundManager.pauseAll();
				$('.playa').find('.playpause').removeClass('playing');
				self.sound.play();
				self.playing=true;
			} else {
				$.error('Track has not been loaded.');
			}
		});
		self.progressBar  = setInterval(function() { 
			var position = Math.floor((self.sound.position/self.sound.durationEstimate)*100);
			player.find('.head').animate({left: position+'px' });
		}, buffer);
		self.elapsedTime  = setInterval(function() { 
			player.children('.time').children('.elapsed').html(self.time(self.sound.position)); 
		}, buffer);
		
		return self.playing;
	};
	
	/**
	 * Stops the currently playing sound file and returns the head to the starting position.
	 */
	this.stop=function() {
		var self = this;
		
		soundManager.onready(function() {
			self.sound.stop();
			self.playing=false;
			clearInterval(self.progressBar);
			clearInterval(self.elapsedTime);
			player.find('.head').css({left: '1px' });
		});
		return self.playing;
	}

	/**
	 * Pauses the currently playing sound file.
	 *
	 * @return `true` if it worked
	 */
	this.pause=function() {
		var self = this;
		
		soundManager.onready(function() {
			self.sound.pause();
			self.playing=false;
			clearInterval(self.progressBar);
			clearInterval(self.elapsedTime);
		});
		
		return self.playing;
	};
	
	/**
	 * Parses a given millisecond value into a human-readable format. Used for displaying duration and current position
	 *
	 * @param {int} ms - the duration of this track in ms
	 * @return the duration of this track in minutes:seconds
	 */
	this.time=function(ms) {
		var s = ms/1000;
		var m = Math.floor(s/60); 
		s = (Math.floor(s % 60) >= 10) ? Math.floor(s % 60) : '0'+Math.floor(s % 60);
		return m+':'+s;
	};

	/**
	 * Looks up an audio recording in the database
	 *
	 * @param {int} recording - the ID of the recording being loaded in
	 */
	this.load=function(recording) {
		var result;
		var self = this;
		var playerID = player.attr('id');
		
		if (typeof recording == 'number') {
			$.ajax({
				url: 'ajax/track.php',
				data: { id: recording },
				method: 'GET',
				dataType: 'json',
				success:  function(track, status, xhr) {
					soundManager.onready(function() {
						if (track.filename) {
							self.sound = soundManager.createSound({
											id: 	playerID,
											url: 	'ufiles/'+track.filename,
											volume: 100
										 });
							self.loaded = true;
						} else {
							self.loaded = false;
						}

					});
				},
				error: 	  function(xhr, status, error) {
					console.error(error);
					self.loaded = false;
				}
			});
		} else {
			if (recording == this.ufiles) {
				$.error('You must specify a sound to load into #'+playerID);
				self.loaded = false;
			} else {
				soundManager.onready(function() {
					self.sound = soundManager.createSound({
						id: playerID,
						url: recording,
						volume: 100
					});
					self.loaded = true;
				});
			}
		}
		
		return self.loaded;
	};
};
6
/**
 * jQuery wrapper plugin. This is the plugin's "runtime", where it's executed on the page
 */
$.fn.playa=function(options) {	
	var player 	= this;
	var track   = new AL_Playa(player);
	
	track.load(player.data('recording'));

	// Play/Pause control, toggles the action and src of the button img
	player.find('.playpause, .meta img').click(function(e) {
		e.preventDefault();
		
		var playPause = $(this);
		
		if (track.loaded && track.playing) {
			track.pause();
			playPause.removeClass('playing');
		} else if (track.loaded) {
			track.play();
			playPause.addClass('playing');
		} else {
			$.error('No track loaded into #'+player.attr('id'));
			playPause.removeClass('playing');
		}
	});
	
	// Stop control, stops the audio and returns to the beginning
	player.find('.stop').click(function() {
		var playPause = $(this).closest('.controls').find('.playpause');
		
		if (track.loaded && track.playing) {
			track.stop();
			playPause.removeClass('playing');
		} else if (!track.loaded) {
			$.error('No track loaded into #'+player.attr('id'));
		}
	});
};
