var msnVideoConfigToday =
{
	"uuid" : "",
	"activeTab" : 1,
	"tabName" : "",
	"params" : "",
	"query" : "",
	"pageSize" : 6,
	"offsetValue" : 1,
	"sortOrder" : "ActiveStartDate",
	"sortDirection" : -1,
	"resultsType" : "videobytag",
	"results" : null,
	"mkt" : "en-au",
	"tabData" : new Array(7),		//localy stores the data returned from the catalog
	"todayVidCount" : 0,			//the number of videos in the main part of the tabs
	"currentIdIndex" : -1,			//The location in tabData of the currently playing video
	"catTag" : "",
	"catRegion" : ""
};
var playerStatus;
var intDayCount = 0;
var now = new Date();	
var postionToMove = 0;
var searching = false;
var foundUUID = false;
var searchTabsLength = 0;
var uniqueId = '';
var maxDist = '';
var msnVidTitle_t = '';

function injectJSONToday(url)
{
	var script = document.createElement("script");
	script.type = "text/javascript";
	script.src = url;
	script.id = "jsonScript";
	if(msnVideoConfigToday.videoResults)
	{
		document.getElementsByTagName('head')[0].removeChild(document.getElementById("jsonScript"));
	}
	document.getElementsByTagName('head')[0].appendChild(script);
}

function selectTabToday(element,region)
{
	var tabLinks;
	if(element)
	{
		tabLinks = document.getElementById("videoTabsToday").getElementsByTagName("ul")[0].getElementsByTagName("li");		
		for(var i=0; i<tabLinks.length; i++)
		{
			if(!region || i != (tabLinks.length - 1))
			{
				tabLinks[i].className = "";
			}
		}

		if(region)
		{
			tabLinks = document.getElementById("videoEntTabs").getElementsByTagName("ul")[0].getElementsByTagName("li");			
			for(var i=0; i<tabLinks.length; i++)
			{
				tabLinks[i].className = "";
			}
		}
		else
		{
			tabLinks = document.getElementById("videoTabsToday").getElementsByTagName("ul")[0].getElementsByTagName("li");		
		}

		for(var i=0; i<tabLinks.length; i++)
		{
			if(tabLinks[i] == element)
			{
				msnVideoConfigToday.activeTab = i+1;
			}
		}

		var sixPM = document.getElementById("SixPM_news");
		if(sixPM == element || region)
		{
			var activeTab = 0;
			if(region == "Per")
			{
				msnVideoConfigToday.activeTab = 7;
				var brisbane = document.getElementById("Per");
				brisbane.className = "selected";
			}
			else if(region == "Gos")
			{
				msnVideoConfigToday.activeTab = 5;
				var sydney = document.getElementById("Gos");
				sydney.className = "selected";
			}
			else
			{//Melb
				msnVideoConfigToday.activeTab = 6;
				var melbourne = document.getElementById("Ent");
				melbourne.className = "selected";
			}
		}

		element.className = "selected";
		var selectedTab = element.getElementsByTagName("a")[0];		
		var tabName = element.getElementsByTagName("a")[0].title;						
		var videoHeaderTitle = document.getElementById("videoRightColTitle");
		var videoFooterTitle = document.getElementById("videoFooter");
		if(videoHeaderTitle && videoFooterTitle)
		{		
			videoHeaderTitle.innerHTML = "Latest " + tabName + " videos";
			videoFooterTitle.innerHTML = tabName + " videos continue below";			
		}
		
		var sixPMTabs = document.getElementById('videoEntTabs');
		if(sixPMTabs)
		{
			if(tabName == 'ENTERTAINMENT' || tabName == 'Entertainment' ||
				tabName == 'Gossip' || tabName == 'Performance')
			{
				sixPMTabs.style.display = 'block';			
			}	
			else
			{
				sixPMTabs.style.display = 'none';						
			}
		} 
		
		msnVideoConfigToday.tabName = tabName;
		msnVideoConfigToday.currentIdIndex = -1;//reset the currently index that is playing
	}	
}

function selectTab6PMToday(element)
{	
	selectTabToday(element,msnVideoConfigToday.catRegion );
	loadVideosToday('ns=MSNVideo_Cat&tag=' + msnVideoConfigToday.catTag);
}

