if ($('video-container')){
	var username  = 'manchesternews';	// default user
	var myDefault = 'zqHijc3Qa_U';	// default video to display
	var urlOverride = window.location.href.toQueryParams().v || null;	// override first video with ?v=videoId
	var myytplayer = '';
	
	var script;
	var itemsPerPage;
	var startIndex;
	var totalResults;
	var videoInfo = new Array();
	
	var maxResults = '50';
	
	$('video-loading').update('<p>Loading video player content, please wait&hellip;</p>');

	// check to see if any of the default values exist in HTML otherwise set to null
	var ytDefault  = ($('yt-default')) ? $('yt-default').innerHTML : myDefault;
	if (urlOverride) ytDefault = urlOverride;
	var ytPlaylist = ($('yt-playlist')) ? $('yt-playlist').innerHTML : null;
	var ytKeywords = ($('yt-keywords')) ? $('yt-keywords').innerHTML : null;
	var ytAutoplay = ($('yt-autoplay')) ? $('yt-autoplay').innerHTML : null;
	var playlistonly = ($('yt-playlistonly')) ? $('yt-playlistonly').innerHTML : null;
	var videolink = ($('yt-videolink')) ? $('yt-videolink').innerHTML : null;

	// insert HTML placeholders for video content
	Element.insert('video-loading', {after: '<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')) ? $('yt-width').innerHTML : 400;
	var ytHeight   = ($('yt-height')) ? $('yt-height').innerHTML : 300;
	// colouring video chrome requires 2 hash values seperated by a comma
	var ytColours  = '';
	if ($('yt-colours')){
		var colorHex = $('yt-colours').innerHTML.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=myytplayer&showsearch=0&fs=1&hd=1' + ytColours + ytAutoPlay,
		"ytapiplayer", ytWidth, ytHeight, requiredFlashVer, null, null, params, atts
	);

	if (playerVersion.major < requiredFlashVer) $('video-loading').update(
		'<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) {
	myytplayer = document.getElementById("myytplayer");
	$('video-loading').remove();	// remove loading cover
	myytplayer.addEventListener("onError", "onPlayerError");
	myytplayer.addEventListener("onStateChange", "onytplayerStateChange");
}

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 html = [];
		
		if(!playlistonly) {
			html = ['<ol>']; 
		}
		
		var section_counter = 1;
		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;
			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
			};
			
			if(playlistonly){
				var index = i+1;
				if(index % 2) {
					html.push('<div id="section' + section_counter + '" class="section">');
					section_counter++;
				}
				
				link = videolink + "?v=" + link.toQueryParams()['v'];
				
				html.push(
					'<div class="job"><div class="imageunit"><a href="' + link + '">' + thumbnail + '</a><img class="play" width="33" height="12" alt="" src="hm/img/play.png"/></div>' +
					'<h3><a href="' + link + '">' + title + '</a></h3>' + 
					'<div class="description">' + description + '</div><br style="clear: both;"/></div>'
				);
				if(i % 2) html.push('</div>');
			}
			else{
				html.push(
					'<li><a href="' + link + '" id="video_' + videoID + '">' +
					'<span class="thumb">' + thumbnail + '<span class="duration">' + duration + '</span>' + '<span class="vid-control"></span></span>' +
					'<span class="title">' + title + '</span>' +
					'<span class="desc">' + description + '</span><div class="clear"/></div></a></li>'
				);
			}
		}
		if(!playlistonly) {
			html.push('</ol>');
		}

		if (!$('playlist')){
			// if the playlist does not already exist, then build one
			Element.insert('video-content', {after: '<div id="playlist"></div><div id="pager"></div>'});
			$('video-container').removeClassName('single');
		}		
		
		if(playlistonly) {
			$('scroller-content').innerHTML = html.join('');
		}
		else{
			$('playlist').innerHTML = html.join('');
		}
		
		if ($('pager')){	// 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').update(
				'Videos: ' + startIndex + '&ndash;' + paginationNum + '<span>' + pageHtml + '</span>'
			);

			$$('a.pager-link').each(function(link) {
				// link events for the pager links
				Event.observe(link, 'click', function(e) {
					var clickedLink = $(Event.findElement(e, 'A'));
					script = document.createElement('script');
					script.setAttribute('src', clickedLink.href);
					if(startIndex) document.body.appendChild(script);
					Event.stop(e);
				});
			});
		}

		// 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);

		$$('div#playlist ol li a').each(function(link) {
			// controls for playing or pausing a video from the playlist
			Event.observe(link, 'click', function(e) {
				var clickedLink = $(Event.findElement(e, 'A'));
				if (clickedLink.hasClassName('playing')){
					clickedLink.removeClassName('playing');
					clickedLink.addClassName('paused');
					pauseVideo();
				} else if (clickedLink.hasClassName('paused')){
					clickedLink.removeClassName('paused');
					clickedLink.addClassName('playing');
					playVideo();
				} else {
					$$('div#playlist ol li a.playing, div#playlist ol li a.paused').each(function(link) {
						link.className = '';
					});
					clickedLink.addClassName('playing');
					var videoID = clickedLink.id.split('video_')[1];
					loadNewVideo(videoID, 0);
				}
				Event.stop(e);
			});
		});
	} else if (urlOverride){
		loadSwfPlayer(urlOverride);
	} else {
		// if no videos exist then let the user search for some videos
		$('video-loading').setStyle({ backgroundImage: 'none' });
		$('video-loading').update(
				'<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>'
		);
		Event.observe('video-search', 'submit', function(e){
			getVideoData(null, $('video-search-query').value, null, 1);
			Event.stop(e);
		});
	}
}
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,
		"seconds" : seconds,
		"duration" : duration
	};

	// display a single video on its own only
	if (myytplayer) {
		loadNewVideo(myDefault, 0);
	} else {
		loadSwfPlayer(myDefault);
	}
	$('video-container').addClassName('single');
}

function loadNewVideo(id, startSeconds) {
	if (myytplayer) {
		myytplayer.loadVideoById(id, parseInt(startSeconds));
	}
}
function playVideo(){
	if (myytplayer) {
		myytplayer.playVideo();
	}
}
function pauseVideo(){
	if (myytplayer) {
		myytplayer.pauseVideo();
	}
}
function onPlayerError(errorCode) {
	alert("An error occured: " + errorCode);
}
function onytplayerStateChange(newState) {
	om.youTubeStateChange(myytplayer, 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;
};
Event.observe(window, 'load', function(){
	document.body.appendChild(script);
});
