/*
* jQuery-1.4.4 flashSound by FirstView (http://firstviewmedia.com).
* This lets you play a sound through flash. The sond.swf flash file is needed.
* Options include some callbacks and the location where you would like to store the SWF
*/
/*
Eg. :

$('._jsPlayAudio').flashSound({
	onPause:function( $this ){
		$this.html('Paused');
	},onPlay:function( $this ){
		$this.html('Playing');
	},onInit:function( $all ){
		$all.html('Preview');
	}
});

*/

(function($){
	$.fn.flashSound = function(opts) {
	
		var defaults = {
			swfUrl: 'flash/flashSound.swf',		// SWF URL relative to root. //		
			onPause: null,						// Additional function to peform when sound gets paused. //
			onPlay: null,						// Additional function to peform when sound gets played after being paused. //
			onInit: null						// Additional function to peform when sound gets played first time around. //
		};
		var opts								= $.extend(defaults, opts);
		var flashContString						= '#_jsFlashAudioContainer ._jsFlashAudioPlayer';
		var $all								= this;
		
		createNewAudioPlayer();
		
		return this.each(function(){
			
			var $this = $(this);
			if( opts.onInit ) opts.onInit($all);
			$this.unbind('click').click(function( e ){
				e.preventDefault();
				
				if( $(this).data('audioStatus') == 'playing' ){
					$(this).data('audioStatus', 'paused');
					pauseFlashAudio();
					if( opts.onPause ) opts.onPause($this);
				}else if( $(this).data('audioStatus') == 'paused' ){
					$(this).data('audioStatus', 'playing');
					playFlashAudio();
					if( opts.onPlay ) opts.onPlay($this);
				}else{
					$(this).data('audioStatus', 'playing');
					var audioUrl = $(this).attr('href');
					loadSound(audioUrl);
					$all.not( $(this) ).each(function(){
						$(this).data('audioStatus', false);
					});
					if( opts.onInit ) opts.onInit($all.not( $(this) ));
					if( opts.onPlay ) opts.onPlay($this);
				}
			});		
			return this;
		});
		
		
		function createNewAudioPlayer( audioUrl ){
			var $flashContainer = $('<div id="_jsFlashAudioContainer"><div class="_jsFlashAudioPlayer"></div></div>');
			$flashContainer.css({'position':'fixed', 'top':-9999, 'left':-9999});
			$('body').append($flashContainer);
			$flashContainer = $(flashContString);
			$flashContainer.flash({
				swf:opts.swfUrl,
				width:200,
				height:200,
				flashvars:{
					audioUrl:audioUrl,
					autoPlay:false
				}
			
			});
		}
		
		function loadSound( audioUrl ){
			var $flashContainer = $(flashContString);
			$flashContainer.flash(function(){ this.loadSound(audioUrl); });
		}
		
		function playFlashAudio(){
			var $flashContainer = $(flashContString);
			$flashContainer.flash(function(){ this.playMovie(); });
		}
		
		function pauseFlashAudio(){
			var $flashContainer = $(flashContString);
			$flashContainer.flash(function(){ this.pauseMovie(); });
		}
		
		
	};
})(jQuery);