function selectTabNumToday(tabNumber)
{
	selectTabToday(document.getElementById("videoTabsToday").getElementsByTagName("ul")[0].getElementsByTagName("li")[tabNumber]);
}

//Fetch data for videos based on ns and tag parameters. If playOnLoad is true, the first video in teh tab will be played once loaded
function loadVideosToday(params, playOnLoad)
{
	if(params)
	{
		msnVideoConfigToday.resultsType = "videobytag";
		msnVideoConfigToday.params = params;
		document.getElementById("videoDivToday").innerHTML = "<p class='loading'>Loading videos...</p>";			
		msnVideoConfigToday.offsetValue = 1;
		msnVideoConfigToday.pageSize = 50;
		
		if(msnVideoConfigToday.tabData[msnVideoConfigToday.activeTab - 1])
		{//data for this tab has already been fetched
			jsonCallbackToday(msnVideoConfigToday.tabData[msnVideoConfigToday.activeTab - 1], playOnLoad);
		}
		else
		{//get the data from the catalog
			injectJSONToday("http://edge2.catalog.video.msn.com/videoByTag.aspx?mk=" + msnVideoConfigToday.mkt + "&" + msnVideoConfigToday.params + "&ind=" + msnVideoConfigToday.offsetValue + "&sf=" + msnVideoConfigToday.sortOrder + "&sd=" + msnVideoConfigToday.sortDirection + "&ps=" + msnVideoConfigToday.pageSize + "&responseEncoding=json&callbackName=jsonCallbackToday" + (playOnLoad ? "&cd=" + playOnLoad : ""));
		}
	}
}

function loadMinorVideosToday()
{
	var vidTabMinor = document.getElementById("videoTabsMinor");
	if(vidTabMinor)
	{
		vidTabMinor.innerHTML = "<p class='loading'>Loading videos...</p>";
	}

	if(msnVideoConfigToday.resultsType == "search")
	{
		injectJSONToday("http://edge2.catalog.video.msn.com/search.aspx?mk=" + msnVideoConfigToday.mkt + "&" + msnVideoConfigToday.params + "&q=" + msnVideoConfigToday.query + "&ind=" + msnVideoConfigToday.offsetValue + "&sf=" + msnVideoConfigToday.sortOrder + "&sd=" + msnVideoConfigToday.sortDirection + "&ps=" + msnVideoConfigToday.pageSize + "&responseEncoding=json&callbackName=jsonCallbackPagingSectionToday");
	}
	else if(msnVideoConfigToday.resultsType == "videobytag")
	{
		injectJSONToday("http://edge2.catalog.video.msn.com/videoByTag.aspx?mk=" + msnVideoConfigToday.mkt + "&" + msnVideoConfigToday.params + "&ind=" + msnVideoConfigToday.offsetValue + "&sf=" + msnVideoConfigToday.sortOrder + "&sd=" + msnVideoConfigToday.sortDirection + "&ps=" + msnVideoConfigToday.pageSize + "&responseEncoding=json&callbackName=jsonCallbackPagingSectionToday");
	}
}

function changePageToday(delta)
{	
	msnVideoConfigToday.offsetValue = ((delta - 1) * msnVideoConfigToday.pageSize) + msnVideoConfigToday.todayVidCount + 1;
	loadMinorVideosToday();
}

function prependMainTabToday(tabName)
{
	var searchTabString = '<li title="' + tabName + '" onclick="selectTabToday(this);searchVideosToday(this.title);return false;"><a href="#" onclick="return false;" title="' + tabName + '">' + tabName + '</a></li>';
	var currentTabs = document.getElementById("videoTabsToday").getElementsByTagName("ul")[0];
	if(currentTabs)
	{
		currentTabs.innerHTML = searchTabString + currentTabs.innerHTML;
	}
	
	selectTabNumToday(0);
	maxDist = countLiNodesToday();  //  works out how far to the left to animate the Ent tabs	
	msnVideoConfigToday.tabData.unshift(null);//prepend the data array as a placeholder
}

