/*
*  msn_video_collection.js
*  JavaScript functions used by the MSN Video Collection highlights template (2179.ascx)
*
*  John Lundebro
*  Last updated: 2007-08-15
*/

if(!Msn)
{
	Msn={};
	if(!Msn.Video)
	{
		Msn.Video = {};
	}
}
var flashTitle = '';
var isMSNVideoClickEnabled = false;

var msnVideoConfig =
{
	"uuid" : "",
	"activeTab" : 1,
	"tabName" : "",
	"params" : "",
	"query" : "",
	"pageSize" : 12,
	"offsetValue" : 1,
	"sortOrder" : "ActiveStartDate",
	"sortDirection" : -1,
	"resultsType" : "videobytag",
	"results" : null,
	"mkt" : "en-au"
};

function injectJSON(url)
{
	var script = document.createElement("script");
	script.type = "text/javascript";
	script.src = url;
	script.id = "jsonScript";
	if(msnVideoConfig.videoResults)
	{
		document.getElementsByTagName('head')[0].removeChild(document.getElementById("jsonScript"));
	}
	document.getElementsByTagName('head')[0].appendChild(script);
}

function selectTab(element)
{
	var tabLinks = document.getElementById("videoTabs").getElementsByTagName("ul")[0].getElementsByTagName("li");
	for(var i=0; i<tabLinks.length; i++)
	{
		if(tabLinks[i] == element)
		{
			msnVideoConfig.activeTab = i+1;
		}
		tabLinks[i].className = "";
	}
	element.className = "selected";
	var tabName = element.getElementsByTagName("a")[0].innerHTML;
	document.getElementById("videoRightColHeader").innerHTML = tabName;
	msnVideoConfig.tabName = tabName;
}

function selectFirstTab()
{
	selectTabNum(0);
}

function selectTabNum(tabNumber)
{
	selectTab(document.getElementById("videoTabs").getElementsByTagName("ul")[0].getElementsByTagName("li")[tabNumber]);
}

// Fetch data for a single video with the uuid provided in the querystring
function loadSingleVideo(uuid, tabNumber)
{
	msnVideoConfig.uuid = uuid;
	// Select the tab unless it's the "more" tab
	if(document.getElementById("videoTabs").getElementsByTagName("ul")[0].getElementsByTagName("li")[tabNumber].getElementsByTagName("a")[0].className != "moreLink")
	{
		selectTab(document.getElementById("videoTabs").getElementsByTagName("ul")[0].getElementsByTagName("li")[tabNumber]);
	}
}

// Fetch data for videos based on ns and tag parameters
function loadVideos(params, offsetValue)
{
	if(params)
	{
		msnVideoConfig.resultsType = "videobytag";
		msnVideoConfig.params = params;
		document.getElementById("videoDiv").innerHTML = "<p>Loading videos...</p>";
		if(offsetValue)
		{
			msnVideoConfig.offsetValue = offsetValue;
			injectJSON("http://edge1.catalog.video.msn.com/videoByTag.aspx?mk=" + msnVideoConfig.mkt + "&" + msnVideoConfig.params + "&ind=" + msnVideoConfig.offsetValue + "&sf=" + msnVideoConfig.sortOrder + "&sd=" + msnVideoConfig.sortDirection + "&ps=" + msnVideoConfig.pageSize + "&responseEncoding=json&callbackName=jsonCallback");
		}
		else
		{
			msnVideoConfig.offsetValue = 1;
			injectJSON("http://edge1.catalog.video.msn.com/videoByTag.aspx?mk=" + msnVideoConfig.mkt + "&" + msnVideoConfig.params + "&sf=" + msnVideoConfig.sortOrder + "&sd=" + msnVideoConfig.sortDirection + "&ps=" + msnVideoConfig.pageSize + "&responseEncoding=json&callbackName=jsonCallback");
		}
	}
	else
	{
		document.getElementById("videoDiv").innerHTML = "";
	}
}

