//# SoundCloud Custom Player

//Make sure to require [SoundManager2](http://www.schillmania.com/projects/soundmanager2/) before this file on your page.
//And set the defaults for it first:

var SOUNDCLOUD_PLAYER_SET_URI = 'http://soundcloud.com/deconstruction-records/sets/website';
//'http://soundcloud.com/deconstruction-records/sets/way-out-west-the-gift-full-length-96-kbps/s-6XI5F';
var consumer_key = '05iB6Cqr7HVJIhLeTW3Axw';

soundManager.url = '/js/soundmanager/swf/';
soundManager.flashVersion = 9;
soundManager.useFlashBlock = false;
soundManager.useHighPerformance = true;
soundManager.wmode = 'transparent';
soundManager.useFastPolling = true;
soundManager.debugMode = false;

//Wait for jQuery to load properly
$(function(){
	
	// Wait for SoundManager2 to load properly
	
	soundManager.onready(function() {
		
		// ## SoundCloud
		// Pass a consumer key, which can be created [here](http://soundcloud.com/you/apps), and your playlist url.
		// If your playlist is private, make sure your url includes the secret token you were given.
		
		var url = SOUNDCLOUD_PLAYER_SET_URI;
		var lastTrack;
		var numTracks;
		
		// Resolve the given url and get the full JSON-worth of data from SoundCloud regarding the playlist and the tracks within.
		$.getJSON('http://api.soundcloud.com/resolve?url=' + url + '&format=json&consumer_key=' + consumer_key + '&callback=?', function(playlist) {
			
			// I like to fill out the player by passing some of the data from the first track.
			// In this case, you'll just want to pass the first track's title.

			$('.player-title h2 b span').text(playlist.tracks[0].title);
			numTracks = playlist.tracks.length;
			$('.player h2 b span').text('1/'+numTracks);

			// Loop through each of the tracks
			
			$.each(playlist.tracks, function(index, track) {
				
				// Create a list item for each track and associate the track *data* with it.
				// track.title
				$('<li id="li_'+track.id+'"></li>').data('track', track).appendTo('.player-tracks ol');
				
				// * Get appropriate stream url depending on whether the playlist is private or public.
				// * If the track includes a *secret_token* add a '&' to the url, else add a '?'.
				// * Finally, append the consumer key and you'll have a working stream url.

				url = track.stream_url;
				
				(url.indexOf("secret_token") == -1) ? url = url + '?' : url = url + '&';
				
				url = url + 'consumer_key=' + consumer_key;
				
				// ## SoundManager2
				// **Create the sound using SoundManager2**
				
				soundManager.createSound({
					
					// Give the sound an id and the SoundCloud stream url we created above.
					
					id: 'track_' + track.id,
					url: url,
					
					// On play & resume add a *playing* class to the main player div.
					// This will be used in the stylesheet to hide/show the play/pause buttons depending on state.
					
					onplay: function() {
						
						$('.player .play-pause').addClass('playing');
						
						$('.player-title h2 b span').text(track.title);

						lastTrack = $('.player-tracks ol li#li_'+track.id);
						
					},
					
					whileplaying: function() {
						$('.player-title .progress').css('width', 100*this.position / track.duration+'%');
					},
					
					onstop: function() {
					
					},
					
					onresume: function() {
						
						$('.player .play-pause').addClass('playing');
						
					},
					
					// On pause, remove the *playing* class from the main player div.
					
					onpause: function() {
						$('.player .play-pause').removeClass('playing');
					},
					
					// When a track finished, call the Next Track function. (Declared at the bottom of this file).
					
					onfinish: function() {
						nextTrack();
					}
					
				});
				
			});
			lastTrack = $('.player-tracks ol li:first');
			if(navigator.userAgent.indexOf('iPhone') == -1 && navigator.userAgent.indexOf('iPad') == -1 && navigator.userAgent.indexOf('iPod') == -1)
				lastTrack.click();
		});

		// ## GUI Actions
		
		// Bind a click event to each list item we created above.

		$('.player-tracks ol li').live('click', function(e){
			
			e.preventDefault();
			// Create a track variable, grab the data from it, and find out if it's already playing *(set to active)*
			
			var $track = $(this),
					data = $track.data('track'),
					playing = $track.is('.active');
					
			if (playing) {
				
				// If it is playing: pause it.
				
//				soundManager.pause('track_' + data.id);				
				
			} else {
				
				// If it's not playing: stop all other sounds that might be playing and play the clicked sound.
				soundManager.stopAll();
				$('.player .play-pause').removeClass('playing');
				soundManager.play('track_' + data.id);
				
			}
			
			// Finally, toggle the *active* state of the clicked li and remove *active* from and other tracks.
			var trackIndex = $('.player-tracks ol li').index(this) + 1;
			$('.player h2 b span').text(trackIndex+'/'+numTracks);
			
			$track.addClass('active').siblings('li').removeClass('active');
			
		});
		
		// Bind a click event to the play / pause button.
		
		$('.player .play-pause').live('click', function(e){
			
			if ( $('.player-tracks ol li').hasClass('active') == true ) {
				
				// If a track is active, play or pause it depending on current state.
				
				soundManager.togglePause( 'track_' + $('.player-tracks ol li.active').data('track').id );
							
			} else {
				
				// If no tracks are active, just play the last one.
				lastTrack.click();
				
			}
			
		});

		$('.player .skip-forward').live('click', function() {
			nextTrack();
		});
		
		// Bind a click event to the previous button, calling the Previous Track function.
		
		$('.player .skip-back').live('click', function() {
			prevTrack();
		});
		
		$('.player .mute').live('click', function() {
			$(this).toggleClass('muted');
			$('.player-tracks ol li').each(function() {
				soundManager.toggleMute('track_' + $(this).data('track').id);
			});
		});
		
		$('.player .control').live('click', function(e) {
			e.preventDefault();
		});
		
		// ## Player Functions
		
		// **Next Track**
		
		var nextTrack = function(){
			
			// Stop all sounds
			
			soundManager.stopAll();
			
			// Click the next list item after the current active one. 
			// If it does not exist *(there is no next track)*, click the first list item.

			if ( $('.player-tracks ol li.active').next().click().length == 0 ) {
				$('.player-tracks ol li:first').click();
			}
			
		};
		
		// **Previous Track**
		
		var prevTrack = function(){
			
			// Stop all sounds
			
			soundManager.stopAll();
			
			// Click the previous list item after the current active one. 
			// If it does not exist *(there is no previous track)*, click the last list item.

			if ( $('.player-tracks ol li.active').prev().click().length == 0 ) {
				$('.player-tracks ol li:last').click();
			}
			
		};

	});
	
});

