$(function() {
	$('.column:last, .content p:last-child, .content ul:last-child').addClass('last');
	$('a[class=fancybox]').fancybox();
	
	$('#background').find('img').css({ width: ($(window).width()+10) + 'px' });
	
	$(window).resize(function() {
		$('#background').find('img').css({ width: ($(window).width()+10) + 'px' });
	});
	
	$('.clear').focus(function() {
		$(this).val('');
	});
	
	$('a[rel=external]').each(function() {
		$(this).attr('target', '_blank');
	});
	
	$('#youtube').each(function() {
		var params = { allowScriptAccess: "always" };
		var atts = { id: $(this).attr('id') };
		
		swfobject.embedSWF('http://www.youtube.com/apiplayer?version=3&enablejsapi=1&playerapiid=youtube', "youtube", "10", "10", "9", null, null, params, atts);
	});
	
	$('#previous').click(function() {
		if (ytplayer) {
			ytplayer.previousVideo();
		}
	});
	
	$('#play').click(function() {
		if (ytplayer) {
			ytplayer.playVideo();
		}
	});
	
	$('#pause').click(function() {
		if (ytplayer) {
			ytplayer.pauseVideo();
		}
	});
	
	$('#volume').click(function() {
		if (ytplayer) {
			ytplayer.mute();
		}
	});
});

function onYouTubePlayerReady(playerId) {
	videoid = 'Ym67EyQAGps';
	
	ytplayer = document.getElementById(playerId);
	ytplayer.addEventListener('onStateChange', 'onPlayerStateChange');
	ytplayer.cueVideoById(videoid, 0, 'medium');
	
	$.getJSON('https://gdata.youtube.com/feeds/api/videos/' + videoid + '?v=2&alt=json', function(data) {
		$('#name p').text(data.entry.title.$t);
	});
	
	setInterval(updatePlayerInfo, 100);
	updatePlayerInfo();
}

function onPlayerStateChange(newState) {
	if (newState == 1) {
		$('#pause').show();
		$('#play').hide();
	} else {
		$('#pause').hide();
		$('#play').show();
	}
}

function updatePlayerInfo() {
	if (ytplayer && ytplayer.getDuration) {
		/*
		updateHTML("videoDuration", ytplayer.getDuration());
		updateHTML("videoCurrentTime", ytplayer.getCurrentTime());
		updateHTML("bytesTotal", ytplayer.getVideoBytesTotal());
		updateHTML("startBytes", ytplayer.getVideoStartBytes());
		updateHTML("bytesLoaded", ytplayer.getVideoBytesLoaded());
		updateHTML("volume", ytplayer.getVolume());
		*/
		
		currentTime = ytplayer.getCurrentTime();
		totalTime = ytplayer.getDuration();
		
		time = updateTime(currentTime);
		time_left = '-' + updateTime(totalTime - currentTime);
		time_percentage = (currentTime / totalTime) * 100;
		
		$('#time').text(time);
		$('#time_left').text(time_left);
		$('#played').width(time_percentage + '%');
	}
}

function updateTime(time) {
	time = Math.round(time);
	
	if (time > 59) {
		minutes = Math.floor(time / 60);
		minutes_to_seconds = minutes * 60;
		seconds = time - minutes_to_seconds;
		minutes = minutes;
		
		return (minutes < 10 ? '0' + minutes : minutes) + ':' + (seconds < 10 ? '0' + seconds : seconds);
	} else {
		seconds = time;
		
		return '00:' + (seconds < 10 ? '0' + seconds : seconds);
	}
}
