// Author: Edd Hannay (@eddhannay)
// http://gingerninja.org/feedtheanimals/
// May 19th 2010

(function($) {
$.GirlTalk = {
	singleton : false,
	extension : "mp3",
	audioTagSupport : true,
	init: function(){
		this.audioTagSupport = !!(document.createElement('audio').canPlayType);
		if (this.audioTagSupport){
			// Basic  Audio support is present
				var audioTag = $('#audio');
				if (audioTag[0].canPlayType('audio/mp3')){
					// Hooray, we can play MP3s (Safari)
					this.extension = "mp3";
				} else {
					if (audioTag[0].canPlayType('audio/ogg')){
						// OGGs instead of MP3s (Firefox, Chrome)
						$('#c1').addClass('hide');
						this.extension = "ogg";
						$('#c2').removeClass('hide');
					} else {
						// Oh dear.
						$('#audio').remove();
					}
				}
				if (!audioTag[0].canPlayType('audio/mp4')){
					// Soundmanager2 is used to play m4a samples (Firefox, Chrome)
					$('#c3').removeClass('hide');
						window.soundManager = new SoundManager(); // Flash expects window.soundManager.
						soundManager.url = 'a/swf/';
						soundManager.flashVersion = 9;
						soundManager.useMovieStar = true;
						soundManager.beginDelayedInit(); // start SM2 init.
			}
			this.attachTracks();
		} else {
			// Nice little message for people without <audio />
			$('#mediaplayer').html('');
			$('#about').prepend($('<h1></h1>').html('Sorry').after($('<p></p>')
				.html('This page relies on the HTML5 Audio tag, which your browser is telling me it doesn&rsquo;t support. I know that Flash can get around that, and that Soundmanager2 is already included in the page, but I have to draw the line somewhere. It&rsquo;s just a silly tech demo after all. It would have looked a bit like this:'))
				.after($('<img />').attr('src','a/i/demo.jpg')).after($('<p></p>').html('Maybe you can come back with a nicer browser like <a href="http://www.apple.com/safari">Safari</a> or <a href="http://www.mozilla.org/firefox">Firefox</a> or <a href="http://chrome.google.com">Chrome</a> and have a go then?')));
			$('body').css('background-color','#efefef');
		}
		
		// Complain a bit
		if ($.browser.mozilla){
			$('#c4').removeClass('hide');
		}
	},
	
	attachTracks: function(){
		$('#songs a').each(function(i,t){
			$(t).click(function(){
				if ($('#songs').hasClass('playing')){
					/* Clear previous samples*/
					$('#samples li').each(function(){
						$(this).fadeOut();
					});

					// Colour song list appropriately
					$('#songs .current').removeClass('current');
					$(this).parent().addClass('current');

					// Kill old tag
					$('#audio').remove();
					$('#audiocontainer').append($('<audio></audio>').attr('id','audio').attr('src',$.GirlTalk.trackName($(this).attr('rel'))).attr('controls','true').attr('rel',$(this).attr('rel')));
					// Hacky: Firefox wasn't triggering canPlayThrough
					if ($.browser.mozilla){
						$.doTimeout( 100, $.GirlTalk.playMainAudio);
						if ($.GirlTalk.singleton == false){
							$.doTimeout( 1000, $.GirlTalk.getArtist);
							$.GirlTalk.singleton = true;
						}
					} else {
	 					$('audio')[0].addEventListener('canplaythrough',function(){
							// Start checking for samples, play the track ASAP
							if ($.GirlTalk.singleton == false){
								$.doTimeout( 1000, $.GirlTalk.getArtist);
								$.GirlTalk.singleton = true;
							}
							$.doTimeout( 1000, $.GirlTalk.playMainAudio);
						},false);
					}
					return false;
				}
			});
		});
	},
	
	// Turns a number in to a filename
	trackName: function(string){
		if (string.length==1){
			string = '0'+string;
		}
		return 'a/m/'+string+'.'+this.extension;
	},
	
	// Turns seconds (<audio />.status) in to hh:mm:ss (sample times)
	hms: function(seconds){
		minutes = Math.floor(seconds/60).toString();  // The minutes
		seconds = Math.round(seconds % 60).toString();              // The balance of seconds

		if (minutes.length==1){
			minutes='0'+minutes;
		}
		if (seconds.length==1){
			seconds='0'+seconds;
		}
		return "0:"+minutes+":"+seconds;
	},
	
	// Uses YQL to fetch Spotify's XML across domains
	getSpotify: function(artist,title,element){
		element.removeClass('loading');
		artist = artist.replace(/\s+/g,'+');
		title = title.replace(/\s+/g,'+');
		$.GirlTalk.requestCrossDomain('http://ws.spotify.com/search/1/track?q='+artist+'%20'+title, function(data) {
			data.replace(/<script[^>]*>[\s\S]*?<\/script>/g, '');
			var track = $(data).find('track');
			track = $(track[0]);
			if (track.length>0){
				var track = $('<a></a>').attr('class','spotify').attr('href',track.attr('href')).html($(track.find('name')[0]).text());
				$(track).click(function(){
					$('#audio')[0].pause();
				});
				element.append(track);
			}
	  });
	},
	
	// Pause any samples, play main audio
	playMainAudio: function(rel){
		$('#samples').removeClass('playing');
		$('#songs').addClass('playing');

		if (rel){
			if (soundManager){
				soundManager.pause(rel);
			} else {
				sampleAudio = $('#'+rel);
				sampleAudio[0].pause();
			}
		}
		$('#samples .playing').removeClass('playing');

		$('#audio')[0].play();
	},
	
	// Pause main audio, play samples
	playSample: function(rel){
		if ($('#songs').hasClass('playing')){
			$('#songs').removeClass('playing');
			$('#samples').addClass('playing');

			if (soundManager){
				soundManager.play(rel);
			} else {
				sampleAudio = $('#'+rel);
				sampleAudio[0].play();
			}
			$('#audio')[0].pause();
		}
	},

	// Search for artist on iTunes when their sample starts
	getArtist: function(){
			timestamp = $.GirlTalk.hms($('#audio')[0].currentTime);
			var trackNo = $('#audio').attr('rel');
				// yes, this is looping through the array every second
				$(tracks[trackNo-1].samples).each(function(i,t){
					if (t.start == timestamp){
						$('#samples').prepend($('<li />').attr('id','sample'+i).attr('class','loading').append(timestamp+": "+t.artist+"-"+t.title ));

						$.getJSON(
						  'http://ax.phobos.apple.com.edgesuite.net/WebObjects/MZStoreServices.woa/wa/wsSearch?term='+t.artist+'+'+t.title+'&limit=1&callback=?',
						  function(data) {
								if (data.resultCount==1){
									r = data.results[0];
									$('#sample'+i).attr('class','');
									$('#sample'+i).html($('<img />').attr('src',r.artworkUrl100).attr('width','100').attr('height','100'));
									$('#sample'+i).append('<a href="'+r.artistViewUrl+'">'+r.artistName+'</a> - '+r.trackName+'<br />From: <a href="'+r.collectionViewUrl+'">'+r.collectionName+'</a>');

									if ($('audio')[0].canPlayType('audio/mp4')){
										// Write an audio tag for nice browsers (Safari)
										$('#sample'+i).append($('<audio />').attr('src',r.previewUrl).attr('id','audio'+trackNo+'-'+i).attr('controls','false'));
										canPlaySample = true;
									} else {
										// Create a soundManager object for the rest (Firefox, Chrome)
										if (soundManager.canPlayURL(r.previewUrl)) {
											var mySound = soundManager.createSound({
											    id: 'audio'+trackNo+'-'+i,
													autoLoad: 'true',
											    url: r.previewUrl,
													onfinish: function(){
														playMainAudio('audio'+trackNo+'-'+i);
													},
													whileloading: function(){
														$('#audio'+trackNo+'-'+i+'playpause').html('Loading clip')
													},
													onload: function(){
														$('#audio'+trackNo+'-'+i+'playpause').html('Play clip')
													}
												
											  });
												canPlaySample = true;
											} else {
												canPlaySample = false;
												console.log("Boourns");
											}
									}
								
									// Write in Play/Pause button, assuming the sample will work
									if (canPlaySample){
										$('#sample'+i).append($('<a>').attr('class','playpause').attr('rel','audio'+trackNo+'-'+i+'playpause').attr('rel','audio'+trackNo+'-'+i).html('Play clip').click(function(){
											if ($(this).parents('li').hasClass('playing')){
												$.GirlTalk.playMainAudio($(this).attr('rel'));
												$(this).html('Play clip');
											} else {
												$.GirlTalk.playSample($(this).attr('rel'));
												$(this).parents('li').addClass('playing');
												$(this).html('Pause clip');
											}
										}));
									}
								}
								$.GirlTalk.getSpotify(t.artist,t.title,$('#sample'+i));
						  }
						);
						tracks[trackNo-1].samples[i] = '';
				
					}
				
			});
		
		return true;
	},
	
	// Fetch XML across domains
	//http://net.tutsplus.com/articles/news/learn-how-to-create-a-jquery-plugin/
	requestCrossDomain: function( site, callback ) {

		// If no url was passed, exit.
		if ( !site ) {
			alert('No site was passed.');
			return false;
		}

		// Take the provided url, and add it to a YQL query. Make sure you encode it!
		var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from xml where url="' + site + '"') + '&format=xml&callback=?';

		// Request that YSQL string, and run a callback function.
		$.getJSON(yql, function(data) {
			// If we have something to work with...
			if ( data.results[0] ) {
				// Strip out all script tags, for security reasons.
				// BE VERY CAREFUL. This helps, but we should do more.
				data = data.results[0].replace(/<script[^>]*>[\s\S]*?<\/script>/g, '');

				// If the user passed a callback, and it
				// is a function, call it, and send through the data var.
				if ( typeof callback === 'function') {
					callback(data);
				}
			}
		});

	}
	
}})(jQuery);

$(document).ready(function(){
	$.GirlTalk.init();
});
SM2_DEFER = true;									// Prevents SoundManager loading until we know we need it

