var sportsArray = new Array();
    sportsArray[0] = "ns=MSNVideo_Cat&tag=AUSportsGeneral-tabLatest";
    sportsArray[1] = "ns=MSNVideo_Cat&tag=AUAFL-tabAfl";
    sportsArray[2] = "ns=MSNVideo_Cat&tag=AUbaggygreen-tabCricket";
    sportsArray[3] = "ns=MSNVideo_Cat&tag=AULeague-tabLeague";
    sportsArray[4] = "ns=MSNVideo_Cat&tag=AUUnion-tabUnion";
    sportsArray[5] = "ns=MSNVideo_Cat&tag=AUFootball-tabFootball";
    sportsArray[6] = "ns=MSNVideo_Cat&tag=AUTennis-tabTennis";
    sportsArray[7] = "ns=MSNVideo_Cat&tag=AUGolf-tabGolf";
    sportsArray[8] = "ns=MSNVideo_Cat&tag=AUBasketball-tabBasketball";
    sportsArray[9] = "ns=MSNVideo_Cat&tag=AUHorseRacing-tabHorse";
    sportsArray[10] = "ns=MSNVideo_Cat&tag=AUMotorsport-tabMotorsport";
    sportsArray[11] = "ns=MSNVideo_Cat&tag=AUCycling-tabCycling";
    sportsArray[12] = "ns=MSNVideo_Cat&tag=AUSurfing-tabSurfing";
    sportsArray[13] = "ns=MSNVideo_Cat&tag=AUFootballWorldCup-tabWinter";
    sportsArray[14] = "ns=MSNVideo_Cat&tag=AUwwostv-tabTV";

    var tabNumber = queryString('tab');
    if ((tabNumber > 0) && (tabNumber < sportsArray.length + 1)) {
        var split = sportsArray[tabNumber - 1].split("-");
        var VIDEO_INITIAL_OVERRIDE = split[0];
    }

    $(document).ready(function() {

        var tabNumber = queryString('tab');
        var vidID = queryString('videoid'); 

       if(vidID != '')
       {}
       else if ((tabNumber > 0) && (tabNumber < sportsArray.length + 1)) {
            var split = sportsArray[tabNumber - 1].split("-");
           if (tabNumber == 14) {
             addTabsImages();
            }
            selectTab(split[1]);
            loadVideos(split[0]);
        }
        else {
            var split = sportsArray[0].split("-");
            selectTab(split[1]);
            loadVideos(split[0]);
        }

    $("#linkLatest").click(function() {
        removeTabImages();
		selectTab("tabLatest");
        replaceADCalls("latest");
        loadVideos('ns=MSNVideo_Cat&tag=AUSportsGeneral');
        return false;
    });
    $("#linkAfl").click(function() {
		removeTabImages();
		replaceADCalls("afl");
		selectTab("tabAfl");
        loadVideos('ns=MSNVideo_Cat&tag=AUAFL');
        return false;
    });
    $("#linkCricket").click(function() {
		removeTabImages();
		replaceADCalls("cricket");
		selectTab("tabCricket");
        loadVideos('ns=MSNVideo_Cat&tag=AUbaggygreen');
        return false;
    });
    $("#linkLeague").click(function() {
		removeTabImages();
		replaceADCalls("league");
		selectTab("tabLeague");
        loadVideos('ns=MSNVideo_Cat&tag=AULeague');
        return false;
    });
    $("#linkUnion").click(function() {
		removeTabImages();
		replaceADCalls("union");
		selectTab("tabUnion");
        loadVideos('ns=MSNVideo_Cat&tag=AUUnion');
        return false;
    });
    $("#linkFootball").click(function() {
		removeTabImages();
		replaceADCalls("football");
		selectTab("tabFootball");
        loadVideos('ns=MSNVideo_Cat&tag=AUFootball');
        return false;
    });
    $("#linkTennis").click(function() {
		removeTabImages();
		replaceADCalls("tennis");
		selectTab("tabTennis");
        loadVideos('ns=MSNVideo_Cat&tag=AUTennis');
        return false;
    });
    $("#linkGolf").click(function() {
        removeTabImages();
        replaceADCalls("golf");
        selectTab("tabGolf");
        loadVideos('ns=MSNVideo_Cat&tag=AUGolf');
        return false;
    });
    $("#linkBasketball").click(function() {
		removeTabImages();
		replaceADCalls("basketball");
		selectTab("tabBasketball");
        loadVideos('ns=MSNVideo_Cat&tag=AUBasketball');
        return false;
    });
    $("#linkHorse").click(function() {
		removeTabImages();
		replaceADCalls("racing");
		selectTab("tabHorse");
        loadVideos('ns=MSNVideo_Cat&tag=AUHorseRacing');
        return false;
    });
    $("#linkMotorsport").click(function() {
		removeTabImages();
		replaceADCalls("motorsport");
		selectTab("tabMotorsport");
        loadVideos('ns=MSNVideo_Cat&tag=AUMotorsport');
        return false;
    });
    $("#linkCycling").click(function() {
		removeTabImages();
	    replaceADCalls("cycling");
	    selectTab("tabCycling");
        loadVideos('ns=MSNVideo_Cat&tag=AUCycling');
        return false;
    });
    $("#linkSurfing").click(function() {
        addTabsImages();
        replaceADCalls("surfing");
        selectTab("tabSurfing");
        loadVideos('ns=MSNVideo_Cat&tag=AUSurfing');
        return false;
    });    
    $("#linkWinter").click(function() {
		removeTabImages();
		replaceADCalls("winter");
		selectTab("tabWinter");
		loadVideos('ns=MSNVideo_Cat&tag=AUFootballWorldCup');
		return false;
    });
    $("#linkTV").click(function() {
		replaceADCalls("wwostv");
		removeTabImages();
		selectTab("tabTV");
        loadVideos('ns=MSNVideo_Cat&tag=AUwwostv');
        return false;
       });
});