function searchVideosToday(searchString)
{
	var query = document.getElementById("videoSearchTextBoxToday");
	if(query)
	{
	    var queryTrim = ( query.value.length > 7 ) ? query.value.substring(0,8) + "..." : query.value; 
		//Insert a new tab for the search results and enable the scrolling functionality
		if(!searchString)
		{
			prependMainTabToday(queryTrim);
			$("#videoTabsToday").css({"width":"284px","margin":"0 3px"});
			$("#videoImgBack, #videoImgFwd").css("display", "block");
			msnVideoConfigToday.query = query.value;
		}
		else
		{
			msnVideoConfigToday.query = searchString;
		}

		msnVideoConfigToday.resultsType = "search";
		msnVideoConfigToday.tabName = "Search results";
		msnVideoConfigToday.params = "ns=MSNVideo_Cat&tag=AUnationalninenews";
		document.getElementById("videoDivToday").innerHTML = "<p class='loading'>Searching for videos...</p>";			
		document.getElementById("videoRightColTitle").innerHTML = "Search results";
		document.getElementById("videoRightColDate").innerHTML = formatDateToday(msnVideoConfigToday.results.video[i].startDate.$,'MDY'); 
		document.getElementById("videoFooter").innerHTML = "Search results videos continue below";
		msnVideoConfigToday.offsetValue = 1;
		msnVideoConfigToday.pageSize = 6;

		//Then call the JSON service for search
		if(msnVideoConfigToday.tabData[msnVideoConfigToday.activeTab - 1])
		{//data for this tab has already been fetched
			jsonCallbackToday(msnVideoConfigToday.tabData[msnVideoConfigToday.activeTab - 1]);
		}
		else
		{//get the data from the catalog
			injectJSONToday("http://edge2.catalog.video.msn.com/search.aspx?mk=" + msnVideoConfigToday.mkt + "&" + msnVideoConfigToday.params + "&q=" + msnVideoConfigToday.query + "&ind=" + msnVideoConfigToday.offsetValue + "&sf=" + msnVideoConfigToday.sortOrder + "&sd=" + msnVideoConfigToday.sortDirection + "&ps=" + msnVideoConfigToday.pageSize + "&responseEncoding=json&callbackName=jsonCallbackToday");
		}
	}	
}

function countLiNodesToday()
{
	//  count li nodes for tabs above main index
	var ul = document.getElementById("videoList");
	var liNodes = 0;			 
	for (var i = 0; i < ul.childNodes.length; i++)
	{
		if (ul.childNodes[i].nodeName == "LI")
		{
			liNodes++;
		}
	}	
	var standardTabsLength = 240;  //  this is the length of the 4 standard tabs, roughly 60px each
	searchTabsLength = liNodes * 60;  // this will be the length of the 5 tabs + any additional search tabs	
	return standardTabsLength - searchTabsLength;
}

function limitStringToday(inputString, limit)
{
	if(inputString.length > limit)
	{
		var words = inputString.split(" ");
		var tmpText = "";
		var j = 0;
		while(j < words.length-1)
		{
			outText = tmpText;
			tmpText += words[j] + " "; 
			if (tmpText.length > limit)
			{
				break;
			}
			outText = tmpText;
			j++;
		}
		return outText.substring(0,outText.length-1) + "...";
	}
	return inputString
}

// Trim whitespace characters
function trimToday(stringToTrim)
{
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}

// Replace all occurrences of a string with another
function replaceAllToday(stringToReplace, findText, repText)
{
	return stringToReplace.replace(new RegExp(findText,"g"), repText);
}

// JavaScript querystring helper function
function PageQueryToday(q)
{
	if(q.length > 1)
	{
		this.q = q.substring(1, q.length);
	}
	else
	{
		this.q = null;
	}
	this.keyValuePairs = new Array();
	if(q)
	{
		for(var i=0; i < this.q.split("&").length; i++)
		{
			this.keyValuePairs[i] = this.q.split("&")[i];
		}
	}
	this.getValue = function(s)
	{
		for(var j=0; j < this.keyValuePairs.length; j++)
		{
			if(this.keyValuePairs[j].split("=")[0] == s)
			{
				return this.keyValuePairs[j].split("=")[1];
			}
		}
		return false;
	}
}

function queryStringToday(key)
{
	var page = new PageQueryToday(window.location.search); 
	return unescape(page.getValue(key)); 
}	

