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 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 (msnVideoConfig.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("videoTabs_rhc").getElementsByTagName("li");
    for (var i = 0; i < tabLinks.length; i++) {
      if (!region || i != (tabLinks.length - 1)) {
        tabLinks[i].className = "";
      }
    }

    tabLinks = document.getElementById("videoTabs_rhc").getElementsByTagName("li");

    for (var i = 0; i < tabLinks.length; i++) {
      if (tabLinks[i] == element) {
        msnVideoConfig.activeTab = i + 1;
      }
    }

    element.className = "selected";
    msnVideoConfig.tabName = element.title;
    msnVideoConfig.currentIdIndex = -1; //reset the currently index that is playing
  }
}

function selectTab6PMToday(element) {
  selectTabToday(element, msnVideoConfig.catRegion);
  loadVideosToday('ns=MSNVideo_Cat&tag=' + msnVideoConfig.catTag);
}

function selectTabNumToday(tabNumber) {
  selectTabToday(document.getElementById("videoTabs_rhc").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) {
    msnVideoConfig.resultsType = "videobytag";
    msnVideoConfig.params = params;
    document.getElementById("videos").innerHTML = "<p class='loading'>Loading videos...</p>";
    msnVideoConfig.offsetValue = 1;
    msnVideoConfig.pageSize = 5; // this config determins how many videos will be returned

    if (msnVideoConfig.tabData[msnVideoConfig.activeTab - 1]) {//data for this tab has already been fetched
      jsonCallbackToday(msnVideoConfig.tabData[msnVideoConfig.activeTab - 1], playOnLoad);
    }
    else {//get the data from the catalog
      injectJSONToday("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=jsonCallbackToday" + (playOnLoad ? "&cd=" + playOnLoad : ""));
    }
  }
}

function loadMinorVideosToday() {
  var vidTabMinor = document.getElementById("videoTabsMinor");
  if (vidTabMinor) {
    vidTabMinor.innerHTML = "<p class='loading'>Loading videos...</p>";
  }

  if (msnVideoConfig.resultsType == "search") {
    injectJSONToday("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=jsonCallbackPagingSectionToday");
  }
  else if (msnVideoConfig.resultsType == "videobytag") {
    injectJSONToday("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=jsonCallbackPagingSectionToday");
  }
}

function changePageToday(delta) {
  msnVideoConfig.offsetValue = ((delta - 1) * msnVideoConfig.pageSize) + msnVideoConfig.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("videoTabs_rhc");
  if (currentTabs) {
    currentTabs.innerHTML = searchTabString + currentTabs.innerHTML;
  }

  selectTabNumToday(0);
  maxDist = countLiNodesToday();  //  works out how far to the left to animate the Ent tabs	
  msnVideoConfig.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");
      msnVideoConfig.query = query.value;
    }
    else {
      msnVideoConfig.query = searchString;
    }

    msnVideoConfig.resultsType = "search";
    msnVideoConfig.tabName = "Search results";
    msnVideoConfig.params = "ns=MSNVideo_Cat&tag=AUnationalninenews";
    document.getElementById("videos").innerHTML = "<p class='loading'>Searching for videos...</p>";
    document.getElementById("videosFooter").innerHTML = "Search results videos continue below";
    msnVideoConfig.offsetValue = 1;
    msnVideoConfig.pageSize = 5;

    //Then call the JSON service for search
    if (msnVideoConfig.tabData[msnVideoConfig.activeTab - 1]) {//data for this tab has already been fetched
      jsonCallbackToday(msnVideoConfig.tabData[msnVideoConfig.activeTab - 1]);
    }
    else {//get the data from the catalog
      injectJSONToday("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=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();
  }
}