var playerStatus;

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(12), 	//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 intDayCount = 0;
var now = new Date();
var postionToMove = 0;
var searching = false;
var foundUUID = false;
var searchTabsLength = 0;
var uniqueId = '';
var maxDist = '';


function addTabsImages() 
	{
		$('#wwosTabImg').css("display","block");
/*$ ('#videoRightColDate').css("display", "none");*/


}

function removeTabImages() {
	
	$('#wwosTabImg').css("display","none");
/*$ ('#videoRightColDate').css("display", "block");*/
}


function selectTab(element) {
    var tabLinks;

    if (element) {
        tabLinks = document.getElementById("wwosVideoTabsContainerAll").getElementsByTagName("div");
        for (var i = 0; i < tabLinks.length; i++) {
            tabLinks[i].className = "wwosVideoTabs";
        }
        var sel = document.getElementById(element);
        sel.className = "wwosVideoTabsSelected";

        msnVideoConfig.activeTab = $("#" + element).attr("activeTab");
        msnVideoConfig.currentIdIndex = -1; //reset the currently index that is playing	

        var videoHeaderTitle = document.getElementById("videoRightColHeader");
        var videoFooterTitle = document.getElementById("videoFooter");

        if (videoHeaderTitle && videoFooterTitle) {
            var val = "Latest";

            if (element == "tabLatest") {
                val = "Latest";
            }
            else if (element == "tabAfl") {
                val = "AFL";
            }
            else if (element == "tabCricket") {
                val = "Cricket";
            }
            else if (element == "tabLeague") {
                val = "League";
            }
            else if (element == "tabUnion") {
                val = "Union";
            }
            else if (element == "tabFootball") {
                val = "Football";
            }
            else if (element == "tabTennis") {
                val = "Tennis";
            }
            else if (element == "tabGolf") {
                val = "Golf";
            }
            else if (element == "tabBasketball") {
                val = "Basketball";
            }
            else if (element == "tabHorse") {
                val = "Horse Racing";
            }
            else if (element == "tabMotorsport") {
                val = "Motorsport";
            }
            else if (element == "tabCycling") {
                val = "Cycling";
            }
            else if (element == "tabSurfing") {
                val = "Surfing";
            }
            else if (element == "tabWinter") {
                val = "World Cup";
                
            }
            else if (element == "tabTV") {
                val = "WWOS TV";
            }
            videoHeaderTitle.innerHTML = val + " videos";
            videoFooterTitle.innerHTML = val + " videos continue below";
            msnVideoConfig.tabName = val + " videos";
            
        }
    }

    return false;
}

