﻿$(function() {
	function getVideoID(link) {
		var id = link.substring(link.indexOf('watch?v=') + 8);
		if(link.indexOf('#') > -1){
			id = id.substring(0, id.indexOf('#'));
		}
		return id;
	}

	function getVideoStart(link) {
		if(link.indexOf('#t=') > -1){
			var start = link.substring(link.indexOf('#t=') + 3);
			start = start.replace(/(\d+)s/, ' + $1').replace('m', ' * 60');

			return eval(start);
		}else{
			return 0;
		}
	}

	function getVideoHTML(link) {
		var videoUrl = 'http://www.youtube.com/embed/' + getVideoID(link) + '?autoplay=1';
		var videoStart = getVideoStart(link);
		if(videoStart > 0){
			videoUrl += '&start=' + videoStart;
		}

		return '<iframe id="video-embed" src="' + videoUrl + '" width="480" height="360"/>';
	}

	$('body').append('<div class="modal" id="video-modal"><div id="video-container"></div></div>');
	var overlay = $('#video-modal').overlay({
		mask: {
			color: '#0d0d0d',
			loadSpeed: 500,
			opacity: 0.9
		},
		closeOnClick: true,
		api: true,
		fixed: false,
		top: '30%',
		left: '35%',
		onClose: function(){
			$('#video-container').html('');
		},
		onLoad: function(){
			this.getOverlay().trigger('load');
		}
	});

	$('a[href^="http://www.youtube.com"]')
	.unbind('click')
	.addClass('yt-video')
	.click(function(){
		var link = $(this);
		var href = link.attr('href');

		$('#video-container').hide().html(getVideoHTML(href));

		overlay.load().getOverlay().bind('load', function(){
			$('#video-container').fadeIn();

			var trackTitle = link.text() + ' (' + href + ')';
			if(typeof _gaq != 'undefined'){_gaq.push(['_trackEvent', 'Day track', 'Play', trackTitle])};
			if(typeof yaCounter != 'undefined'){yaCounter.hit(href, trackTitle, document.URL)};
		});

		return false;
	});
});