function attachMinorTabEventsToday() {
  $("#videoTabsMinor .videoItem").bind("mouseenter", function() {
    $(this).css("background-color", "#4C4C4E");
    $(this).find(".videoItemTitle, .videoCaption, .playButton").css("text-decoration", "underline");
  });

  $("#videoTabsMinor .videoItem").bind("mouseleave", function() {
    $(this).css("background-color", "#4C4C4E");
    $(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 - 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="changePageToday(' + i + ');">' + i + '</div>';
      }
      pageLinksHTML += pageLink;
    }

    if (currentPage < resultPages) {
      nextPageHTML = '<div class="pageNext" onclick="changePageToday(' + parseInt(currentPage + 1) + ');">Next &gt;</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="pagePrev" onclick="changePageToday(' + parseInt(currentPage - 1) + ');">&lt; 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) {
    msnVideoConfig.todayVidCount = 0;
    msnVideoConfig.results = results;
    msnVideoConfig.tabData[msnVideoConfig.activeTab - 1] = results;
    var vidDiv = document.getElementById("videos");
    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 5 results in main section
        if (msnVideoConfig.todayVidCount >= 5) {
          break;
        }
      }
      else {
        var videoDateString = formatDateToday(results.video[i].startDate.$);
        if (i == 0) {
          mostRecentVideoDate = videoDateString;
        }
        else if (mostRecentVideoDate != videoDateString) {//Video is past the most recent date, no need to proceed
          break;
        }
      }

      vidDiv.innerHTML += getVideoItemHTMLToday(results.video[i], i);
      msnVideoConfig.todayVidCount++;
    }

    if (results.$total == 0) {
      document.getElementById("videoTabsMinor").innerHTML = "";
      document.getElementById("videos").innerHTML = "<p>No videos found.</p>";
      document.getElementById("videosFooter").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 > 5) {
        //fetch more in the minor tabs
        msnVideoConfig.pageSize = 5;
        msnVideoConfig.offsetValue = msnVideoConfig.todayVidCount + 1;
        //Next, fetch the next six videos for the pagination section
        loadMinorVideosToday()
      }
      else {
        document.getElementById("videoDivPagination").innerHTML = "";
        document.getElementById("videoTabsMinor").innerHTML = "";
        document.getElementById("videosFooter").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/video/transparent_arrow.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/video/transparent_arrow.png" />' + 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 = msnVideoConfig.tabData[msnVideoConfig.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 < msnVideoConfig.todayVidCount) {
        msnVideoConfig.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]) - 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
    {
      msnVideoConfig.catTag = "aubrisbane";
      catTitle = "Brisbane";
      msnVideoConfig.catRegion = "Bris";

    }
    else if (regionCode == "02")//NSW
    {
      msnVideoConfig.catTag = "ausydney";
      catTitle = "Sydney";
      msnVideoConfig.catRegion = "Syd";

    }
    else//default to VIC for all else
    {
      msnVideoConfig.catTag = "aumelbourne";
      catTitle = "Melbourne";
      msnVideoConfig.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() {
    if (this.className.indexOf("selected") == -1) {
      $(this).css("background-color", "4C4C4E");
      $(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", "#4C4C4E");
    }
    $(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").css("left", "-26px");
  //move text arrow
  $(".videoTabs .videoText .playingImg").css("margin-left", "-77px");
  //remove play button
  $(".videoTabs .playButton").show();
  //change style
  $(".videoTabs .videoItem").css("background-color", "#4C4C4E");
  $(".videoTabs .videoItem .videoTitle, .videoIndexRight .videoItem .videoText").css("color", "#CCCCCE");
  $(".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", "#000000");
  item.find(".videoTitle, .videoText").css("color", "#ffffff");
}

//Given the index position, plays a video that is in the current results set
function playVideoToday(index) {
  //alert(index);
  //alert('MSNVideoPlayer_a ' + MSNVideoPlayer_a.innerHTML);
  msnVideoConfig.currentIdIndex = index;
  playerStatus = 3;
  playVideoUUIDToday(msnVideoConfig.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") {
        msnVideoConfig.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);
}

//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 = msnVideoConfig.currentIdIndex + 1;
        if (newIndex >= msnVideoConfig.todayVidCount) {
          newIndex = 0;
        }
      }
      playVideo(newIndex);
    }
} */