function jsonCallbackPagingSectionToday(results)
{
	if(results.video.length > 0)
	{
		var strDayToCompare = formatDateToday(results.video[0].startDate.$);			
		var videoDateMDY = formatDateToday(results.video[0].startDate.$,'MDY');
		var vidTabMinor = document.getElementById("videoTabsMinor");
		if(vidTabMinor)
		{
			vidTabMinor.innerHTML = "";
		}

		videoItemHTML = '<div class="videoDate">' + videoDateMDY +'</div>';
		
		for(var i = 0; i < results.video.length; i++)
		{
			var currentVideo = results.video[i];
			var videoDateString = formatDateToday(currentVideo.startDate.$);	
			if(videoDateString != strDayToCompare)
			{
				intDayCount++;
				strDayToCompare = videoDateString;
				videoDateMDY = formatDateToday(results.video[i].startDate.$,'MDY');						 		
				videoItemHTML += '<div class="videoDate">' + videoDateMDY  +'</div>';				
			}			
			var videoDescriptionNoHtml = replaceAllToday(currentVideo.description.$, "\"", "&quot;");
			var videoDescriptionNoHtml = replaceAllToday(videoDescriptionNoHtml, ">", "&gt;");
			var videoDescriptionNoHtml = replaceAllToday(videoDescriptionNoHtml, "<", "&lt;");
			var videoTitle = limitStringToday(currentVideo.title.$, 25);						
			videoItemHTML +=
			'<div class="videoItem" onclick="playVideoUUIDToday(\'' + currentVideo.uuid.$ + '\');" >' +
				'<span class="videoItemTitle" title="' + currentVideo.source.$friendlyName + '">' + currentVideo.source.$friendlyName + ':</span>' +
				'<span class="videoCaption" title="' + currentVideo.title.$ + '">' + currentVideo.title.$ + '</span><span class="playButton">Play</span>' +
				'<div class="videoPostedDate">Posted: ' + videoDateString + '</div>' +				
			'</div>';
			vidTabMinor.innerHTML += videoItemHTML;
			videoItemHTML = '';	
		}

		renderMinorPagingToday(results);
		attachMinorTabEventsToday();
		setHeightAuto();		
			
	}
}

function setHeightAuto()
{
	//  fix for column heights
	document.getElementById("rghtcol").style.height= 'auto';
	document.getElementById("contentcol").style.height = 'auto';
	document.getElementById("lftcol").style.height= 'auto';	
}

function attachMinorTabEventsToday()
{
	$("#videoTabsMinor .videoItem").bind("mouseenter",function(){
		$(this).css("background-color",	"#262D54");
		$(this).find(".videoItemTitle, .videoCaption, .playButton").css("text-decoration", "underline");
	});
	
	$("#videoTabsMinor .videoItem").bind("mouseleave",function(){
		$(this).css("background-color",	"#262D54");
		$(this).find(".videoItemTitle, .videoCaption, .playButton").css("text-decoration", "none");
	});
}

//Renders the paging for the minor video results
function renderMinorPagingToday(results)
{
	if(results.$total > results.video.length)
	{//paging is required
		var resultPages = Math.ceil((results.$total - msnVideoConfigToday.todayVidCount) / msnVideoConfigToday.pageSize);
		var currentPage = Math.ceil((msnVideoConfigToday.offsetValue - msnVideoConfigToday.todayVidCount) / msnVideoConfigToday.pageSize);
		
		// Number of pages to display
		var displayPages = 3;		
		var startIndex = currentPage - 1; // normal case
		if(currentPage < displayPages)
		{//special case for first 3 pages
			startIndex = 1;
		}
		else if(currentPage >= resultPages - 1)
		{//special case for the last 3 pages
			startIndex = resultPages - 2;
		}

		var pageLinksHTML = "";
		var firstPageHTML = "";
		var prevPageHTML = "";
		var nextPageHTML = "";
		var lastPageHTML = "";

		for(var i = startIndex; i < startIndex + displayPages; i++)
		{
			var pageLink = "";
			if(i == currentPage)
			{
				pageLink = '<div class="pageNumber pageNumberSelected">' + i + '</div>';
			}
			else if(i <= resultPages)
			{
				pageLink = '<div class="pageNumber" onclick="changePageToday(' + i + ');">' + i + '</div>';
			}
			pageLinksHTML += pageLink;
		}			
		
		if(currentPage < resultPages)
		{
			nextPageHTML = '<div class="pageNumber" onclick="changePageToday(' + parseInt(currentPage + 1) + ');">Next</div>';
		}

		if((currentPage < resultPages - 1) && resultPages > displayPages)
		{
			lastPageHTML = '<div class="elipsees">...</div><div class="pageNumber" onclick="changePageToday(' + resultPages + ');">' + resultPages + '</div>';
		}

		if(currentPage > 1)
		{//Only show PREV if not on the first page
			prevPageHTML = '<div class="pageNumber" onclick="changePageToday(' + parseInt(currentPage - 1) + ');">Prev</div>';
		}
				
		if(currentPage > displayPages - 1)
		{
			firstPageHTML = '<div class="pageNumber" onclick="changePageToday(1);">1</div><div class="elipsees">...</div>';				
		}

		var pagesHTML = '<div class="pageNumbers">' + prevPageHTML + firstPageHTML + pageLinksHTML + lastPageHTML + nextPageHTML + '</div>';
		document.getElementById("videoDivPagination").innerHTML = pagesHTML;
	}
	else // One page only
	{
		document.getElementById("videoDivPagination").innerHTML = "";
	}
}

