if ($('#video-container')[0]){
	var username  = 'manchesternews';	// default user
	var myDefault = 'zqHijc3Qa_U';	// default video to display
	var	urlOverride = window.location.href.getQueryParam('v') || null;	// override first video with ?v=videoId
	
	var script;
	var ytplayer;
	var itemsPerPage;
	var startIndex;
	var totalResults;
	var videoInfo = new Array();

	var maxResults = '3';

	$('#video-loading').html('<p>Loading</p>');

	// check to see if any of the default values exist in HTML otherwise set to null
	var ytDefault  = ($('#yt-default')[0]) ? $('#yt-default').html() : myDefault;
	if (urlOverride) ytDefault = urlOverride;
	var ytPlaylist = ($('#yt-playlist')[0]) ? $('#yt-playlist').html() : null;
	var ytKeywords = ($('#yt-keywords')[0]) ? $('#yt-keywords').html() : null;
	var ytAutoplay = ($('#yt-autoplay')[0]) ? $('#yt-autoplay').html() : null;

	// insert HTML placeholders for video content
	$('#video-container').append('<div id="video-content"><div id="ytapiplayer"></div></div>');

	getVideoData(ytPlaylist, ytKeywords, ytDefault);
}

function loadSwfPlayer(ytDefault){
	// width & height of video is set via HTML or loads default value
	var ytWidth    = ($('#yt-width')[0]) ? $('#yt-width').html() : 300;
	var ytHeight   = ($('#yt-height')[0]) ? $('#yt-height').html() : 250;
	// colouring video chrome requires 2 hash values seperated by a comma
	var ytColours  = '';
	if ($('#yt-colours')[0]){
		var colorHex = $('#yt-colours').html().split(',');
		ytColours = '&color1=0x' + colorHex[0] + '&color2=0x' + colorHex[1];
	}
	// auto play video if its a single video or loaded via URL

	var ytAutoPlay = ((!ytPlaylist) && (!ytKeywords) && (!ytAutoplay) || (urlOverride)) ? '&autoplay=1' : '';
	var requiredFlashVer = '8';
	var playerVersion = swfobject.getFlashPlayerVersion();

	var params = { allowScriptAccess: 'always', bgcolor: '#cccccc', wmode: 'opaque' };
	var atts = { id: 'myytplayer', allowfullscreen: 'true' };
	swfobject.embedSWF(
		'http://www.youtube.com/v/' + ytDefault +
		'&enablejsapi=1&playerapiid=ytplayer&showsearch=0&rel=0&fs=1&hd=1' + ytColours + ytAutoPlay,
		"ytapiplayer", ytWidth, ytHeight, requiredFlashVer, null, null, params, atts
	);

	if (playerVersion.major < requiredFlashVer) $('#video-loading').html(
		'<p>Sorry! This video requires Flash ' + requiredFlashVer + ' to play, update your version of Flash by <a href="http://get.adobe.com/flashplayer/" target="_blank">clicking here</a>.</p>'
	);
}

function onYouTubePlayerReady(playerId) {
	ytplayer = document.getElementById("myytplayer");
	ytplayer.addEventListener("onError", "onPlayerError");
	ytplayer.addEventListener("onStateChange", "onytplayerStateChange");
	$('#video-loading').remove();	// remove loading cover
}