function loadVideos(params, playOnLoad) {
    if (params) {
        msnVideoConfig.resultsType = "videobytag";
        msnVideoConfig.params = params;
        document.getElementById("videoDiv").innerHTML = "<p class='loading'>Loading videos...</p>";
        msnVideoConfig.offsetValue = 1;
        msnVideoConfig.pageSize = 50;

        if (msnVideoConfig.tabData[msnVideoConfig.activeTab - 1]) {
            //data for this tab has already been fetched
            jsonCallback(msnVideoConfig.tabData[msnVideoConfig.activeTab - 1], playOnLoad);
        } else {
            //get the data from the catalog
            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" + (playOnLoad ? "&cd=" + playOnLoad : ""));
        }
    }
    return false;
}

function injectJSON(url) {
    //$("#videoDiv").html(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);
}

//Renders the main portion of the video tabs given the results
function jsonCallback(results, playOnLoad) {
    if (results) {
        msnVideoConfig.todayVidCount = 0;
        msnVideoConfig.results = results;
        //Put result into cache
        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;
                    document.getElementById("videoRightColDate").innerHTML = formatDate(results.video[i].startDate.$, 'MDY');
                }
                else if (mostRecentVideoDate != videoDateString) {//Video is past the most recent date, no need to proceed
                    break;
                }
            }

            vidDiv.innerHTML += getVideoItemHTML(results.video[i], i);
            msnVideoConfig.todayVidCount++;
        }

        if (results.$total == 0) {
            document.getElementById("videoRightColDate").innerHTML = "";
            document.getElementById("videoDivFooterPagination").innerHTML = "";
            document.getElementById("videoTabsMinor").innerHTML = "";
            document.getElementById("videoDiv").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
                playVideo(0);
            }

            if (msnVideoConfig.resultsType == "search") {
                rhs_video_results = 6;
            }
            else {
                rhs_video_results = 0;
            }

            if (results.$total > rhs_video_results) {
                //fetch more in the minor tabs
                msnVideoConfig.pageSize = 6;
                msnVideoConfig.offsetValue = msnVideoConfig.todayVidCount + 1;
                //Next, fetch the next six videos for the pagination section
                loadMinorVideos()
            }
            else {
                document.getElementById("videoDivFooterPagination").innerHTML = "";
                document.getElementById("videoTabsMinor").innerHTML = "";
                document.getElementById("videoFooter").innerHTML = "";
            }
        }
        attachAnnimationEvents();
    }
    return false;
}

function getVideoItemHTML(itemData, i) {
    var videoDescriptionNoHtml = replaceAll(itemData.description.$, "\"", "&quot;");
    var videoDescriptionNoHtml = replaceAll(videoDescriptionNoHtml, ">", "&gt;");
    var videoDescriptionNoHtml = replaceAll(videoDescriptionNoHtml, "<", "&lt;");
    var videoTitle = limitString(itemData.title.$, 25);
    var videoThumbnailSrc = getThumbnailUrl(itemData, 0);
    var videoItemHTML = '';
    var videoDescription = limitString(videoDescriptionNoHtml, 100);
    var videoUsage = itemData.usage.usageItem[0].$totalCount;

    videoItemHTML =
	'<div class="videoItem" id="videoItem_' + i + '" onclick="playVideoUUID(\'' + 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>' +
		'</div>' +
		'<div class="videoUsage">' + videoUsage + (videoUsage == 1 ? ' view' : ' views') + '</div>' +
	'</div>';
    return videoItemHTML;
}

//Given the UUID of a specific video, plays that video in the video player
function playVideoUUID(uuid) {
    $(document).ready(function() {
        var msnVidObj = document.getElementById("MSNVideoPlayer_pobj");
        if (msnVidObj) {
            if (typeof (msnVidObj.vidPlayId) == "function") {
                msnVideoConfig.uuid = uuid;
                msnVidObj.vidPlayId(uuid);
            }
        }
    });
}

function playVideo(index) {
    msnVideoConfig.currentIdIndex = index;
    playerStatus = 3;
    playVideoUUID(msnVideoConfig.results.video[index].uuid.$);
}

