﻿var player; 

function onYouTubePlayerReady(playerId) {

	// youtube player
    player = document.getElementById('myplayer');
    player.addEventListener('onStateChange', 'onPlayerStateChange');
	player.userEnded = false;
	player.currentVideoID = undefined;
	player.playvideo = function() {
		if(player.currentVideoID == undefined)
			player.currentVideoID = $('#tracks li:first').attr('id');
		
		$('#tracks li').removeClass('selected').find('span').remove();
		$('#' + player.currentVideoID).addClass('selected');
		player.loadVideoById(player.currentVideoID, 0);
		
		player.userEnded = false; // reset
		$('#loading').fadeOut('slow');
	};
	player.updateRemaining = function () { 
		var mins = Math.floor((player.getDuration() - player.getCurrentTime()) / 60);
		var secs = Math.floor((player.getDuration() - player.getCurrentTime()) % 60);
		secs = ('00' + secs).slice(-2); // leading zero
		$('#' + player.currentVideoID).find('span').remove();
		$('#' + player.currentVideoID).append('<span>'+ mins + ':' + secs + '</span>');
	};
	
	setInterval(player.updateRemaining, 1000);

    // wire up controls
    $('#previous').click(function() { player.userEnded = true; player.currentVideoID = $('#' + player.currentVideoID).prev().attr('id'); player.playvideo(); return false; });
    $('#back').click(function() { player.seekTo(player.getCurrentTime() - 30, true); return false; });
    $('#play').click(function() { player.userEnded = true; player.currentVideoID = player.currentVideoID; player.playvideo(); return false; });
    $('#stop').click(function() { player.userEnded = true; player.stopVideo(); return false; });
    $('#forward').click(function() { player.seekTo(player.getCurrentTime() + 30, true); return false; });
    $('#next').click(function() { player.userEnded = true; player.currentVideoID = $('#' + player.currentVideoID).next().attr('id'); player.playvideo(); return false; });
	
	// go go go!
	$.ajax({
		url: 'http://query.yahooapis.com/v1/public/yql?q=USE%20%22http%3A%2F%2Faddbass.com%2Fyoutube.xml?2%22%20AS%20vids%3B%20SELECT%20id%2C%20title%20FROM%20vids%20WHERE%20orderby%3D%22' + (location.search == '?relevance' ? 'relevance' : 'viewCount') + '%22%20AND%20q%20IN%20(SELECT%20alt%20FROM%20html%20WHERE%20%0Aurl%3D%22http%3A%2F%2Fwww.bbc.co.uk%2Fradio1%2Fchart%2Fsingles%2F%22%20and%20xpath%3D%22%2F%2Fli%2Fimg%22%20LIMIT%2020)%20%7C%20sanitize()&format=json&diagnostics=false&_maxage=86400',
		cache: true,
		dataType: 'jsonp',
		jsonp: 'callback',
		jsonpCallback: 'yqlSuccess',
		success: function(data, text, request) { yqlSuccess(data); },
		error: function(request,status,errorThown) { alert('doooom!'); yqlFail(status);}
	});
	
	function yqlFail(status) {
		$('#loading').addClass('fail').html('Oh noes! ' + status );
	}
	
	function yqlSuccess(data) {
	
		$('#tracks').empty();
	
		$.each(data.query.results.entry, function(i,item){
			var id = item.id.replace('http://gdata.youtube.com/feeds/api/videos/','');
			var title = item.title.content.indexOf(" - ") == -1 ? '<b>' + item.title.content + '</b>' : '<b>' + item.title.content.substring(0,item.title.content.indexOf(" - ")) + '</b> '+ item.title.content.substring(item.title.content.indexOf(" - "));
			var $li = $('<li id="' + id + '" ><a title="Play ' + item.title.content + '" href="http://www.youtube.com/watch#!v=' + id + '">' + title + ' </li></a>');
            $li.click(function() { player.userEnded = true; player.currentVideoID = this.id; player.playvideo(); return false; });
            $('#tracks').append($li);
		});
		
		player.playvideo();
	}
};

function onPlayerStateChange(newState) {

    if (newState == 0 && !player.userEnded) { // track finished
		player.currentVideoID = $('#' + player.currentVideoID).next().attr('id');
		player.playvideo();
	}
};