//Renders the main portion of the video tabs given the results
function jsonCallbackToday(results, playOnLoad)
{
	if(results)
	{
		msnVideoConfigToday.todayVidCount = 0;
		msnVideoConfigToday.results = results;
		msnVideoConfigToday.tabData[msnVideoConfigToday.activeTab - 1] = results;		
		var vidDiv = document.getElementById("videoDivToday");		
		if(vidDiv)
		{
			vidDiv.innerHTML = "";		
		}	
		//All videos with the most recent date should be rendered in the main section, all others in the pagination section
		var mostRecentVideoDate = '';
		
		for(var i = 0;i < results.video.length; i++)
		{
			if(msnVideoConfigToday.resultsType == "search")
			{//if search is in progress, display only top 6 results in main section
				if(msnVideoConfigToday.todayVidCount >= 6)
				{
					break;
				}
			}
			else
			{
				var videoDateString = formatDateToday(results.video[i].startDate.$);	
				if(i == 0)
				{
					mostRecentVideoDate = videoDateString;
					document.getElementById("videoRightColDate").innerHTML = formatDateToday(results.video[i].startDate.$,'MDY');
				}
				else if(mostRecentVideoDate != videoDateString)
				{//Video is past the most recent date, no need to proceed
					break;
				}
			}
				
			vidDiv.innerHTML += getVideoItemHTMLToday(results.video[i], i);
			msnVideoConfigToday.todayVidCount++;
		}	
			
		if(results.$total == 0)
		{
			document.getElementById("videoRightColDate").innerHTML = "";	
			document.getElementById("videoDivPagination").innerHTML = "";		
			document.getElementById("videoTabsMinor").innerHTML = "";	
			document.getElementById("videoDivToday").innerHTML = "<p>No videos found.</p>";
			document.getElementById("videoFooter").innerHTML = "";
		}
		else
		{
			var currentYear = (new Date()).getFullYear();			
			if(playOnLoad)
			{
				//if tab is specified in query string, play first video for that tab
				playVideoToday(0);
			}	

			if(results.$total > 6)
			{
				//fetch more in the minor tabs
				msnVideoConfigToday.pageSize = 6;
				msnVideoConfigToday.offsetValue = msnVideoConfigToday.todayVidCount + 1;
				//Next, fetch the next six videos for the pagination section
				loadMinorVideosToday()
			}
			else
			{
				document.getElementById("videoDivPagination").innerHTML = "";		
				document.getElementById("videoTabsMinor").innerHTML = "";	
				document.getElementById("videoFooter").innerHTML = "";
			}
		}
		attachAnnimationEvents();
	}		
}