function attachAnnimationEvents() {
    $(".videoTabs .videoItem").bind("mouseenter", function() {
        if (this.className.indexOf("selected") == -1) {
            $(this).css("background-color", "#fff");
            $(this).find(".itemImage .playFadeBG").css("z-index", 3);
        }
        $(this).find(".videoTitle, .playButton").css("text-decoration", "underline");
    });

    $(".videoTabs .videoItem").bind("mouseleave", function() {
        if (this.className.indexOf("selected") == -1) {
            $(this).css("background-color", "#F2F2F2");
        }
        $(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");
            openTabItem(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", "#F2F2F2");
    $(".videoTabs .videoItem .videoTitle, .videoIndexRight .videoItem .videoText").css("color", "#2D486D");
    $(".videoTabs .videoItem").removeClass("selected");
    $(".videoUsage").css("color", "gray");
}

//open one tab
function openTabItem(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": "-10px" }, animationTime, "swing");
    //remove play button
    item.find(".playButton").hide();
    //change style
    item.css("background-color", "#203143");
    item.find(".videoTitle, .videoText").css("color", "#fff");
    item.find(".videoUsage").css("color", "#fff");
}

function loadMinorVideos() {
    var vidTabMinor = document.getElementById("videoTabsMinor");
    if (vidTabMinor) {
        vidTabMinor.innerHTML = "<p class='loading'>Loading videos...</p>";
    }

    if (msnVideoConfig.resultsType == "search") {
        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=jsonCallbackPagingSection");
    }
    else if (msnVideoConfig.resultsType == "videobytag") {
        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=jsonCallbackPagingSection");
    }
}

function jsonCallbackPagingSection(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 = '<div class="videoDate">' + videoDateMD + ", " + msnVideoConfig.tabName + '</div>';

        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 += '<div class="videoDate">' + videoDateMD + ", " + msnVideoConfig.tabName + '</div>';
            }
            var videoDescriptionNoHtml = replaceAll(currentVideo.description.$, "\"", "&quot;");
            var videoDescriptionNoHtml = replaceAll(videoDescriptionNoHtml, ">", "&gt;");
            var videoDescriptionNoHtml = replaceAll(videoDescriptionNoHtml, "<", "&lt;");
            var videoTitle = limitString(currentVideo.title.$, 25);
            var videoUsage = currentVideo.usage.usageItem[0].$totalCount;

            videoItemHTML +=
			'<div class="videoItem" onclick="playVideoUUID(\'' + currentVideo.uuid.$ + '\');" >' +
				'<span class="videoItemTitle" title="' + currentVideo.source.$friendlyName + '">' + currentVideo.source.$friendlyName + ':</span>' +
				'<span class="videoCaption" title="' + currentVideo.title.$ + '">' + currentVideo.title.$ + '</span><span class="videoUsageBottom"> (' + videoUsage + (videoUsage == 1 ? ' view' : ' views') + ')</span><span class="playButton">Play</span>' +
            //'<div class="videoPostedDate">Posted: ' + videoDateString + '</div>' +
			'</div>';
            vidTabMinor.innerHTML += videoItemHTML;
            videoItemHTML = '';
        }

        renderMinorPaging(results);
        attachMinorTabEvents();

        //  fix for IE7 column heights
        document.getElementById("lftcol").style.height = 'auto';
        document.getElementById("contentcol").style.height = 'auto';
    }
}

function attachMinorTabEvents() {
    $("#videoTabsMinor .videoItem").bind("mouseenter", function() {
        $(this).css("background-color", "#fff");
        $(this).find(".videoItemTitle, .videoCaption, .playButton").css("text-decoration", "underline");
    });

    $("#videoTabsMinor .videoItem").bind("mouseleave", function() {
        $(this).css("background-color", "#F2F2F2");
        $(this).find(".videoItemTitle, .videoCaption, .playButton").css("text-decoration", "none");
    });
}

//Renders the paging for the minor video results
function renderMinorPaging(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="changePage(' + i + ');">' + i + '</div>';
            }
            pageLinksHTML += pageLink;
        }

        if (currentPage < resultPages) {
            nextPageHTML = '<div class="pageNumber" onclick="changePage(' + parseInt(currentPage + 1) + ');">Next</div>';
        }

        if ((currentPage < resultPages - 1) && resultPages > displayPages) {
            lastPageHTML = '<div class="elipsees">...</div><div class="pageNumber" onclick="changePage(' + resultPages + ');">' + resultPages + '</div>';
        }

        if (currentPage > 1) {//Only show PREV if not on the first page
            prevPageHTML = '<div class="pageNumber" onclick="changePage(' + parseInt(currentPage - 1) + ');">Prev</div>';
        }

        if (currentPage > displayPages - 1) {
            firstPageHTML = '<div class="pageNumber" onclick="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 = "";
    }
}

