function initLiveNewsIcon(f) {
	www.getServerTime(function(serverTime) {
		var current_minute = parseInt(serverTime.hours, 10) * 60 + parseInt(serverTime.minutes, 10);
		if (serverTime.dayText == "Saturday" || serverTime.dayText == "Sunday") {
			$(liveStreamDB.weekends).each(function(i) {
				if (this.day.toLowerCase() == "both" || serverTime.dayText.toLowerCase() == this.day.toLowerCase()){
					var start_time = (parseInt(this.start_hour, 10)) * 60 + parseInt(this.start_minute, 10);
					var end_time = (parseInt(this.end_hour, 10)) * 60 + parseInt(this.end_minute, 10);
					if ((current_minute  >= start_time) && (current_minute  < end_time)) {
						f({liveStream:this});
					}
				}
			});
		} else {
			$(liveStreamDB.weekdays).each(function(i) {
				var start_time = (parseInt(this.start_hour, 10)) * 60 + parseInt(this.start_minute, 10);
				var end_time = (parseInt(this.end_hour, 10)) * 60 + parseInt(this.end_minute, 10);
				if ((current_minute  >= start_time) && (current_minute  < end_time)) {
					f({liveStream:this});
				}
			});
		}
	});
}

var tabCookie = "tab";
var catCookie = "cat";
var playCookie = "play";
var pageCookie = "page";
var cookieTime = 15/24/60;

var videoTabUrl = www.readCookie(tabCookie);
var videoCatUrl = www.readCookie(catCookie);
var videoPlayUrl = www.readCookie(playCookie);
var videoPage = www.readCookie(pageCookie);

