//# 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 JSONURL = WEBROOT+'js/playlist.json.php';
//JSONURL = 'http://localhost/roybailey/newsite/js/playlist.json.php';

/*
// try on roybailey site, check error function in $.ajax, below
$.ajax({
	type: 'GET',
	url: JSONURL,
	processData: true,
	data: {},
	dataType: "json",
	success: function(json) {
		alert("success");
	},
	error: function (xhr, ajaxOptions, thrownError){
		alert(xhr.status);
		alert(thrownError);
	}
});
//*/
//		return;


soundManager.url = WEBROOT+'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 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(JSONURL, 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.

			$('#soundplayer .player-title').text(playlist.tracks[0].title);
			$('#soundplayer .player-image').html('<a href="'+playlist.tracks[0].album_url+'"><img src="'+playlist.tracks[0].artwork+'" /></a>');
			$('#soundplayer .player-info').text(playlist.tracks[0].info);
			numTracks = playlist.tracks.length;

			// 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+'"><a href="#">'+track.title+'</a></li>').data('track', track).appendTo('#soundplayer .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 + '&';
				
				// ## 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() {
						
						$('#soundplayer .player-controls .play-pause').addClass('playing');
						
						$('#soundplayer .player-title').text(track.title);
						$('#soundplayer .player-image').html('<a href="'+track.album_url+'"><img src="'+track.artwork+'" /></a>');
						$('#soundplayer .player-info').text(track.info);

						lastTrack = $('#soundplayer .player-tracks ol li#li_'+track.id);
						
					},
					
					whileplaying: function() {
						$('#soundplayer .player-progress-container .progress').css('width', 100*this.position / this.duration+'%');
					},
					
					onstop: function() {
					
					},
					
					onresume: function() {
						
						$('#soundplayer .player-controls .play-pause').addClass('playing');
						
					},
					
					// On pause, remove the *playing* class from the main player div.
					
					onpause: function() {
						$('#soundplayer .player-controls .play-pause').removeClass('playing');
					},
					
					// When a track finished, call the Next Track function. (Declared at the bottom of this file).
					
					onfinish: function() {
						nextTrack();
					}
					
				});
				
			});
			lastTrack = $('#soundplayer .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.

		$('#soundplayer .player-tracks ol li a').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).parent(),
					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();
				$('#soundplayer .player-controls .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 = $('#soundplayer .player-tracks ol li').index(this) + 1;
			
			$track.addClass('active').siblings('li').removeClass('active');
			
		});
		
		// Bind a click event to the play / pause button.
		
		$('#soundplayer .player-controls .play-pause').live('click', function(e){
			
			if ( $('#soundplayer .player-tracks ol li').hasClass('active') == true ) {
				
				// If a track is active, play or pause it depending on current state.
				
				soundManager.togglePause( 'track_' + $('#soundplayer .player-tracks ol li.active').data('track').id );
							
			} else {
				
				// If no tracks are active, just play the last one.
				lastTrack.find('a').click();
				
			}
			
		});

		$('#soundplayer .player-controls .skip-forward').live('click', function() {
			nextTrack();
		});
		
		// Bind a click event to the previous button, calling the Previous Track function.
		
		$('#soundplayer .player-controls .skip-back').live('click', function() {
			prevTrack();
		});
		
		$('#soundplayer .player-controls .mute').live('click', function() {
			$(this).toggleClass('muted');
			$('#soundplayer .player-tracks ol li').each(function() {
				soundManager.toggleMute('track_' + $(this).data('track').id);
			});
		});
		
		$('#soundplayer .player-controls .control').live('click', function(e) {
			e.preventDefault();
		});
		
		$('#soundplayer .player-progress-container').live('click', function(event) {
			var $track = $('#soundplayer .player-tracks ol li.active'),
			data = $track.data('track'),
			playing = $track.is('.active');
			
			if (playing) {
				var mySMSound = soundManager.getSoundById('track_' + data.id);
				var relative = (event.pageX - $(this).offset().left) / $(this).width();
				soundManager.setPosition('track_' + data.id, mySMSound.duration * relative);	
//			} else {
//				lastTrack.click();
			}

		});

		// ## 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 ( $('#soundplayer .player-tracks ol li.active').next().find('a').click().length == 0 ) {
				$('#soundplayer .player-tracks ol li:first a').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 ( $('#soundplayer .player-tracks ol li.active').prev().find('a').click().length == 0 ) {
				$('#soundplayer .player-tracks ol li:last a').click();
			}
			
		};

	});
	
});