function changePage(delta) {
    msnVideoConfig.offsetValue = ((delta - 1) * msnVideoConfig.pageSize) + msnVideoConfig.todayVidCount + 1;
    loadMinorVideos();
}

function searchVideos(searchString) {
    var query = document.getElementById("videoSearchTextBox");
    if (query) {
        if (!searchString) {
            msnVideoConfig.query = query.value;
        }
        else {
            msnVideoConfig.query = searchString;
        }

        msnVideoConfig.resultsType = "search";
        msnVideoConfig.tabName = "Search results";
        msnVideoConfig.params = "ns=MSNVideo_Cat&tag=AUnationalninenews";
        document.getElementById("videoDiv").innerHTML = "<p class='loading'>Searching for videos...</p>";
        document.getElementById("videoRightColHeader").innerHTML = "Search results";
        document.getElementById("videoRightColDate").innerHTML = "";  //formatDate(msnVideoConfig.results.video[i].startDate.$, 'MDY');
        document.getElementById("videoFooter").innerHTML = "Search results videos continue below";
        msnVideoConfig.offsetValue = 1;
        msnVideoConfig.pageSize = 6;

        //Then call the JSON service for search
        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");
    }
}
/* ---------------- HELPER FUNCTION ---------------- */

function focusOnSearch(obj) {
    if (obj.value == 'Search videos..') {
        obj.value = '';

    }
    return true;
}

function focusOutSearch(obj) {
    if (obj.value == '') {
        obj.value = 'Search videos..';
    }
    return true;
}

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], 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;
}

function dateMD(date) {
    var videoDateMD = '';
    var videoDateMDY = formatDate(date, 'MDY');
    videoDateMD = videoDateMDY.substr(0, videoDateMDY.indexOf(','));
    return videoDateMD;
}

function replaceAll(stringToReplace, findText, repText) {
    return stringToReplace.replace(new RegExp(findText, "g"), repText);
}

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
}

function queryString(key) {
    var page = new PageQuery(window.location.search);
    return unescape(page.getValue(key));
}

// 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 highlightIndex(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();
}

//When a new video is loaded, highlight it in the RHS if it can be found
Msn.Video.OnVideoLoaded = function(id) {
    highlightIndex(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 (vidTitle != "Advertisement") {
            var newIndex = msnVideoConfig.currentIdIndex + 1;
            if (newIndex >= msnVideoConfig.todayVidCount) {
                newIndex = 0;
            }
            playVideo(newIndex);
        }
    }
} 


//Video AD targeting support
//Remove when this go live
 //var JS_ADX_BANNER_TOP='&PG=AUAKGA&AP=1390';var JS_ADX_BANNER2_TOP='&PG=AUANHK&AP=1390';var JS_ADX_CATEGORYTILE_RIGHT__1='&PG=AUANDZ&AP=0000';var JS_ADX_HALFBANNER_RIGHT__1='&PG=AUANAC&AP=1007';var JS_ADX_LOCALTILE_RIGHT__1='&PG=AUAND0&AP=0000';var JS_ADX_MEDIUM_TOP='&PG=AUANHJ&AP=1089';var JS_ADX_MTEXTLINK_RIGHT__1='&PG=AUANAE&AP=1484';var JS_ADX_PANEAD_TOP__1='&PG=AUANLN&AP=3092';var JS_ADX_TILE_RIGHT__1='&PG=AUANDY&AP=0000';var JS_ADEXPERT_RECTANGLE2='';var JS_SURVEY_URL='';var JS_ADX_NETPROMO_TOP='&PG=AUANGK&AP=1419';var JS_GENERIC_ENABLE_CHANGE='';var JS_HEADER_AUTO_FOCUS='';var JS_SLIDESHOW_LOADIMAGECOUNT='';var JS_ADX_PANEAD_TOP='&PG=AUANHH&AP=3092';