$(function () {
	if(location.href.indexOf('/national-news/one-news-minute-informed-quickly-video-1664522') > 0)
		// if this is news in a minute, set some overrides
		www.createCookie(catPlayCookie, '/content/video_home_nz_news_video_group/ta_news_video_home_module_skin.xinc', cookieTime);
	
	// default to the first tab (and no cat)
	if (!videoTabUrl) 
		videoTabUrl = $("#contentBtm .nav li a").first().attr("href");
	
	// default play tab to the first tab (and as it happens the first cat too)
	if (!videoPlayUrl)
		videoPlayUrl = $("#contentBtm .nav li a").first().attr("href");
	
	// default to page 1
	if (!videoPage) videoPage = 1;
	
	var href = location.href.indexOf('/news-video') >= 0 ? null : location.href;

	/*
	 * Set up the tabs to load their tab content when clicked. Remember the tab
	 * in the cookie. Clear the cat and page cookies.
	 */
	$("#contentBtm .nav li a").live('click', function(event) {
		event.stopPropagation();
		event.preventDefault();
		videoTabUrl = $(this).attr("href");
		videoCatUrl	= null;
		videoPage = 1;
		loadTabAndCat();
		return false;
	});
	/*
	 * Set up the cats to load their tab content when clicked. Remember the tab
	 * and the cat in the cookies. Clear the page cookie.
	 */
	$("#menu li a").live('click', function(event) {
		event.stopPropagation();
		event.preventDefault();
		videoTabUrl = $("#contentBtm .nav li a.selected").attr("href");
		videoCatUrl	= $(this).attr("href");
		videoPage = 1;
		loadTabAndCat();
		return false;
	});	
	
	/*
	 * Set up the actual video in the tab content. Remember the tab and cat that
	 * the video was played/clicked on. Media items should open a new window to
	 * the ondemand page. TODO should the page be remembered too?
	 */
	$(".videoItem a").live('click', function(event) {
		www.createCookie(playCookie, $("#menu li a.selected").attr("href"), cookieTime);
		if ($(this).parents().hasClass("media")) {
			event.preventDefault();
			event.stopPropagation();
			window.open($(this).attr("href"));
			return false;
		}
	});
	
	/*
	 * Set up the page links
	 */
	$("#videoSelect .pagination li a").live('click', function(event) {
		event.preventDefault();
		event.stopPropagation();
		if ($(this).parent().hasClass('prev')) 
			$("#videoSelect").trigger('pagePrev');
		else if ($(this).parent().hasClass('next')) 
			$("#videoSelect").trigger('pageNext');
		else 
			$("#videoSelect").trigger('page', {page:$(this).text()});
		return false;
	});
	
	/*
	 * Update the live stream tab's icon. Animate the icon if there is a live
	 * stream currently available. 
	 */
	var liveStream = null;
	initLiveNewsIcon(function (data) {
		liveStream = data.liveStream;
		$("#contentBtm").trigger('liveStream');
	});
	
	$("#contentBtm").live('liveStream', function (event) {
		if (liveStream) $("#liveStreams", this).css("background-image", "url('http://images.tvnz.co.nz/tvnz_site_images/images/newsvideo_live_streams_animation.gif')");
		$(".videoItem", this).updateLive(liveStream);
	}).live('nowPlaying', function (event, data) {
		$("#videoSelect .videoItem", this).updateNowPlaying(data);
	});
	
	$("#upNext").live('nowPlaying', function (event, data) {
		// remove the up next if this is a live stream 
		// or if the current tab is livestream and there is no play cat 
		// or if the livestream tab is the play cat
		if ($("#liveStreams").attr('href').indexOf(videoPlayUrl) >= 0) {
			$("#upNext").hide(500);
		} else {
			// re-show up next if it's been hidden
			$("#upNext:hidden").show(500);
			// get the next three items
			// TODO the bc player doesn't have 'items' to pass, so how do we do it? 
			// TODO we could pass them in from bc
			var upNext = data.items.filterNowPlaying(data).nextAll('.video').slice(0,3);
			// replace the current list with them
			upNext.find(".videoInfo a").clone().replaceAll("#upNext ul").wrapAll("<ul/>").wrap("<li/>");
			// grab the first one'd ID to return to the BC player
			upNext.first().each(function () {
				var nextId = $(this).attr('id').substr(7);
				var nextUrl = $(this).attr('href');
				// register the new content id for the BC player
				window.brightcoveCountdownCallback = function (id) {
					return nextId;
				};
				// register the next URL for the flash player
				window.nextNewsAvailable = function () {
					setTimeout(function () {
						location = nextUrl;
					}, 2000);
				};
			});
		}
	});
	
	var doPagination = function (page) {
		var NUM_PER_PAGE = 12;
		var PAGE_HEIGHT = -496;
		
		var newPage = 0;
		if (page == 'prev') {
			newPage = parseInt($("#videoSelect .videos").css("margin-top")) / PAGE_HEIGHT - 1;
		}
		else if (page == 'next') {
			newPage = parseInt($("#videoSelect .videos").css("margin-top")) / PAGE_HEIGHT + 1;
		}
		else {
			newPage = page;
		}
		
		$("#videoSelect .videos").stop().animate({marginTop: ((newPage)*PAGE_HEIGHT)+"px"}, 10);

		// store the (new) current page
		videoPage = newPage+1;
		www.createCookie(pageCookie, videoPage, cookieTime);
		
		$("#videoSelect .pagination li a").removeClass("disable");

		if (newPage == 0) {
			$("#videoSelect .pagination .prev a").addClass("disable");
		}
		
		if (newPage == Math.floor($(".videos .videoItem").size() / NUM_PER_PAGE)) {
			$("#videoSelect .pagination .next a").addClass("disable");
		}
		
		$("#videoSelect .pagination li a").each(function() {
			if (parseInt($(this).text()) - 1 == newPage) {
				$(this).addClass("disable");
			}
		});

		var startCount = (newPage * NUM_PER_PAGE) + 1;
		var endCount = ((newPage + 1) * NUM_PER_PAGE);
		if ($(".videos .videoItem").size() - endCount < 0) {
			endCount = $(".videos .videoItem").size(); 
		}
		$(".showing strong.currentView").text(startCount + "-" + endCount);
	}
	
	$("#videoSelect").live('page', function (event, data) {
		// animate to the specified page
		doPagination(data.page-1);
	}).live('pageNext', function (event) {
		doPagination('next');
	}).live('pagePrev', function (event) {
		doPagination('prev');
	});
	
	var loadTabAndCat = function () {
		
		if (videoTabUrl && videoCatUrl) {
			// get the tab and just do the menu
			$.get(videoTabUrl, null, function (data, textStatus, jqXHR) {
				$("#contentBtm .nav li a").updateSelected(videoTabUrl);
				$("#menu", data).replaceAll("#menu").find("a").updateSelected(videoCatUrl);
			}, "html");
			// get the cat and do the content
			$.get(videoCatUrl, null, function (data, textStatus, jqXHR) {
				$("#videoSelect",data).replaceAll("#videoSelect");
				$("#contentBtm").trigger('liveStream');
				$("#videoSelect").trigger('page', {page:videoPage});
			}, "html");
		} else if (videoTabUrl) {
			// get the tab and do the menu and the content
			$.get(videoTabUrl, null, function (data, textStatus, jqXHR) {
				$("#contentBtm .nav li a").updateSelected(videoTabUrl);
				$("#menu", data).replaceAll("#menu");
				$("#videoSelect",data).replaceAll("#videoSelect");
				$("#contentBtm").trigger('liveStream');
				$("#videoSelect").trigger('page', {page:videoPage});
			}, "html");
		}

		// get the cat and do the content
		$.get(videoPlayUrl, null, function (data, textStatus, jqXHR) {
			var eventData = {
				items: $("#videoSelect .videoItem", data),
				href: href
			};
			$("#contentBtm").trigger('nowPlaying', eventData);
			$("#upNext").trigger('nowPlaying', eventData);
		}, "html");
		
		// set cookies appropriately
		www.createCookie(tabCookie, videoTabUrl, cookieTime);
		if (videoCatUrl) www.createCookie(catCookie, videoCatUrl, cookieTime);
		else www.eraseCookie(catCookie);
		www.eraseCookie(pageCookie);
	};
	
	loadTabAndCat();
	
});