function getVideoItemHTMLToday(itemData, i)
{
	var videoDescriptionNoHtml = replaceAllToday(itemData.description.$, "\"", "&quot;");
	var videoDescriptionNoHtml = replaceAllToday(videoDescriptionNoHtml, ">", "&gt;");
	var videoDescriptionNoHtml = replaceAllToday(videoDescriptionNoHtml, "<", "&lt;");
	var videoTitle = limitStringToday(itemData.title.$, 25);
	var videoThumbnailSrc = getThumbnailUrl(itemData, 0);
	var videoItemHTML = '';
	var	videoDescription = limitStringToday(videoDescriptionNoHtml, 70);
			
	videoItemHTML =
	'<div class="videoItem" id="videoItem_' + i + '" onclick="playVideoUUIDToday(\'' + itemData.uuid.$ + '\');">' +
		'<div class="itemImage">' +					
			'<img class="playingImg" src="/img/videoindex/arrow_cover_img.png" />' +			
			'<img class="videoImage" src="' + videoThumbnailSrc + '" alt="' + itemData.title.$ + '" title="' + itemData.title.$ + '" />' +
			'<div class="playFadeBG" /></div>' +
		'</div>' +
		'<div class="videoTitle" title="' + itemData.title.$ + '">' + videoTitle + '</div>' +
		'<div class="videoText" title="' + videoDescriptionNoHtml + '">' +
			//'<img class="playingImg" src="/img/videoindex/arrow_orange.gif" />' + videoDescription + '<span class="playButton">Play</span>' +
			'<span class="playingImg">Playing...</span>' + videoDescription + '<span class="playButton">Play</span>' +
		'</div>' +
	'</div>';
	return videoItemHTML;
}

function highlightIndexToday(uuid)
{
	var tabData = msnVideoConfigToday.tabData[msnVideoConfigToday.activeTab - 1];
	if(tabData && tabData.video)
	{
		var videoArray = tabData.video;
		for(var j = 0; j < videoArray.length; j++)
		{
			var video = videoArray[j];
			var currentUuid = video.uuid.$;
			if(currentUuid == uuid && j < msnVideoConfigToday.todayVidCount)
			{
				msnVideoConfigToday.currentIdIndex = j;
				var tabItem = document.getElementById("videoItem_" + j);
				highlightVideo(tabItem);
				return true;
			}
		}
	}
	
	//if none found, close all tab items
	closeTabItems();	
}
function dateMDToday(date)
{
	var videoDateMD = '';
	var videoDateMDY = formatDateToday(date, 'MDY');
	videoDateMD = videoDateMDY.substr(0, videoDateMDY.indexOf(','));
	return videoDateMD;
}

function formatDateToday(dateString, MDY)
{//2008-12-16T02:00:00Z
	var months = [
		"January",
		"February",
		"March",
		"April",
		"May",
		"June",
		"July",
		"August",
		"September",
		"October",
		"November",
		"December"
	];
	var videoDateArray = dateString.substring(0,10).split('-');
	var videoTimeArray = dateString.substring(11,16).split(':');	

	var videoDate = new Date();
	videoDate.setUTCFullYear(videoDateArray[0], parseInt(videoDateArray[1],10) - 1, videoDateArray[2]);
	videoDate.setUTCHours(videoTimeArray[0], videoTimeArray[1]);
	if(MDY)
	{
		return months[videoDate.getMonth()] + ' ' + videoDate.getDate() + ', ' + videoDateArray[0];		
	}
	else
	{
		return getDateThToday(videoDate.getDate()) + " " + months[videoDate.getMonth()];
	}	
}

//Returns the extension to a number (this is one of "*1st", "*2nd", "*3rd" or "*th"
function getDateThToday(number)
{
	var strNumber = number.toString();
	var lastDigit = strNumber.substr(strNumber.length - 1);
	var resultStr = "";

	if(lastDigit == 0 || lastDigit > 3)
	{
		resultStr = strNumber + "th";
	}
	else if(lastDigit == 3)
	{
		resultStr = strNumber + "rd";
	}
	else if(lastDigit == 2)
	{
		resultStr = strNumber + "nd";
	}
	else if(lastDigit == 1)
	{
		resultStr = strNumber + "st";
	}

	return resultStr;
}

/**
 * Callback function to check for the source image.  If the image is available and is not the default ninemsn logo,
 * it replaces the current placeholder. 
 * Author: Domagoj Filipovic
 * Date: 29/04/08
 * Notes:	This is a workaround fix to use the service which returns the url of the content source images rather
 *			than building the url on the fly and assuming the image will be located in a predefined location.
 */