var _adCalls={
	"AdList":
		[{"adKey":"BANNER_TOP","js_key":"JS_ADX_BANNER_TOP","prev_value":(typeof(JS_ADX_BANNER_TOP)=="undefined")?"":JS_ADX_BANNER_TOP},
		 {"adKey":"MEDIUM_TOP","js_key":"JS_ADX_BANNER2_TOP","prev_value":(typeof(JS_ADX_BANNER2_TOP)=="undefined")?"":JS_ADX_BANNER2_TOP},
		 {"adKey":"BANNER2_TOP","js_key":"JS_ADX_MEDIUM_TOP","prev_value":(typeof(JS_ADX_MEDIUM_TOP)=="undefined")?"":JS_ADX_MEDIUM_TOP},
		 {"adKey":"PANEAD_TOP.1","js_key":"JS_ADX_PANEAD_TOP","prev_value":(typeof(JS_ADX_PANEAD_TOP)=="undefined")?"":JS_ADX_PANEAD_TOP}
		]
};
var _adCallsList=null;
var _adSubSectionName="";

function findPGIndexValue(adKey){
 var _result=-1;
 for(var i=0;i< _adCalls.AdList.length;i++)
 {
  if (_adCalls.AdList[i].adKey.toString() == adKey)
  {
	return i;
  }
 }
 return _result;
}
function ADTargetingCallback(results)
{
 if (results)
	{
		_adCallsList=results;
		ADTargeting(results);
	}
}

function ADTargeting(results)
{
 var _defaultBg="";
 var _winterBg="url(/img/sponsors/wwos_test_skin_full.jpg)";
 if (results)
 {
	var sw=false;
	var _list=results.AdExpertList.AdExpert;
	for (var i=0;i<_list.length;i++)
	{
		if ((_list[i].SectionName) && (_list[i].SectionName.toString().toLowerCase()=='video') && (_list[i].SubsectionName.toString().toLowerCase()== _adSubSectionName))
		//if ((_list[i].SectionName) && (_list[i].SectionName.toString().toLowerCase()=='video'))
		{
		  var _index=findPGIndexValue(_list[i].AdKey.toString());
		  if (_index != -1)
		  {
			//Replace the JS_ADX_VARIABLE value with the current section value
			var _replaceString=_adCalls.AdList[_index].js_key.toString() + "=\"" + _list[i].AdCall.toString() + "\"";
			_replaceString=_replaceString.replace("&amp;","&").replace("&amp;","&");
			eval(_replaceString + ";");
			sw=true;
		  }
		}
	}
	//if there is some matched subSection
	//Render the Ads
	if (sw)
	{
		//debugger;
		dapMgr.trackEvent(eventType.click);
		if (_adSubSectionName == "winter")
		{
		  //document.body.style.backgroundImage=_winterBg;
		}
	}
	else
	{
		//Recover the js values
		for(var j=0;j< _adCalls.AdList.length;j++)
		{
		  if (_adCalls.AdList[j].prev_value.toString() != "")
		  {
		    var _replaceString=_adCalls.AdList[j].js_key.toString() + "=\"" + _adCalls.AdList[j].prev_value.toString()+ "\"";
		    eval(_replaceString);
		  }
		}
		dapMgr.trackEvent(eventType.click);
		//document.body.style.backgroundImage=_defaultBg;
	}
 }
}

function replaceADCalls(subsectionName)
{
  _adSubSectionName=subsectionName.toLowerCase();
  var _url="http://data.ninemsn.com.au/Services/Service.axd?ServiceName=AdExpert&ServiceAction=GetAdCalls&AttributeStyle=True&ServiceFormat=json&site=wwos&v=1302010&callback=ADTargetingCallback&AdxEnabled=false" ;
  if (!_adCallsList)
  {
	injectJSON(_url);
  }
  else
  {
   ADTargeting(_adCallsList);
  }
}