/*
 * Do some of the more complex updates for the DOM as a jQuery plugin, it'll let
 * us use them as if they were built into jQuery
 */
(function($){
	var noClick = function (event) {
		event.preventDefault();
		event.stopPropagation();
		return false;
	}

	$.fn.updateSelected = function (href) {
		this.removeClass("selected").filter(function (i) {
			return href == $(this).attr("href");
		}).addClass("selected");
		return this;
	};
	
	$.fn.updateLive = function (liveStream) {
		// TODO the noClick stuff should probably just move up to the normal click handler with a current live stream and tab check! 
		if ($("#liveStreams").hasClass('selected')) 
		// strip the liveSteam class from everything, prevent clicks on everything...
		// filter for the current liveStream, add the liveStream class and allow clicks 
		this.removeClass('livestream').bind('click', noClick).filter(function (i) {
			// grr, AJAX'ed content in IE7 (and compat mode apparently) returns a FQURL from href, not the literal value despite attr fixing that behaviour
			var href = $(".videoInfo a", this).attr('href');
			// IE is false! so strip the scheme://host parts
			if (!$.support.hrefNormalized)
				href = href.replace(/^http:\/\/.*tvnz.co.nz\//, '/');
			return liveStream && liveStream.url.indexOf(href) >= 0;
		}).addClass('livestream').unbind('click', noClick);
		return this;
	};
	
	$.fn.updateNowPlaying = function (data) {
		// only highlight up now and up next items if the tab/cat displayed is the same as the play cat/tab
		if (videoPlayUrl == videoTabUrl || videoPlayUrl == videoCatUrl) {
			// live streams have no 'up next' and can't default to the first item 
			if ($("#liveStreams").hasClass('selected')) {
				// strip the current hightlights off 
				this.removeClass("currentVid nextVid").each(function (){
					$(this).children('.play').remove();
				}).filterNowPlaying(data, true).append("<img src='http://images.tvnz.co.nz/tvnz_site_images/images/play.png' class='play' />")
					.addClass("currentVid");
			} else {
				// strip the current hightlights off 
				this.removeClass("currentVid nextVid").each(function (){
					$(this).children('.play').remove();
				}).filterNowPlaying(data).append("<img src='http://images.tvnz.co.nz/tvnz_site_images/images/play.png' class='play' />")
					.addClass("currentVid").nextAll('.video').first().addClass("nextVid");
			}
		}
		return this;
	};
	
	$.fn.filterNowPlaying = function (data, preventDefault) {
		return this.filter('.video').filter(function (i) { // filter for the matching item by id, href, or default to the first item 
			return !data.id && !data.href && i == 0 && !preventDefault ||
				data.id && $(this).attr('id') == "VideoId"+data.id ||
				data.href && data.href.indexOf($(".videoInfo a", this).attr('href')) >= 0;
		});
	};
})(jQuery);

//Update Up Now on video change
function onTemplateLoaded(experienceID) {
	var bcExp = brightcove.getExperience(experienceID);
	var modVP = bcExp.getModule(APIModules.VIDEO_PLAYER);
	modVP.addEventListener(BCMediaEvent.CHANGE, function (evt) {
		var currentVideo = modVP.getCurrentVideo();
		var fields = currentVideo.customFields;
		var upNow = $('#upNow');
		var length = new Date(currentVideo.length);
		$('a.title',upNow).attr('href',fields.tvnzurl.replace(/^http:\/\/.*tvnz.co.nz/,''))
						  .text(currentVideo.displayName + ' (' + $.format.date( length, "mm:ss").replace(/^0?(\d{1,2}):(\d{2})/, '$1:$2') + ')');
		$('p.added span',upNow).text($.format.date(currentVideo.publishedDate,"hh:mma ddd MMMM dd, yyyy"));
		$('span',$('p.source',upNow).toggle(Boolean($.trim(fields.source)))).text(fields.source);
		$('p.description',upNow).html(www.truncate(currentVideo.shortDescription,110));
		
		// legacy globals
		productionUrl = escape(fields.tvnzurl);
		urlEncodedArticleTitle = escape(currentVideo.displayName);
		$('#upNow .share a, #shareMore a').each(
			function() {
				$(this).attr('href',unescape($(this).attr('href'))
						.replace(/(\W(?:u|url|add)?=)(?:[^&;]+)(.*)/i,'$1'+productionUrl+'$2') 				// re to replace url params for all share types
						.replace(/(\W(?:t|title|h)?=)(?:[^&;]+)(.*)/i,'$1'+urlEncodedArticleTitle+'$2'));	// and titles
			}
		);
		// these events also need the 'items' passed, 
		// because we don't have an ajax payload here
		// just use the current on-page items
		$("#contentBtm").trigger('nowPlaying', {id:currentVideo.referenceId, items:$("#videoSelect .videoItem")});
		$("#upNext").trigger('nowPlaying', {id:currentVideo.referenceId, items:$("#videoSelect .videoItem")});
			
	}); 
};	