function srcImgCallbackToday(results)
{
	var img = document.getElementById("srcVidImgLogo");

	if(img)
	{
		if(results && results.contentSource && results.contentSource.$logoUrl && results.contentSource.$logoUrl != "http://img.video.msn.com/video/i/src/AU_ninemsn.gif")
		{//get image src from results. If it contains anything, update the image. Ignore the default ninemsn image
			img.src = results.contentSource.$logoUrl;
			img.alt = results.contentSource.$friendlyName;
		}
		//Make image visable
		img.style.visibility = "visible";
	}
}

/**
 * Returns the correct thumbnail url to use for the specified video.  Will return the image with the 2009 formatCode th
 * Author: Domagoj Filipovic
 * Date: 28/04/08
 * Notes:	The image with a formatCode of "2009" is the 300 x 400 image supplied by ninemsn and should be used in
 *			conjunction with the ninemsn resizer if found.  If not found, the "2007" format should be used.  The "2007"
 *			has 2 variants:
 *				1. Ninemsn supplied image (this should be passed through the ninemsn resizer)
 *				2. MSN resized thumbnail (this SHOULD NOT be passed through the ninemsn resizer).
 */

function buildVideoPathToday(videoData)
{
	var result = "";
	var pid = videoData.providerId.$;
	var base = "http://images.netshow.ninemsn.com.au";
	var extension = ".jpg";
	
	if(pid.length < 9)
	{
		for(var i = 0; i < 9 - pid.length; i ++)
		{
			result += "0";
		}
		result += pid;
	}
	else
	{
		result = pid.substring(pid.length - 9, pid.length);
	}
	
	result = insertStringToday(result, 9, "/");
	result = insertStringToday(result, 6, "/");
	result = insertStringToday(result, 3, "/");
	result = insertStringToday(result, 0, "/");

	return base + result + pid + extension;
}

function insertStringToday(str, pos, inStr)
{
	var result = str;

	if(pos >= 0 && pos <= str.length)
	{
		var pre = str.substring(0, pos);
		var post = str.substring(pos, str.length);
		result = pre + inStr + post;
	}

	return result;
}



function setGEOCodeRegion(data)
{
	if(data && data.IpLocationList && data.IpLocationList.IpLocation && data.IpLocationList.IpLocation.RegionCode)
	{
		var regionCode = data.IpLocationList.IpLocation.RegionCode;		
		var catTitle = "";
		
		if(regionCode == "07")//QLD
		{
			msnVideoConfigToday.catTag = "aubrisbane";
			catTitle = "Brisbane";
			msnVideoConfigToday.catRegion  = "Bris";			
			
		}
		else if(regionCode == "02")//NSW
		{
			msnVideoConfigToday.catTag = "ausydney";
		    catTitle = "Sydney";
			msnVideoConfigToday.catRegion = "Syd";			
			
		}
		else//default to VIC for all else
		{
			msnVideoConfigToday.catTag = "aumelbourne";
			catTitle = "Melbourne";
			msnVideoConfigToday.catRegion = "Melb";
			
		}

		var SixPM_news = document.getElementById("SixPM_news");
		if(SixPM_news)
		{			
			var titleA = SixPM_news.getElementsByTagName("a")[0];
			if(titleA)
			{
				titleA.title = catTitle;
			}
		}
	}
}

function focusOnSearch(obj) {
    if (obj.value == 'Search TODAY videos')
    {
        obj.value = '';
    }
    return true;
}

function focusOutSearch(obj) {
    if (obj.value == '')
    {
        obj.value = 'Search TODAY videos';
    }
    return true;
}

function attachAnnimationEvents()
{
	$(".videoTabs .videoItem").bind("mouseenter",function(){
		//$(this).css("opacity",0.7);
		//$(this).find(".itemImage .thumb").css("opacity",0.5);
		if(this.className.indexOf("selected") == -1)
		{
			$(this).css("background-color",	"262D54");
			$(this).find(".itemImage .playFadeBG").css("z-index", 3);			
		}
		$(this).find(".videoTitle, .playButton").css("text-decoration", "underline");
	});
	
	$(".videoTabs .videoItem").bind("mouseleave",function(){
		//$(this).css("opacity",1);
		//$(this).find(".itemImage .thumb").css("opacity",1);
		if(this.className.indexOf("selected") == -1)
		{
			$(this).css("background-color",	"#262D54");
		}
		$(this).find(".itemImage .playFadeBG").css("z-index", 1);
		$(this).find(".videoTitle, .playButton").css("text-decoration", "none");
	});
	
	$(".videoTabs .videoItem").click(function(){
		highlightVideo(this);
	});
}