function getVideoData(ytPlaylist, ytKeywords, ytDefault, startIndex){
	var url = '';
	var alt = 'json-in-script'; // can be set to the following atom, rss, json and json-in-script
	var start = (startIndex) ? startIndex : 1;

	myPlaylist = ytPlaylist;	// set myPlaylist for loading playlists on the fly
	myKeywords = ytKeywords;	// set myKeywords for loading playlists on the fly
	myDefault  = ytDefault;		// set myKeywords for loading playlists on the fly

	if (myKeywords){
		// if keywords have been supplied - do a search for those keywords on all uploads by defined user
		var splitKeywords = myKeywords.split(/,\s+|,/);
		var query = '&q=';

		for (var i = 0; i < splitKeywords.length; i++){
			// break each search term up adding quotes around each term & seperated by an OR (|)
			query += '"' + splitKeywords[i] + '"';
			if (i < (splitKeywords.length - 1)) query += '|';
		}

		url = 'http://gdata.youtube.com/feeds/api/users/' +  username + '/uploads' +
					'?v=2&alt=' + alt + '&format=5&callback=buildPlaylist&orderby=published&start-index=' + start + '&max-results=' + maxResults + query;
	} else if (myPlaylist) {
		// display all videoes from a supplied playlist ID
		url = 'http://gdata.youtube.com/feeds/api/playlists/' + myPlaylist +
					'?v2&alt=' + alt + '&format=5&callback=buildPlaylist&start-index=' + start + '&max-results=' + maxResults;
	} else {
		url = 'http://gdata.youtube.com/feeds/api/users/' +  username + '/uploads/' + myDefault +
					'?v2&alt=' + alt + '&format=5&callback=singleVideoData';
	}
	//console.log(url);
	script = document.createElement('script');
	script.setAttribute('src', url);
	if(startIndex) document.body.appendChild(script);
}
function buildPlaylist(data) {
	var feed = data.feed;
	var entries = feed.entry || [];
	var returnedResults = entries.length;
	//console.log(feed);

	if(returnedResults != 0){
		var myHtml = '<ol>\n';

		for (var i = 0; i < returnedResults; i++) {
			//console.log(entries[i]);
			var entry = entries[i];
			var title = entry.title.$t;
			var link  = entry.media$group.media$player.url || entry.media$group.media$player[0].url;
			var videoID = (ytKeywords) ? entry.media$group.yt$videoid.$t : entry.media$group.media$player[0].url.split('?v=')[1].truncate(11, '');
			var description = entry.media$group.media$description.$t.split(' ... ')[0].truncate(40, '...');
			var seconds = entry.media$group.yt$duration.seconds;
			var duration = Math.floor(seconds / 60) + ':' + (seconds % 60).toFixed().pad(2, '0');
			var thumbnail = '<img src="' + entry.media$group.media$thumbnail[0].url + '" alt="" class="yt-thumb" />';

			videoInfo[videoID] = {
				"title" : title,
				"link"  : link,
				"description" : description,
				"seconds" : seconds,
				"duration" : duration
			};

			myHtml +=
				'<li class="you_made_it"><a href="' + link + '" id="video_' + videoID + '">\n' +
				'<span class="thumb">' + thumbnail + '<span class="duration">' + duration + '</span>' + '<span class="vid-control"></span></span>\n' +
				'<span class="title">' + title + '</span>\n' +
				'<span class="desc">' + description + '</span></a></li>\n';
		}
		myHtml += '</ol>\n';
		
		if (!$('#playlist')[0]){
			// if the playlist does not already exist, then build one
			$('#video-container').append('<div id="playlist"></div><div id="pager"></div>');
			$('#video-container').removeClass('single');
		}

		$('#playlist').html(myHtml);

		if ($('#pager')[0]){	// if paging exists for playlist
			// get pagination data
			startIndex   = feed.openSearch$startIndex.$t;
			totalResults = feed.openSearch$totalResults.$t;

			var pageHtml = '';

			if (totalResults > maxResults){
				// don't show previous / next links if all results fit on one pages
				/*
				feed.link.each(function(link){
					if ((link.rel == 'next') || (link.rel == 'previous')){
						var linkTxt = (link.rel == 'next') ? 'Next' : 'Previous';
						pageHtml += '<a href="' + link.href + '&callback=buildPlaylist" class="pager-link">' + linkTxt + '</a>';
						if ((link.rel == 'previous') && (feed.link.last().rel != 'previous')) pageHtml += ' | ';
					}
				});
				*/
			}

			var paginationNum = returnedResults;
			if (startIndex > 1) paginationNum = startIndex + (returnedResults - 1);

			$('#pager').html(
				'Videos: ' + startIndex + '&ndash;' + paginationNum + '<span>' + pageHtml + '</span>'
			);

			$('a.pager-link').each(function(link) {
				// link events for the pager links
				link.click(function() {
					script = document.createElement('script');
					script.setAttribute('src', this.href);
					if(startIndex) document.body.appendChild(script);
					return false;
				});
			});
		}

		// find the video that is at the top of a playlist and display that first
		latestVideo = (ytKeywords) ? entries[0].media$group.yt$videoid.$t : entries[0].media$group.media$player[0].url.split('?v=')[1];
		if (urlOverride) latestVideo = urlOverride;
		loadSwfPlayer(latestVideo);

		var playListItem = $('div#playlist ol li a');
		
		$('div#playlist ol li a').each(function() {
			// controls for playing or pausing a video from the playlist
			var video = $(this);
			
			video.click(function(e) {
				link = $(e.target).closest('a');
				if (link.hasClass('playing')){
					link.removeClass('playing');
					link.addClass('paused');
					pauseVideo();
				} else if (link.hasClass('paused')){
					link.removeClass('paused');
					link.addClass('playing');
					playVideo();
				} else {
					$('div#playlist ol li a.playing, div#playlist ol li a.paused').each(function() {
						$(this).removeAttr('class');
					});
					link.addClass('playing');
					var videoID = link.attr('id').split('video_')[1];
					loadNewVideo(videoID, 0);
				}
				return false;
			});
		});
	} else if (urlOverride){
		loadSwfPlayer(urlOverride);
	} else {
		// if no videos exist then let the user search for some videos
		$('#video-loading').css({ backgroundImage: 'none' });
		$('#video-loading').html(
				'<p>No videos are available for this section, if you wish to watch a video from the MEN Media archives please enter a search term below.</p>' +
				'<form id="video-search" action=""><input type="text" class="video-search-txt" id="video-search-query" /><input type="submit" value="search" /></form>'
		);
		$('#video-search').submit(function() {
			getVideoData(null, $('#video-search-query').val(), null, 1);
			return false;
		});
	}
}
function singleVideoData(data){
	var feed = data.entry;
	var seconds = feed.media$group.yt$duration.seconds;
	var duration = Math.floor(seconds / 60) + ':' + (seconds % 60).toFixed().pad(2, '0');

	videoInfo[myDefault] = {
		"title" : feed.title.$t,
		"link"  : feed.link[0].href,
		"description" : feed.media$group.media$description.$t.split(' ... ')[0],
		"seconds" : seconds,
		"duration" : duration
	};

	// display a single video on its own only
	(ytplayer) ? loadNewVideo(myDefault, 0) : loadSwfPlayer(myDefault);
	$('#video-container').addClass('single');
}

