if(!window.Fix)
{
	window.Fix={};
}

Fix.Video = new function()
{
	var me=this;
	var intDayCount = 0;
	var thumbDefaultSize = 116;
	var msnVideoConfig =
	{
		"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 imgAssetConfig =
	{
		"arrow_cover" : "/static/images/video/arrow_cover.png",
		"playing" : "/static/common/images/video/playing_grey.gif"
	}	
	
	// Injects json as a script tag. This is needed as server is on external domain and doesn't support jsonp
	this.InjectJSON = function(url)
	{
		var script = document.createElement("script");
		script.type = "text/javascript";
		script.src = url;
		script.id = "jsonScript";
		if(msnVideoConfig.videoResults)
		{
			$('head')[0].removeChild($("#jsonScript"));
		}
		$('head')[0].appendChild(script);
	};	
	
	// Event handler for tab click
	this.SelectTab = function(element, params, playOnLoad)
	{
		if(element)
		{
			var tabLinks = $("#videoTabs li").removeClass();
			var tabName = $(element).children("a")[0].title;	
			
			for(var i=0; i<tabLinks.length; i++)
			{
				if(tabLinks[i] == element)
				{
					msnVideoConfig.activeTab = i+1;
				}
			}
	
			$(element).addClass("selected");
			$("#videoDivTop h3").text("Latest " + tabName + " videos");
			
			msnVideoConfig.tabName = tabName;
			msnVideoConfig.currentIdIndex = -1; //reset the currently index that is playing
			
			this.LoadVideos(params, playOnLoad);
			
		}	
	};
	
	//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
	this.LoadVideos = function(params, playOnLoad)
	{
		if(params)
		{
			this.SetLoading('#videoDiv');

			$("#videoTabsMinor, #videoDivFooterPagination").html("");

			msnVideoConfig.resultsType = "videobytag";
			msnVideoConfig.params = params;
			msnVideoConfig.offsetValue = 1;
			msnVideoConfig.pageSize = 50;
	
			if(msnVideoConfig.tabData[msnVideoConfig.activeTab - 1])
			{
				//data for this tab has already been fetched
				this.LoadVideosCallback(msnVideoConfig.tabData[msnVideoConfig.activeTab - 1], playOnLoad);
			}
			else
			{
				//get the data from the catalog
				this.InjectJSON("http://edge2.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=Fix.Video.LoadVideosCallback" + (playOnLoad ? "&cd=" + playOnLoad : ""));
			}
		}
	};
	
	// Renders the main portion of the video tabs given the results
	this.LoadVideosCallback = function(results, playOnLoad)
	{
		if(results)
		{
			msnVideoConfig.todayVidCount = 0;
			msnVideoConfig.results = results;
			msnVideoConfig.tabData[msnVideoConfig.activeTab - 1] = results;		
			var vidDiv = document.getElementById("videoDiv");		
			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(msnVideoConfig.resultsType == "search")
				{//if search is in progress, display only top 6 results in main section
					if(msnVideoConfig.todayVidCount >= 6)
					{
						break;
					}
				}
				else
				{
					var videoDateString = formatDate(results.video[i].startDate.$);	
					if(i == 0)
					{
						mostRecentVideoDate = videoDateString;
						$("#videoRightColDate").html(formatDate(results.video[i].startDate.$,'MDY'));
					}
					else if(mostRecentVideoDate != videoDateString)
					{//Video is past the most recent date, no need to proceed
						break;
					}
				}
					
				vidDiv.innerHTML += this.GetVideoItemHTML(results.video[i], i);
				msnVideoConfig.todayVidCount++;
			}	
				
			if(results.$total == 0)
			{
				$("#videoRightColDate, #videoDivFooterPagination, #videoTabsMinor").html("");
				$("#videoDiv").html("<p class=\"novideo\">No videos found.</p>");
			}
			else
			{
				var currentYear = (new Date()).getFullYear();			
				if(playOnLoad)
				{
					//if tab is specified in query string, play first video for that tab
					this.PlayVideo(0);
				}	
	
				if(results.$total > 6)
				{
					//fetch more in the minor tabs
					msnVideoConfig.pageSize = 6;
					msnVideoConfig.offsetValue = msnVideoConfig.todayVidCount + 1;
					//Next, fetch the next six videos for the pagination section
					this.LoadMinorVideos()
				}
				else
				{
					$("#videoDivFooterPagination, #videoTabsMinor").html("");
				}
			}
			this.AttachAnnimationEvents();
		}		
	};
	
	// Renders the extra portion of the videos
	this.LoadMinorVideos = function()
	{
		this.SetLoading('#videoTabsMinor');
	
		if(msnVideoConfig.resultsType == "search")
		{
			this.InjectJSON("http://edge2.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=Fix.Video.PagingSectionCallback");
		}
		else if(msnVideoConfig.resultsType == "videobytag")
		{
			this.InjectJSON("http://edge2.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=Fix.Video.PagingSectionCallback");
		}
	};	
	
	// Sets loading status for html element
	this.SetLoading = function(el)
	{
		$(el).html("<p class=\"loading\">Loading videos...</p>");	
	};
	
	// Pagination event handler
	this.ChangePage = function(delta)
	{	
		msnVideoConfig.offsetValue = ((delta - 1) * msnVideoConfig.pageSize) + msnVideoConfig.todayVidCount + 1;
		this.LoadMinorVideos();
	};
	
	// Paging callback event
	this.PagingSectionCallback = function(results)
	{
		if(results.video.length > 0)
		{
			var strDayToCompare = formatDate(results.video[0].startDate.$);			
			var videoDateMD = dateMD(results.video[0].startDate.$);
			var vidTabMinor = document.getElementById("videoTabsMinor");
			if(vidTabMinor)
			{
				vidTabMinor.innerHTML = "";
			}
	
			videoItemHTML = '<h5>' + videoDateMD + '</h5>';
			
			for(var i = 0; i < results.video.length; i++)
			{
				var currentVideo = results.video[i];
				var videoDateString = formatDate(currentVideo.startDate.$);	
				if(videoDateString != strDayToCompare)
				{
					intDayCount++;
					strDayToCompare = videoDateString;
					videoDateMD = dateMD(results.video[i].startDate.$);						 		
					videoItemHTML += '<h5>' + videoDateMD + ", " + msnVideoConfig.tabName  +'</h5>';				
				}			
				var videoDescriptionNoHtml = currentVideo.description.$.replaceAll("\"", "&quot;");
				var videoDescriptionNoHtml = videoDescriptionNoHtml.replaceAll(">", "&gt;");
				var videoDescriptionNoHtml = videoDescriptionNoHtml.replaceAll("<", "&lt;");
				var videoTitle = currentVideo.title.$.limit(20);						
				videoItemHTML +=
				'<div class="videoItem" onclick="Fix.Video.PlayVideoUUID(\'' + currentVideo.uuid.$ + '\');" >' +
					'<div class="playButton">Play</div>' + 
					'<span class="videoItemTitle" title="' + currentVideo.source.$friendlyName + '">' + currentVideo.source.$friendlyName + ':</span>' +
					'<span class="videoCaption" title="' + currentVideo.title.$ + '">' + currentVideo.title.$ + '</span>' +
					
				'</div>';
				vidTabMinor.innerHTML += videoItemHTML;
				videoItemHTML = '';	
			}
	
			this.RenderMinorPaging(results);
			this.AttachMinorTabEvents();
			
			//  fix for IE7 column heights
			document.getElementById("videoNav").style.height= 'auto';
			document.getElementById("videoPane").style.height = 'auto';
		}
	};
	
	// Tab event handlers 
	this.AttachMinorTabEvents = function()
	{
		$("#videoTabsMinor .videoItem").bind("mouseenter",function(){
			$(this).find(".videoItemTitle, .videoCaption, .playButton").css("text-decoration", "underline");
		});
		
		$("#videoTabsMinor .videoItem").bind("mouseleave",function(){
			$(this).find(".videoItemTitle, .videoCaption, .playButton").css("text-decoration", "none");
		});
		
		$("#videoTabsMinor .videoItem").click(function(){
			Fix.Video.HighlightMinorVideo(this);
		});		
	};
	
	// Builds the html for a video item
	this.GetVideoItemHTML = function(itemData, i)
	{
		var videoDescriptionNoHtml = itemData.description.$.replaceAll("\"", "&quot;");
		var videoDescriptionNoHtml = videoDescriptionNoHtml.replaceAll(">", "&gt;");
		var videoDescriptionNoHtml = videoDescriptionNoHtml.replaceAll("<", "&lt;");
		var videoTitle = itemData.title.$.limit(25);
		var videoThumbnailSrc = this.GetThumbnailUrl(itemData, 0);
		var	videoDescription = videoDescriptionNoHtml.limit(60);
				
		var videoItemHTML =
		'<div class="videoItem" id="videoItem_' + i + '" onclick="Fix.Video.PlayVideoUUID(\'' + itemData.uuid.$ + '\');">' +
			'<div class="itemImage">' +					
				'<img class="playingImg" src="' + imgAssetConfig.arrow_cover + '" />' +
				'<img class="videoImage" src="' + videoThumbnailSrc + '" alt="' + itemData.title.$ + '" title="' + itemData.title.$ + '" />' +
				'<div class="playFadeBG"></div>' +
			'</div>' +
			'<h4 title="' + itemData.title.$ + '">' + videoTitle + '</h4>' +
			'<p title="' + videoDescriptionNoHtml + '">' +
				'<img class="playingImg" src="' + imgAssetConfig.playing + '" />' + videoDescription + '<div class="playButton">Play</div>' +
			'</p>' +
		'</div>';				
		
		return videoItemHTML;
	};
	
	this.GetManualLinkHtml = function(link, i)
	{
		var html = 
		'<div id="videoItem_'+i+'" class="videoItem" title="'+link.title+'" onclick="Fix.Video.PlayVideoUUID(\'' + link.uuid.$ + '\');">' +
			'<img src="' + link.imgUrl + '" alt="' + link.title + '" />' +
			'<p>' + 
				link.title.limit(45) + 
			'</p>' +
			'<div class="playButton">Play</div>' +
		'</div>'; 
		
		return html;
	}	
	
	// Renders the paging for the minor video results
	this.RenderMinorPaging = function(results)
	{
		if(results.$total > results.video.length)
		{
			//paging is required
			var resultPages = Math.ceil((results.$total - msnVideoConfig.todayVidCount) / msnVideoConfig.pageSize);
			var currentPage = Math.ceil((msnVideoConfig.offsetValue - msnVideoConfig.todayVidCount) / msnVideoConfig.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="Fix.Video.ChangePage(' + i + ');">' + i + '</div>';
				}
				pageLinksHTML += pageLink;
			}			
			
			if(currentPage < resultPages)
			{
				nextPageHTML = '<div class="nextPrev" onclick="Fix.Video.ChangePage(' + parseInt(currentPage + 1) + ');">Next &gt;</div>';
			}
			else
			{
				prevPageHTML = '<div class="nextPrevInactive">Next &gt;</div>';
			}
	
			if((currentPage < resultPages - 1) && resultPages > displayPages)
			{
				lastPageHTML = '<div class="elipsees">...</div><div class="pageNumber" onclick="Fix.Video.ChangePage(' + resultPages + ');">' + resultPages + '</div>';
			}
	
			if(currentPage > 1)
			{//Only show PREV if not on the first page
				prevPageHTML = '<div class="nextPrev" onclick="Fix.Video.ChangePage(' + parseInt(currentPage - 1) + ');">&lt; Prev</div>';
			}
			else
			{
				prevPageHTML = '<div class="nextPrevInactive">&lt; Prev</div>';
			}
					
			if(currentPage > displayPages - 1)
			{
				firstPageHTML = '<div class="pageNumber" onclick="Fix.Video.ChangePage(1);">1</div><div class="elipsees">...</div>';				
			}
	
			var pagesHTML = '<div class="pageNumbers">' + prevPageHTML + firstPageHTML + pageLinksHTML + lastPageHTML + nextPageHTML + '</div>';
			document.getElementById("videoDivFooterPagination").innerHTML = pagesHTML;
		}
		else // One page only
		{
			document.getElementById("videoDivFooterPagination").innerHTML = "";
		}
	};		
	
	this.RenderManualLinks = function(data) 
	{
		var html = "";
		for(var i = 0; i < data.length; i++)
		{
			html += this.GetManualLinkHtml(data[i], i);
		}
		html += '<div class="clear"></div>';
		$("#vidManualLinks").removeClass("loading").addClass("loaded").html(html);
	
		$("#vidManualLinks .videoItem").click(function(){
			
			Fix.Video.HighlightMinorVideo(this);
			
			var indexPosition = $(this).parent().find(".videoItem").index(this);
			document.getElementById("MSNVideoPlayer_pobj").vidPlayId(data[indexPosition].uuid);
		});
	}	
	
	// Attaches animation events for video items
	this.AttachAnnimationEvents = function()
	{
		$("#videoDiv .videoItem").bind("mouseenter",function(){
			
			if(this.className.indexOf("selected") == -1)
			{
				$(this).find(".itemImage .playFadeBG").css("z-index", 3);
				//$(this).find("h4, .playButton").css("text-decoration", "underline");			
			}
			
		});
		
		$("#videoDiv .videoItem").bind("mouseleave",function(){
			
			if(this.className.indexOf("selected") == -1)
			{
				$(this).find(".itemImage .playFadeBG").css("z-index", 1);
				//$(this).find("h4, .playButton").css("text-decoration", "none");
			}

		});

		$("#videoDiv .videoItem").click(function(){
			Fix.Video.HighlightVideo(this);
		});
	
	};
	
	// Highlights a selected video item
	this.HighlightVideo = function(element)
	{
		$(document).ready(function(){
			var jElem = $(element);
			if(!jElem.hasClass("selected"))
			{
				Fix.Video.CloseSelectedVideo();
				Fix.Video.OpenSelectedVideo(jElem);
			}
		});
	};
	
	// Closes any other selected video items
	this.CloseSelectedVideo = function()
	{
		var animationTime = 200;
		// main videos 
		
		//move image arrow
		$("#videoDiv .itemImage .playingImg").animate({"left":"-26px"}, animationTime, "swing");
		//move text arrow
		$("#videoDiv p .playingImg").animate({"marginLeft":"-83px"}, animationTime, "swing");
		//display play button
		$("#videoDiv .playButton").show();
		$("#videoDiv .itemImage .playFadeBG").css("z-index", 1);
		// remove selected class
		$("#videoDiv .videoItem").removeClass("selected");
		
		// minor/manual videos
		//display play button
		$("#videoTabsMinor .playButton, #vidManualLinks .playButton").show();;
		// remove selected class
		$("#videoTabsMinor .videoItem, #vidManualLinks .videoItem").removeClass("selected");
		
	};
	
	// Open selected video item
	this.OpenSelectedVideo = function(item)
	{
		var animationTime = 200;
		//move image arrow
		item.find(".itemImage .playingImg").animate({"left":"0"}, animationTime, "swing");
		//move text arrow
		item.find("p .playingImg").animate({"marginLeft":"-10px"}, animationTime, "swing");
		//remove play button
		item.find(".playButton").hide();
		item.find(".playFadeBG").css("z-index", 3);
		//change style
		item.addClass("selected");
	}

	// Highlights a selected video item
	this.HighlightMinorVideo = function(element)
	{
		$(document).ready(function(){
			var jElem = $(element);
			if(!jElem.hasClass("selected"))
			{
				Fix.Video.CloseSelectedVideo();
				Fix.Video.OpenSelectedMinorVideo(jElem);
			}
		});
	};		

	// Open selected video item
	this.OpenSelectedMinorVideo = function(item)
	{
		var animationTime = 200;
		//remove play button
		//item.find(".playButton").hide();
		//change style
		item.addClass("selected");
	}	
	
	//Given the index position, plays a video that is in the current results set
	this.PlayVideo = function(index)
	{
		msnVideoConfig.currentIdIndex = index;
		this.PlayVideoUUID(msnVideoConfig.results.video[index].uuid.$);
	};
	
	//Given the UUID of a specific video, plays that video in the video player
	this.PlayVideoUUID = function(uuid)
	{
		$(document).ready(function(){
			var msnVidObj = document.getElementById("MSNVideoPlayer_pobj");	
			if(msnVidObj)
			{
				if(typeof(msnVidObj.vidPlayId) == "function")
				{
					msnVideoConfig.uuid = uuid;
					msnVidObj.vidPlayId(uuid);
				}
			}			
		});
	};	
	
	this.InitManualLinks = function(vidManualLinksUUIDs){
		
		if(vidManualLinksUUIDs.length == 0)
		{
			$("#manualLinks").hide();
			return;
		}
		
		
		$.getJSON("http://edge2.catalog.video.msn.com/videoByUuids.aspx?uuids=" + vidManualLinksUUIDs + "&responseEncoding=json&callbackName=?", function(data){
			if (data && data.video) {
				var vidManualLinks = new Array();
				var list = data.video;
				for (var i = 0; i < list.length; i++) 
				{
					vidManualLinks[i] = {title: list[i].title.$,uuid: list[i].uuid,imgUrl: ''};
					Fix.Video.UpdateVideoData(vidManualLinks[i], list[i]);
				}
			}
			Fix.Video.RenderManualLinks(vidManualLinks);
		});
	}
	
	this.UpdateVideoData = function(data, videoItem)
	{
		data.imgUrl = data.imgUrl ? data.imgUrl : this.GetThumbnailUrl(videoItem, 0, 145);
	}	
	
	// Gets resized thumbnail url
	this.GetThumbnailUrl = function(videoData, hlCatId, width)
	{
		var videoThumbnailSrc = "";
		var thumbSize = width ? width : thumbDefaultSize;
		
		var resizerUrl = "http://images.ninemsn.com.au/resizer.aspx?width=" + thumbSize + "&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") == -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 dateMD(date)
{
	var videoDateMD = '';
	var videoDateMDY = formatDate(date, 'MDY');
	videoDateMD = videoDateMDY.substr(0, videoDateMDY.indexOf(','));
	return videoDateMD;
}

function formatDate(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]) - 1, videoDateArray[2]);
	videoDate.setUTCHours(videoTimeArray[0], videoTimeArray[1]);
	if(MDY)
	{
		return months[videoDate.getMonth()] + ' ' + videoDate.getDate() + ', ' + videoDateArray[0];		
	}
	else
	{
		return getDateTh(videoDate.getDate()) + " " + months[videoDate.getMonth()];
	}	
}

//Returns the extension to a number (this is one of "*1st", "*2nd", "*3rd" or "*th"
function getDateTh(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;
}