function sortVideos(sortOrder)
{
	msnVideoConfig.offsetValue = 1;
	msnVideoConfig.sortOrder = sortOrder;
	msnVideoConfig.sortDirection = -1;
	if(msnVideoConfig.sortOrder == "Title")
	{
		msnVideoConfig.sortDirection = 1;
	}
	if(msnVideoConfig.resultsType == "search")
	{
		searchVideos(msnVideoConfig.offsetValue);
	}
	else
	{
		loadVideos(msnVideoConfig.params, msnVideoConfig.offsetValue);
	}
}

function changePage(delta)
{
	if(delta == "first")
	{
		msnVideoConfig.offsetValue = 1;
	}
	else
	{
		if(delta == "last")
		{
			var resultPages = Math.ceil(msnVideoConfig.results.$total / msnVideoConfig.pageSize);
			var currentPage = (msnVideoConfig.pageSize + msnVideoConfig.offsetValue - 1) / msnVideoConfig.pageSize;
			delta = resultPages - currentPage;
		}
		msnVideoConfig.offsetValue += delta * msnVideoConfig.pageSize;
	}

	if(msnVideoConfig.resultsType == "search")
	{
		searchVideos(msnVideoConfig.offsetValue);
	}
	else
	{
		loadVideos(msnVideoConfig.params, msnVideoConfig.offsetValue);
	}
}

function searchVideos(offsetValue)
{
	if(offsetValue)
	{
		msnVideoConfig.offsetValue = offsetValue;
	}
	else
	{
		msnVideoConfig.offsetValue = 1;
	}
	msnVideoConfig.resultsType = "search";
	var query = document.getElementById("videoSearchTextBox").value;
	if(trim(query) != "")
	{
		msnVideoConfig.query = query;
		msnVideoConfig.tabName = "Search results"
		document.getElementById("videoDiv").innerHTML = "<p>Searching...</p>";
		document.getElementById("videoRightColHeader").innerHTML = "Search results";
		var tabLinks = document.getElementById("videoTabs").getElementsByTagName("ul")[0].getElementsByTagName("li");
		for(var i=0; i<tabLinks.length; i++)
		{
			tabLinks[i].className = "";
		}
		if(tabLinks[0].firstChild.innerHTML == "Search results")
		{
			tabLinks[0].className = "selected";
		}
		else
		{
			var searchTabString = '<li class="selected" onclick="selectTab(this);searchVideos();"><a href="#" onclick="return false;">Search results</a></li>';
			var currentSearchTabHtml = trim(document.getElementById("videoTabs").getElementsByTagName("ul")[0].innerHTML);
			document.getElementById("videoTabs").getElementsByTagName("ul")[0].innerHTML = searchTabString + currentSearchTabHtml;
		}
		injectJSON("http://edge1.catalog.video.msn.com/search.aspx?mk=" + msnVideoConfig.mkt + "&" + msnVideoConfig.params + "&q=" + msnVideoConfig.query + "&ind=" + msnVideoConfig.offsetValue + "&sf=" + msnVideoConfig.sortOrder + "&sd=" + msnVideoConfig.sortDirection + "&ps=" + msnVideoConfig.pageSize + "&responseEncoding=json&callbackName=jsonCallback");
	}
}

