// Youtube API controls.
var ytplayer;
var state;

function playVideo(video,num){
	if (ytplayer)
	ytplayer.loadVideoById(video,num);
}

function onYouTubePlayerReady(playerId) {
    ytplayer = document.getElementById('myytplayer');
    // setInterval(updateytplayerInfo, 250);
    //    	updateytplayerInfo();
    ytplayer.addEventListener('onStateChange', 'onytplayerStateChange');
	//playVideo('Ia8V__LmvAE', 0); //the default band video

	playVideo(video, 0);
	// Un mute the player just inc.
	$('a#play').css('background-position','0 -20px');
	setInterval(updater, 250);
	updater();
	
	ytplayer.unMute();
}

// Rob's updater function
function updater(){
	if (state == 1) {
		updateytplayerInfo();
	} 
}

function onytplayerStateChange(newState) {
     setytplayerState(newState);
}

function updateytplayerInfo() {
    if (ytplayer) {
        updateTimebar();
		updateBufferbar();
    }
}

function updateTimebar() {
    var all = ytplayer.getDuration();
    var part = ytplayer.getCurrentTime();
    var percent = getPercent(all, part);
	var timebarWidth = parseInt($('#timebar').css('width'));
    document.getElementById('timebarIndicator').style.width = percent * (timebarWidth / 100) + "px";
}

function getPercent(all, part) {
   return (all > 0) ? (100 / all) * part : 0;
}

function updateBufferbar() {
    var all = ytplayer.getVideoBytesTotal();
    var part = ytplayer.getVideoBytesLoaded();
    var percent = getPercent(all, part);
    var bufferbarWidth = parseInt($('#timebar').css('width'));
    document.getElementById('bufferbarIndicator').style.width = percent * (bufferbarWidth / 100) + "px";
}

$(function(){
  	// Document is ready
	// Load the youtube player
	var params = { allowScriptAccess: "always", bgcolor: "#ffffff" };
	var atts = { id: "myytplayer" };
	swfobject.embedSWF("http://www.youtube.com/apiplayer?enablejsapi=1&playerapiid=ytplayer","ytapiplayer", "495", "280", "8", null, null, params, atts);

	$('.unmute').hide();

	// Mute function for youtube.
	$('.mute').click(function(){
		$(this).hide();
		$('.unmute').show();
		ytplayer.mute();
		return false;
	});

	$('.unmute').click(function(){
		$(this).hide();
		$('.mute').show();
		ytplayer.unMute();
		return false;
	});

	$('.youtube_link').click(function(){
		video = $(this).attr('rel');
		playVideo(video,0);
		$('a#play').html('Pause');
		return false;
	});


	$('a#play').click(function() { playPause(); return false; });
	$('#col-videos').click(function() { playPause(); return false; });

	function playPause(){
		
		var playPauseText = '';
		
		switch(ytplayer.getPlayerState()) {
			case 2:
				$('a#play').css('background-position','0 -20px');
				playPauseText = "Pause";
				ytplayer.playVideo();
				break;
			default:
			$('a#play').css('background-position','0 0');
				playPauseText = "Play";
				ytplayer.pauseVideo();
				break;
		}
		
		$('a#play').html(playPauseText);
	}

});