/**
 * @author Paul G. de Jong
 * 
 * To use this script make a song list array like: 
 * var songList = ['http://kjpaul.com/songs/2011/04/19107.ogg','http://kjpaul.com/songs/2011/04/19108.ogg','http://kjpaul.com/songs/2011/04/19109.ogg'];
 * 
 * then call 
 * listPlayer(songList, '#id');
 * probably via an onclick event like this:
 *     <div id="id1">
 *       <div onclick="listPlayer(['http://kjpaul.com/songs/2011/04/19107.ogg','http://kjpaul.com/songs/2011/04/19108.ogg','http://kjpaul.com/songs/2011/04/19109.ogg'], '#id1')">click me</a>
 *     </div>
 * 
 * This script uses jQuery!
 * 
 **/

  	var saveHtml = '';
  	function listPlayer(songList, elm){
  		/**
  		 * This is a recursive function that will play every song in the songList and then return the original HTML
  		 * The songList is an array of songs urls with an ogg or oga extension. 
  		 * The script assumes there is also a .m4a version of the song.
  		 */
  		elm = typeof(elm)==='undefined' ? this : elm;
  		if(saveHtml === ''){ saveHtml = $(elm).parent().html(); }//grab original HTML to reset to after final song ends
  		var song = songList.shift(); //grab next song from array and remove it array
  		var s = song.slice(0,-4);
  		var x = song.slice(-4);
  		str = '<span><audio controls="controls"><source src="' + s + '.m4a" type="audio/mp4" /><source src="' + s + x + '" type="audio/ogg" /><a href="' + s + '.m4a">download song</a></audio></span>';
  		//note: need to keep track of html of paused elements.... fix this later..
  		$(elm).parent().html(str).find('audio').one({ //use parent incase the calling tag was an anchor tag
  			ended: function(){ 
  				if( songList.length > 0 ){ //then there is a playlist
  					listPlayer( songList, this ); 
  				}else{ //no playlist or end of playlist, so restore original html
//	  				alert(this.saveHtml);
  					$(this).parent().parent().html( this.saveHtml ); //remove extra span I added in str
  					saveHtml = ''; 
  				}
  			}, loadstart: function(){ 
//  				alert(saveHtml.slice(1,6).toLowerCase());
  				if(typeof(this.saveHtml)=='undefined' && saveHtml.slice(1,5).toLowerCase() != 'audio'){
  					this.saveHtml = saveHtml;
  					saveHtml = '';
  				} 
//  				alert(this.saveHtml);
  				$('audio').each(function(){
  					this.pause();
  				});
  			}, canplay: function(){
  				this.play();
  			} 
  		});
  		//$(elm).find('audio').one('canplay',function(){this.play();});
  	}