function limitString(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 trim(stringToTrim)
{
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}

// Replace all occurrences of a string with another
function replaceAll(stringToReplace, findText, repText)
{
	return stringToReplace.replace(new RegExp(findText,"g"), repText);
}

// JavaScript querystring helper function
function PageQuery(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 queryString(key)
{
	var page = new PageQuery(window.location.search); 
	return unescape(page.getValue(key)); 
}							

function jsonCallback(results)
{
	// Save results to config object
	msnVideoConfig.results = results;
	document.getElementById("videoDiv").innerHTML = "";
	
	for(var i=0; i<results.video.length; i++)
	{
		// Create video item
		var videoDateString = formatDate(results.video[i].startDate.$);
		var videoDescriptionNoHtml = replaceAll(results.video[i].description.$, "\"", "&quot;");
		videoDescriptionNoHtml = replaceAll(videoDescriptionNoHtml, ">", "&gt;");
		videoDescriptionNoHtml = replaceAll(videoDescriptionNoHtml, "<", "&lt;");
		var videoTitle = limitString(results.video[i].title.$, 30);
		var videoDescription = limitString(videoDescriptionNoHtml, 120);
		var videoThumbnailSrc = getThumbnailUrl(results.video[i]);
		var videoItemHTML =
		'<div class="videoItem" onmouseover="this.className=\'videoItem videoItemOver\';" onmouseout="this.className=\'videoItem\';">' +
			'<div onclick="playVideo(' + i + ');" onmouseover="this.parentNode.lastChild.className=\'videoDescription\';" onmouseout="this.parentNode.lastChild.className=\'videoDescription videoDescriptionHidden\';">' +
				'<img class="videoImage" src="' + videoThumbnailSrc + '" alt="' + results.video[i].title.$ + '" title="' + results.video[i].title.$ + '" />' +
			'</div>' +
			'<a href="#" onclick="playVideo(' + i + ');return false;" title="' + results.video[i].title.$ + '">' + videoTitle + '</a>' +
			'<div class="videoSource">' + results.video[i].source.$friendlyName + '</div>' +
			'<div class="videoPostedDate">Posted: ' + videoDateString + '</div>' +
			'<div class="videoDescription videoDescriptionHidden">' +
				'<div class="videoDescriptionHeader">Overview</div>' +
				'<div>' + videoDescription + '</div>' +
			'</div>' +
		'</div>';
		document.getElementById("videoDiv").innerHTML += videoItemHTML;
	}
	
	// Create sort dropdown list
	var sortOrders = {};
	if(msnVideoConfig.resultsType == "search")
	{
		sortOrders =
		{
			"sortOrderNames" : ["Relevance", "ActiveStartDate", "HourlyCount", "DailyCount", "TotalCount"],
			"sortOrderTitles" : ["relevance", "posted date", "views: last hour", "views: today", "views: total"]
		};
	}
	else
	{
		var sortOrders =
		{
			"sortOrderNames" : ["ActiveStartDate", "Title", "HourlyCount", "DailyCount", "TotalCount"],
			"sortOrderTitles" : ["posted date", "title", "views: last hour", "views: today", "views: total"]
		};
	}
	var sortHTML =
	'<span>Sort by:</span>' +
	'<select onchange="sortVideos(this.value);">';
	for(var i=0; i<sortOrders.sortOrderNames.length; i++)
	{
		if(msnVideoConfig.sortOrder == sortOrders.sortOrderNames[i])
		{
			sortHTML += '<option value="' + sortOrders.sortOrderNames[i] + '" selected="selected">' + sortOrders.sortOrderTitles[i] + '</option>';
		}
		else
		{
			sortHTML += '<option value="' + sortOrders.sortOrderNames[i] + '">' + sortOrders.sortOrderTitles[i] + '</option>';
		}
	}
	sortHTML += '</select>';
	document.getElementById("videoDivHeaderSorting").innerHTML = sortHTML;
	document.getElementById("videoDivFooterSorting").innerHTML = sortHTML;
	
	var pageLinksHTML = "";
	var firstPageHTML = "";
	var prevPageHTML = "";
	var nextPageHTML = "";
	var lastPageHTML = "";

	if(results.$total == 0)
	{
		document.getElementById("videoRightColResults").innerHTML = "";
		document.getElementById("videoDivHeaderSorting").innerHTML = "";
		document.getElementById("videoDivFooterSorting").innerHTML = "";
		document.getElementById("videoDivHeaderPagination").innerHTML = "";
		document.getElementById("videoDivFooterPagination").innerHTML = "";
		document.getElementById("videoBottomLinksLeft").className = "videoBottomLinksLeft videoBottomLinksLeftHidden";
		document.getElementById("videoDiv").innerHTML = "<p>No videos found.</p>";
	}
	else
	{
		if(results.$total > results.video.length)
		{
			var resultPages = Math.ceil(results.$total / msnVideoConfig.pageSize);
			var currentPage = (msnVideoConfig.pageSize + msnVideoConfig.offsetValue - 1) / msnVideoConfig.pageSize;

			// Number of pages with search results to display (2-5)
			var displayPages = (resultPages > 5 ? 5 : resultPages);
			if(currentPage >= 10)
			{
				displayPages = 3;
			}
			var pages = new Array(displayPages);
			
			var startIndex = currentPage - 2; // normal case
			if(displayPages == 3) // Special case if only 3 pages are to be displayed
			{
				startIndex = currentPage - 1
			}
			if(currentPage <= 3) // special case for first 3 pages
			{
				startIndex = 1;
			}
			else // special case for last 2 pages
			{
				if(currentPage == resultPages - 1)
				{
					startIndex = currentPage - (displayPages - 2);
				}
				else if(currentPage == resultPages)
				{
					startIndex = currentPage - (displayPages - 1);
					if(startIndex < 1)
					{
						startIndex = 1;
					}
				}
			}
			
			for(var i=startIndex; i<startIndex+pages.length; i++)
			{
				var pageLink = "";
				if(i == currentPage)
				{
					pageLink = '<div class="pageNumber pageNumberSelected">' + i + '</div>';
				}
				else
				{
					pageLink = '<div class="pageNumber" onclick="changePage(' + (i - currentPage) + ');">' + i + '</div>';
				}
				pageLinksHTML += pageLink;
			}			

			if((msnVideoConfig.offsetValue + results.video.length - 1) < results.$total)
			{
				nextPageHTML = '<div class="nextPage" onclick="changePage(1);"></div>';
				lastPageHTML = '<div class="lastPage" onclick="changePage(\'last\');"></div>';
			}
			if(msnVideoConfig.offsetValue > 1)
			{
				firstPageHTML = '<div class="firstPage" onclick="changePage(\'first\');"></div>';
				prevPageHTML = '<div class="prevPage" onclick="changePage(-1);"></div>';
			}

			var pagesHTML =
			'<span>Page:</span>' + firstPageHTML + prevPageHTML + 
			'<div class="pageNumbers">' + pageLinksHTML + '</div>' + nextPageHTML + lastPageHTML;

			document.getElementById("videoDivHeaderPagination").innerHTML = pagesHTML;
			document.getElementById("videoDivFooterPagination").innerHTML = pagesHTML;
		}
		else // One page only
		{
			document.getElementById("videoDivHeaderPagination").innerHTML = "";
			document.getElementById("videoDivFooterPagination").innerHTML = "";
		}
		document.getElementById("videoRightColResults").innerHTML = "Results: " + msnVideoConfig.offsetValue + "&ndash;" + (msnVideoConfig.offsetValue + results.video.length - 1) + " of " + results.$total;

		// Create RSS link
		var rssLink = "";
		if(msnVideoConfig.resultsType == "search")
		{
			rssLink = "http://edge1.catalog.video.msn.com/search.aspx?mk=" + msnVideoConfig.mkt + "&" + msnVideoConfig.params + "&q=" + msnVideoConfig.query + "&ind=" + msnVideoConfig.offsetValue + "&sf=" + msnVideoConfig.sortOrder + "&sd=" + msnVideoConfig.sortDirection + "&ps=" + msnVideoConfig.pageSize + "&responseEncoding=rss&title=" + escape("ninemsn Video: " + msnVideoConfig.tabName);
		}
		else
		{
			rssLink = "http://edge1.catalog.video.msn.com/videoByTag.aspx?mk=" + msnVideoConfig.mkt + "&" + msnVideoConfig.params + "&ind=" + msnVideoConfig.offsetValue + "&sf=" + msnVideoConfig.sortOrder + "&sd=" + msnVideoConfig.sortDirection + "&responseEncoding=rss&title=" + escape("ninemsn Video: " + msnVideoConfig.tabName);
		}
		document.getElementById("videoBottomLinksLeft").className = "videoBottomLinksLeft";
		document.getElementById("videoBottomLinksLeft").innerHTML = '<a href="' + rssLink + '">Get ' + msnVideoConfig.tabName + ' as RSS</a>';
	}
}

// This function is called by the video player SWF object when a new video is loaded
// Function changed to use new MSN naming
Msn.Video.OnVideoTitle = function(text, id)
{
	injectJSON("http://edge1.catalog.video.msn.com/videoByUuid.aspx?uuid=" + document.getElementById("MSNVideoPlayer_pobj").vidGetId() + "&responseEncoding=json&callbackName=getDescription");
	flashTitle = text;
	
	var currentSite = window.location.hostname.substr(0,window.location.hostname.indexOf('.'));
	if (currentSite.toLowerCase() == "today")  //  show email link for today.ninemsn.com.au
	{
		$("#" + id + "_t").html(text);
		$("#" + id + "_mail").html("E-mail '" + text + "' video to your friends and family");
		$("#" + id + "_mail").show();
		if(text == "Advertisement")
		{
			$("#" + id + "_mail").hide();
		}
		if(!isMSNVideoClickEnabled)
		{
			$("#" + id + "_mail").click(function()
			{
				var vidObj = document.getElementById(id + "_pobj");
				if(vidObj)
				{
					var link = (window.location.protocol + "//" + window.location.hostname + window.location.pathname + window.location.search).toLowerCase();

					//first, get rid of any existing videoid QS parameter
					var startVideoId = link.indexOf("videoid=");
					if(startVideoId > -1)
					{
						var endVideoId = link.indexOf("&", startVideoId);
						var qsToRemove = link.substring(startVideoId - 1, (endVideoId == -1 ? link.length : endVideoId));
						link = link.replace(qsToRemove, "");
						
						//Next, fix the url to have a leading ? before any & in the QS
						var firstInstanceOfAnd = link.indexOf("&");
						var firstInstanceOfQuestionMark = link.indexOf("?");
						if(firstInstanceOfAnd < firstInstanceOfQuestionMark || (firstInstanceOfQuestionMark == -1 && firstInstanceOfAnd > -1))
						{
							link = link.replace("&", "?");
						}
					}
					
					//Construct new URL
					link = escape(link + (link.indexOf("?") > -1 ? "&" : "?") + "videoid=" + vidObj.vidGetId());
					window.location = "mailto:?subject=" + vidObj.vidGetTitle() + "&body=This video appears in news.ninemsn.com.au and I thought you should see it. " + link + "%0A%0AIf you cannot click on the link above, copy and paste the entire address below into your web browser." + link + "%0A%0AFor all the latest news and entertainment from TODAY, visit: %0Ahttp%3A//today.ninemsn.com.au";
				}
			});
			isMSNVideoClickEnabled = true;
		}
	}
}

// function OnAdLoaded(adData) has been moved to msn_inline_channels.js ! IMPORTANT
// This functions is called by the video player SWF object when a new ad is loaded

function playVideo(index)
{
	document.getElementById("MSNVideoPlayer_pobj").vidPlayId(msnVideoConfig.results.video[index].uuid.$);
}

function formatDate(dateString)
{
	var videoDateArray = dateString.substring(0,10).split('-');
	return videoDateArray[2] + "/" + videoDateArray[1] + "/" + videoDateArray[0].substring(2,4);
}

/**
 * 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 srcImgCallback(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";
	}
}

function getDescription(currentVideo)
{
	// Video description text
	var videoDateString = formatDate(currentVideo.startDate.$);
	var videoDescriptionString = replaceAll(currentVideo.description.$, "\"", "&quot;");
	videoDescriptionString = replaceAll(videoDescriptionString, ">", "&gt;");
	videoDescriptionString = replaceAll(videoDescriptionString, "<", "&lt;");
	var videoDescriptionHTML = 
	'<div id="videoDescriptionText" class="videoDescriptionText">' +
		'<p>' + videoDescriptionString + '</p>' +
		'<p>' + currentVideo.usage.usageItem[0].$totalCount + ' views since ' + videoDateString + '</p>' +
	'</div>';

	// Related links (displayed in two columns)
	var videoRelatedLinksHTML = '<div id="videoRelatedLinks" class="videoRelatedLinks videoRelatedLinksHidden">';
	if(currentVideo.extendedXml && typeof(currentVideo.extendedXml.relatedLinks == "object"))
	{
		videoRelatedLinksHTML += '<ul>';
		if(typeof(currentVideo.extendedXml.relatedLinks.link.$url) != "undefined")
		{
			// One link only
			videoRelatedLinksHTML += '<li><a href="' + currentVideo.extendedXml.relatedLinks.link.$url  +'">' +	currentVideo.extendedXml.relatedLinks.link.$ + '</a></li>';
		}
		else
		{
			for(var i=0; i<currentVideo.extendedXml.relatedLinks.link.length; i++)
			{
				if(i < 2) // Links 1-2
				{
					videoRelatedLinksHTML += '<li><a href="' + currentVideo.extendedXml.relatedLinks.link[i].$url  +'">' +	currentVideo.extendedXml.relatedLinks.link[i].$ + '</a></li>';
				}
			}
			if(currentVideo.extendedXml.relatedLinks.link.length > 2) // Links 3-4
			{
				videoRelatedLinksHTML += '</ul><ul>';
				for(var i=currentVideo.extendedXml.relatedLinks.link.length-1; i<currentVideo.extendedXml.relatedLinks.link.length; i++)
				{
					videoRelatedLinksHTML += '<li><a href="' + currentVideo.extendedXml.relatedLinks.link[i].$url  +'">' + currentVideo.extendedXml.relatedLinks.link[i].$ + '</a></li>';
				}
			}
		}
		videoRelatedLinksHTML += '</ul>';
	}
	else // no related links
	{
		videoRelatedLinksHTML += '<p>This video does not have any related links associated with it.</p>';
	}
	videoRelatedLinksHTML += '</div>';

	// Email, blog, video link and IM This links
	var videoLinkURL = "";
	if(window.location.search.indexOf("?") > -1)
	{
		videoLinkURL = window.location.href.substring(0, window.location.href.indexOf("?")) + "?videoid=" + currentVideo.uuid.$ + "&tab=" + msnVideoConfig.activeTab;
	}
	else
	{
		videoLinkURL = window.location.href + "?videoid=" + currentVideo.uuid.$ + "&tab=" + msnVideoConfig.activeTab;
	}
		
	var mailtoLinkURL = 'mailto:?subject=' + escape('Check out this video I found on ninemsn!') + '&body=' + escape(currentVideo.title.$) + escape('\n\r') + escape(videoLinkURL);
	var videoThumbnailSrc = getThumbnailUrl(currentVideo);
	var videoSpacesURL = 'http://spaces.live.com/BlogIt.aspx?Title=' + escape(currentVideo.title.$) + '&SourceURL=' + escape(videoLinkURL) + '&description=' + escape('<p><img src="' + videoThumbnailSrc + '" alt="" /></p>') + escape('<p>' + videoDescriptionString + '</p>');
	this.BlogIt = function(){window.open(videoSpacesURL);};
	this.Email = function(){window.location.href = mailtoLinkURL;};
	this.VideoLink = function(){window.open(videoLinkURL);};
	this.IMThis = function()
	{
		try
		{
			obj = new ActiveXObject("MSNMessenger.P4QuickLaunch");
			var expMinutes = 5;
			var expires = new Date();
			expires.setTime(expires.getTime() + (expMinutes*60*1000));
			document.cookie = 'msnvideo_mediashare=' + currentVideo.uuid.$ + ';expires=' + expires.toGMTString() + ';domain=.ninemsn.com.au;path=/';
			obj.LaunchApp("99995288","");
		}
		catch(e)
		{
			alert("Sorry, your configuration does not support this feature.\nThe minimum requirements are MSN Messenger 6.0 or higher and Internet Explorer 5.5 or higher.");
		}
	};
	
	var videoIconsHTML = 
	'<div id="videoIcons">' +
		'<a href="javascript:Email();" class="videoEmailIcon" title="Email this video to a friend">Email</a>' +
		'<a href="javascript:BlogIt();" class="videoSpacesIcon" title="Blog about this video in your space">Send to spaces</a>' +
		'<a href="javascript:VideoLink();" class="videoLinkIcon" title="Get a direct link to this video">Video link</a>';
		if(typeof(ActiveXObject) == "function")
		{
			videoIconsHTML += '<a href="javascript:IMThis();" class="videoIMIcon" title="Send this video to a friend with Windows Live Messenger">IM this</a>';
		}
	videoIconsHTML += '</div>';

	// Source image
	var sourceImageHTML =
	'<img style="visibility:hidden;" id="srcVidImgLogo" src="http://img.video.msn.com/video/i/src/' + currentVideo.source.$ + '.gif" alt="' + currentVideo.source.$friendlyName + '" />' +
	'<h1>' + limitString(currentVideo.title.$, 30) + '</h1>' +
	'<div id="videoRelatedLinksButton" class="videoRelatedLinksButton" onclick="showRelatedLinks();">Related links</div>' +
	'<div id="videoDescriptionButton" class="videoDescriptionButton videoDescriptionButtonActive" onclick="showDescription();">Description</div>';

	// Render the HTML
	document.getElementById("videoDescriptionDiv").innerHTML = sourceImageHTML + videoDescriptionHTML + videoRelatedLinksHTML + videoIconsHTML;
	
	//Make call to fetch content source image
	injectJSON("http://edge1.catalog.video.msn.com/getcontentsource.aspx?csid=au_ninemsn&name=" + currentVideo.source.$ + "&responseEncoding=json&callbackName=srcImgCallback");
}

function showRelatedLinks()
{
	document.getElementById("videoDescriptionText").className = "videoDescriptionText videoDescriptionTextHidden";
	document.getElementById("videoRelatedLinks").className = "videoRelatedLinks";
	document.getElementById("videoDescriptionButton").className = "videoDescriptionButton";
	document.getElementById("videoRelatedLinksButton").className = "videoRelatedLinksButton videoRelatedLinksButtonActive";
}
function showDescription()
{
	document.getElementById("videoDescriptionText").className = "videoDescriptionText";
	document.getElementById("videoRelatedLinks").className = "videoRelatedLinks videoRelatedLinksHidden";
	document.getElementById("videoDescriptionButton").className = "videoDescriptionButton videoDescriptionButtonActive";
	document.getElementById("videoRelatedLinksButton").className = "videoRelatedLinksButton";
}

/**
 * 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 getThumbnailUrl(videoData)
{
	var videoThumbnailSrc = "";
	var resizerUrl = "";
		
	if (!strImageSize)
	{
		resizerUrl = "http://images.ninemsn.com.au/resizer.aspx?width=92&url=";
	}
	else
	{
		resizerUrl = "http://images.ninemsn.com.au/resizer.aspx?width=" + strImageSize + "&url=";
	}
	
	if(videoData && videoData.files && videoData.files.file)
	{
		for(var i = 0; i < videoData.files.file.length; i++)
		{
			var imgFile = videoData.files.file[i];
			if(imgFile.$formatCode == "2001")
			{//if 2001 format is found, use it with the resizer
				videoThumbnailSrc = resizerUrl + escape(imgFile.uri.$);
				break;
			}
			else if((imgFile.$formatCode == "2009" || imgFile.$formatCode == "2007") && (imgFile.uri.$.toLowerCase().indexOf("catalog.video.msn.com/image.aspx") == -1))
			{//if 2007 or 2009 format is found and the location is on netshow, use it with the resizer
				videoThumbnailSrc = resizerUrl + escape(imgFile.uri.$);
				break;
			}
		}

		if(!videoThumbnailSrc && videoData.providerId && videoData.providerId.$)
		{//couldn't find suitable thumbnail, construct it manualy
			videoThumbnailSrc = resizerUrl + buildVideoPath(videoData);
		}
	}

	return videoThumbnailSrc;
}

function buildVideoPath(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 = insertString(result, 9, "/");
	result = insertString(result, 6, "/");
	result = insertString(result, 3, "/");
	result = insertString(result, 0, "/");

	return base + result + pid + extension;
}

function insertString(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;
}