function highlightVideo(element)
{
	$(document).ready(function(){
		var jElem = $(element);
		if(!jElem.hasClass("selected"))
		{
			closeTabItems();
			jElem.addClass("selected");
			openTabItemToday(jElem);
		}
	});
}

//closes all tabs
function closeTabItems()
{
	var animationTime = 200;
	//move image arrow
	$(".videoTabs .itemImage .playingImg").animate({"left":"-18px"}, animationTime, "swing");
	//move text arrow
	$(".videoTabs .videoText .playingImg").animate({"marginLeft":"-77px"}, animationTime, "swing");
	//remove play button
	$(".videoTabs .playButton").show();
	//change style
	$(".videoTabs .videoItem").css("background-color", "#262D54");
	$(".videoTabs .videoItem .videoTitle, .videoIndexRight .videoItem .videoText").css("color", "#FFF");
	$(".videoTabs .videoItem").removeClass("selected");
}

//open one tab
function openTabItemToday(item)
{
	var animationTime = 200;
	//move image arrow
	item.find(".itemImage .playingImg").animate({"left":"0"}, animationTime, "swing");
	//move text arrow
	item.find(".videoText .playingImg").animate({"marginLeft":"0px"}, animationTime, "swing");
	//remove play button
	item.find(".playButton").hide();
	//change style
	item.css("background-color", "#FFF");
	item.find(".videoTitle, .videoText").css("color", "#000");
}

//Given the index position, plays a video that is in the current results set
function playVideoToday(index)
{	
    msnVideoConfigToday.currentIdIndex = index;
    playerStatus = 3;
    playVideoUUIDToday(msnVideoConfigToday.results.video[index].uuid.$);
}

//Given the UUID of a specific video, plays that video in the video player
function playVideoUUIDToday(uuid)
{
	$(document).ready(function(){
		var msnVidObj = document.getElementById("MSNVideoPlayer_pobj");	
		if(msnVidObj)
		{
			if(typeof(msnVidObj.vidPlayId) == "function")
			{
				msnVideoConfigToday.uuid = uuid;
				msnVidObj.vidPlayId(uuid);
			}
		}			
	});
}

//When a new video is loaded, highlight it in the RHS if it can be found
Msn.Video.OnVideoLoaded = function(id)
{
    highlightIndexToday(id);  
    playerStatus = 1; 
}

//When a video completes, begin playing the video immediately after it.
//If the video is not currently in the RHS or is the last video, begin playing the first video in the RHS
Msn.Video.OnMediaCompleted = function()
{
    if (playerStatus != 3) {
        playerStatus = 0;
        setTimeout("OnMediaCompletedCallback()", 2000); // wait short period before callback
    } 
}  


Msn.Video.OnRequestAutoplay = function() {
        var newIndex = msnVideoConfig.currentIdIndex + 1;
        if (newIndex >= msnVideoConfig.todayVidCount) {
            newIndex = 0;
        }
        playVideo(newIndex);
}

function OnMediaCompletedCallback() {
    if (playerStatus == 0) {
	//var vidTitle = document.getElementById("MSNVideoPlayer_t").innerHTML;
	if(flashTitle != "Advertisement")
	{
		var newIndex = msnVideoConfigToday.currentIdIndex + 1;
		if(newIndex >= msnVideoConfigToday.todayVidCount)
		{
			newIndex = 0;
		}			
	}
	playVideoToday(newIndex);	
    }
} 

$(document).ready(function(){
			
	$("#videoImgBack").click(function(){
		var left = parseInt($("#videoTabsInner").css("left"));		
		var newLeft = left + 60;		
		if(newLeft <= 0)
		{
			$("#videoTabsInner").animate({"left":newLeft + "px"}, 200, "swing");
		}	
	});
	$("#videoImgFwd").click(function(){		
		var left = parseInt($("#videoTabsInner").css("left"));		
		var newLeft = left - 60;		
		if(newLeft >= maxDist)	
		{
			$("#videoTabsInner").animate({"left":newLeft + "px"}, 200, "swing");
		}		
	});	
});