function loadNewVideo(id, startSeconds) {
	if (ytplayer) {
		ytplayer.loadVideoById(id, parseInt(startSeconds));
	}
}
function playVideo(){
	if (ytplayer) {
		ytplayer.playVideo();
	}
}
function pauseVideo(){
	if (ytplayer) {
		ytplayer.pauseVideo();
	}
}
function onPlayerError(errorCode) {
	if (errorCode == 100){
		alert('Error ' + errorCode + ': The video requested is not available, it has been removed, or marked as private.');
	} else {
		alert('Error ' + errorCode + ': The video requested does not allow playback in the embedded player.');
	}
}
function onytplayerStateChange(newState) {
	//console.log("Player's new state: " + newState);
    om.youTubeStateChange(ytplayer, newState);
}

function getVideoId(currentPlayer) {
    var url = currentPlayer.getVideoUrl();
    url.match(/\?(.+)$/);
    var params = RegExp.$1;
    params = params.split("&");
    for(var i=0;i<params.length;i++) {
        var tmp = params[i].split("=");
        if(tmp[0] == 'v')
            return tmp[1];
    }
    return myDefault;
}



String.prototype.pad = function(l, s){
	return (l -= this.length) > 0
		? (s = new Array(Math.ceil(l / s.length) + 1).join(s)).substr(0, s.length) + this + s.substr(0, l - s.length)
		: this;
};

document.body.appendChild(script);
