var akamaiRoot = "http://a123.g.akamai.net/f/123/41524/60m/webdata.showcase.ca/";
var ScriptRoot = akamaiRoot + "ScriptBuilder.ashx";
var playerDiv = "#cwpPlayerDiv";
var cwpIsShowPage = false; // This will be overriden on show pages
var showPageNotFound = false;
var adHasTriggered = false;

/* Methods that must be available on the page and cannot be encapsulated */
function onDimButtonClick(){
	$("#VideoCentre-Dim").trigger("click");
}
function monitorDocumentActivity(){
	var timeout = 1000;
	var playerHandle = document.getElementById("playerwidget");
	if(playerHandle){
		$(document).bind("idle.idleTimer", function(){
		   playerHandle.pauseCountdown(false);
		});

		$(document).bind("active.idleTimer", function(){
			playerHandle.pauseCountdown(true);
		});

		$.idleTimer(timeout);
	}
}
function onResizeMediaArea(event){
	function setElementWidth(divid, newW) {
		$("#"+divid).width(newW);
	}
	function setElementSize(divid, newW, newH) {
		setElementWidth(divid, newW);
		$("#"+divid).height(newH);
	}
	$("#ContentBrowser-PopupMenu-Container").hide();
	if (event.data == false){
		setElementSize('playerwidget', 912, 513);
		setElementWidth('SocialToolbar-Container', 912);
		setElementWidth('SocialToolbar-Embed-Container', 912);
		setElementWidth('SocialToolbar-Email-Container', 912);
		$("#VideoPlayer-BigBox").hide();
		
	} else {
		setElementSize('playerwidget', 608, 362);
		setElementWidth('SocialToolbar-Container', 608);
		setElementWidth('SocialToolbar-Embed-Container', 608);
		setElementWidth('SocialToolbar-Email-Container', 608);
		if (adHasTriggered){  // we don't want to display the ad area if we have not had an ad
			$("#VideoPlayer-BigBox").show();
		}
	}
	$("#SocialToolbar-Container").show();
	if ($("#SocialToolbar-Email-Container").is(":visible")) {
		var emailPosition = $("#SocialToolbar-Container").offset();
	}
	
}
function onMediaPlaying(event) {
	var remainingSeconds = Math.floor((event.data.duration-event.data.currentTime)/1000);
	$("#ClipDescriptor-Countdown span:first").text(remainingSeconds);
	if(remainingSeconds<2){
		$("#ClipDescriptor-Countdown span:last").text("second");
	}else{
		$("#ClipDescriptor-Countdown span:last").text("seconds");
	}
}

/* Social Toolbar Functions */
function socialPopup(url,width,height) {
	day = new Date();
	id = day.getTime();
	eval("page" + id + " = window.open('" + url + "', '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=" + width + ",height=" + height + ",left=340,top=362');");
}
function populateEmbedCode(changed) {
	var advanced = 0;
	var advancedReplace = advanced;
	var bug = "&player.overlayImageUrl=http://www.showcase.ca/videoEmbedPlayer/images/globalTVbug.png";
	var flashWidthMod = 0;
	var flashHeightMod = 0;
	var embedCode = '<object width="**PLAYERWIDTH**" height="**PLAYERHEIGHT**"><param name="movie" value="http://www.showcase.ca/video/swf/EmbedPlayer.swf?player.width=**FLASHWIDTH**&player.height=**FLASHHEIGHT**&player.overlayImageUrl=&pid=**PID**&show=**SHOW**&episode=**EPISODE**&season=**SEASON**&cliptitle=**CLIPTITLE**"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.showcase.ca/video/swf/EmbedPlayer.swf?player.width=**FLASHWIDTH**&player.height=**FLASHHEIGHT**&player.overlayImageUrl=&pid=**PID**&show=**SHOW**&episode=**EPISODE**&season=**SEASON**&cliptitle=**CLIPTITLE**" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="**PLAYERWIDTH**" height="**PLAYERHEIGHT**"></embed></object>';
	if ($("#SocialToolbar-Embed-Advanced-Checkbox").is(":checked")) { advanced = 1; }
	if (advanced) { advancedReplace = "1"; } else { advancedReplace = "0"+bug; }
	if (advanced && changed == "advanced" && ($("#SocialToolbar-Embed-Size-Width").val() / $("#SocialToolbar-Embed-Size-Height").val() != 1.535)) { $("#SocialToolbar-Embed-Size-Height").val(Math.ceil($("#SocialToolbar-Embed-Size-Width").val()/1.535)); }
	if (!advanced && changed == "advanced" && ($("#SocialToolbar-Embed-Size-Height").val() / $("#SocialToolbar-Embed-Size-Width").val() != 0.5625)) { $("#SocialToolbar-Embed-Size-Height").val(Math.ceil($("#SocialToolbar-Embed-Size-Width").val()*0.5625)); }
	if (advanced && changed == "width") { $("#SocialToolbar-Embed-Size-Height").val(Math.ceil($("#SocialToolbar-Embed-Size-Width").val()/1.535)); }
	if (advanced && changed == "height") { $("#SocialToolbar-Embed-Size-Width").val(Math.ceil($("#SocialToolbar-Embed-Size-Height").val()*1.535)); }
	if (!advanced && changed == "width") { $("#SocialToolbar-Embed-Size-Height").val(Math.ceil($("#SocialToolbar-Embed-Size-Width").val()*0.5625)); }
	if (!advanced && changed == "height") { $("#SocialToolbar-Embed-Size-Width").val(Math.ceil($("#SocialToolbar-Embed-Size-Height").val()/0.5625)); }
	if (advanced && $("#SocialToolbar-Embed-Size-Width").val()<400) { $("#SocialToolbar-Embed-Size-Width").val("400"); $("#SocialToolbar-Embed-Size-Height").val("261"); }
	if (!advanced && $("#SocialToolbar-Embed-Size-Width").val()<400) { $("#SocialToolbar-Embed-Size-Width").val("400"); $("#SocialToolbar-Embed-Size-Height").val("225"); }
	if (advanced && $("#SocialToolbar-Embed-Size-Width").val()>1280) { $("#SocialToolbar-Embed-Size-Width").val("1280"); $("#SocialToolbar-Embed-Size-Height").val("834"); }
	if (!advanced && $("#SocialToolbar-Embed-Size-Width").val()>1280) { $("#SocialToolbar-Embed-Size-Width").val("1280"); $("#SocialToolbar-Embed-Size-Height").val("720"); }
	flashWidthMod = advanced ? 5 : 0;
	flashHeightMod = advanced ? 58 : 0;
	embedCode = embedCode.replace(/\*\*PLAYERWIDTH\*\*/g,$("#SocialToolbar-Embed-Size-Width").val()).replace(/\*\*PLAYERHEIGHT\*\*/g,$("#SocialToolbar-Embed-Size-Height").val()).replace(/\*\*FLASHWIDTH\*\*/g,$("#SocialToolbar-Embed-Size-Width").val()-flashWidthMod).replace(/\*\*FLASHHEIGHT\*\*/g,$("#SocialToolbar-Embed-Size-Height").val()-flashHeightMod).replace(/\*\*PID\*\*/g,embed_vars.pid).replace(/\*\*SHOW\*\*/g,embed_vars.show).replace(/\*\*EPISODE\*\*/g,embed_vars.episode).replace(/\*\*SEASON\*\*/g,embed_vars.season).replace(/\*\*CLIPTITLE\*\*/g,embed_vars.cliptitle);
	$("#SocialToolbar-Embed-Code-Text").fadeTo(200,0.1,function(){
		$("#SocialToolbar-Embed-Code-Text").val(embedCode);
		$("#SocialToolbar-Embed-Code-Text").fadeTo(400,1);
	});
}
function initializeSocialToolbar() {
	var emailSeason = "";
	var emailEpisode = "";
	if (embed_vars.season && !isNaN(embed_vars.season)) { emailSeason = "Season "+embed_vars.season+";"; }
	if (embed_vars.episode && !isNaN(embed_vars.episode)) {
		emailEpisode = "Episode "+embed_vars.episode;
	}else if (embed_vars.episode && isNaN(embed_vars.episode)) {
		emailEpisode = embed_vars.episode;
	}
	populateEmbedCode();
}

/* Google Click Tracking */
function clickTrack(label) {
	var trackEventArea;
	if (typeof(embed_vars) != "undefined" && embed_vars.show.length>1) {
		trackEventArea=embed_vars.show+" S"+embed_vars.season+" E"+embed_vars.episode;
	}else{
		trackEventArea="Video Landing Page";
	}
	pageTracker._trackEvent('VideoBrowser', trackEventArea, label);
}

/* Wallpaper Ad Call */
function cwChangeWallpaperAd(url,hex) {
	if (typeof(url)!="string") {
		jQuery('body').css("background","#050203 url(/Media/Images/Global/body_bg2.jpg) no-repeat scroll center top");
	}else{
		jQuery('body').css("background",hex+" url("+url+") no-repeat scroll center top");
	}
}

/**********
* The first function called, which launches everything
**********/
function cwpInsertPlayer(data){
	// First we define some methods that we will use within the scope of this.  They are defined here so as not to pollute the namespace
	function addVideoEvtHandlers(){
		if (tpController) {
			tpController.addEventListener("OnDimButtonClick", "onDimButtonClick");
			tpController.addEventListener("OnResizeMediaArea", "onResizeMediaArea");
			tpController.addEventListener("OnMediaLoadStart", "monitorDocumentActivity");
		}
		if(cwp.manager){
			cwp.manager.onAdStart(function(){
				tpController.addEventListener("OnMediaPlaying","onMediaPlaying");
				$("#ClipDescriptor-Countdown").show();
				if ($("#SocialToolbar-Email-Container").is(":visible")) {
					var emailPosition = $("#SocialToolbar-Container").offset();
					$("#at16p").offset({left:emailPosition.left,top:(emailPosition.top+34)});
				}
			});
			cwp.manager.onAdEnd(function(){
				tpController.removeEventListener("OnMediaPlaying","onMediaPlaying");
				$("#ClipDescriptor-Countdown").hide();
				if ($("#SocialToolbar-Email-Container").is(":visible")) {
					var emailPosition = $("#SocialToolbar-Container").offset();
					$("#at16p").offset({left:emailPosition.left,top:(emailPosition.top+34)});
				}
			});
		}
		//No Flash Error Message
		$("#cwpPlayerDiv p").addClass("ErrorMessage");
	}

	/* Flash Fix: Title Tag Changing to URL Hash (IE) */
	function activateFlashHashFix(){
		var oldDocumentTitle = document.title;
		document.onpropertychange = function(){
			var newtitle = document.title;
			if(newtitle && oldDocumentTitle != newtitle && newtitle != ''){
				document.title = oldDocumentTitle;
			}
		}
	}

	/* IE6 PNG Fix */
	function activatePNGFix(){
		var detectAgent = navigator.userAgent.toLowerCase();
		if (detectAgent.indexOf('msie') > -1) {
			var arVersion = navigator.appVersion.split("MSIE");
			var version = parseFloat(arVersion[1]);
			if ((version == 6) && (document.body.filters)) {
				if (document.all) {
					document.all["ContentBrowser-Search"].style.cssText = 'background:none; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader (src="/media/images/video/ContentBrowser_Search_Icon.png",sizingMethod="crop");';
				}
			}
		}
	}

	/* Search Functions */
	var trySearchTimeout = null;
	function trySearch(){
		clearTimeout(trySearchTimeout);
		trySearchTimeout = setTimeout(
			function(){
				trySearchTimeout = null;
				if($("#ContentBrowser-Search-Text").val().length == 0){ 
					cwp.manager.removeSearch();
				}else if ($("#ContentBrowser-Search-Text").val().length > 1){
					doSearch();	
				}
			},250);
	}
	function doSearch(){
		var userinput = $("#ContentBrowser-Search-Text").val();
		var searchQuery = jQuery.trim(userinput);
		var extractedQuery = extractSearchQuery(searchQuery);
		clickTrack(searchQuery);
		cwp.manager.loadSearchResult(userinput, extractedQuery.query, extractedQuery.season, extractedQuery.episode);
		return false;
	}
	function extractSearchQuery(searchQuery){
		var season = null;
		var episode = null;

		//convert Season X to Season=X, including all variations of Season X, s X;
		if(searchQuery.search(/season/i) != -1){
			var index_season = searchQuery.search(/season/i);
			var seasonNum = searchQuery.substr(index_season +6);
			season = parseInt(seasonNum);	
		}else if(searchQuery.search(/s/i)!=-1){
			var index_season = searchQuery.search(/s/i);
			var seasonNum = searchQuery.substr(index_season +1);
			season = parseInt(seasonNum);
			while(!season && (seasonNum.search(/s/i)!=-1)){
				//for all recurrence of s
				var index_seasonNum = seasonNum.search(/s/i);
				seasonNum = seasonNum.substr(index_seasonNum +1);
				season = parseInt(seasonNum);
				index_season += index_seasonNum +1;
			}
		}
		//convert Episode X to Episode=X, including all variations of Episode X, ep X, e X;
		if(searchQuery.search(/episode/i) != -1){
			var index_episode = searchQuery.search(/episode/i);
			var episodeNum = searchQuery.substr(index_episode+7);
			episode = parseInt(episodeNum);
		}else if(searchQuery.search(/ep/i) != -1){
			var index_episode = searchQuery.search(/ep/i);
			var episodeNum = searchQuery.substr(index_episode+2);
			episode = parseInt(episodeNum);
			var episodeindexplus =0;
			while(!episode && (episodeNum.search(/ep/i)!=-1)){
				var index_episodeNum = episodeNum.search(/ep/i);
				episodeNum = episodeNum.substr(index_episodeNum +2);
				episode = parseInt(episodeNum);
				episodeindexplus += index_episodeNum + 2;
			}
			if(episode) index_episode += episodeindexplus; 
		}else if(searchQuery.search(/e/i) != -1){
			index_episode = searchQuery.search(/e/i);
			var episodeNum = searchQuery.substr(index_episode+1);
			episode = parseInt(episodeNum);
			var episodeindexplus =0;
			while(!episode && (episodeNum.search(/e/i)!=-1)){
				var index_episodeNum = episodeNum.search(/e/i);
				episodeNum = episodeNum.substr(index_episodeNum +1);
				episode = parseInt(episodeNum);
				episodeindexplus += index_episodeNum + 1;
			}
			if(episode) index_episode += episodeindexplus; 
		}
		if(season || episode){
			var index = 0;
			if(!episode) index = index_season;
			else if(!season) index = index_episode;
			else if(index_season < index_episode) index = index_season;
			else index = index_episode;
				searchQuery = searchQuery.substring(0, index);
				searchQuery = jQuery.trim(searchQuery);
		}		
		return {query:searchQuery, season:season, episode:episode};
	}
	
	function convertCatToURLPath(fullTitle){
		var retVal = fullTitle.replace(/[^\/]*(\/([^\/]*(\/|))|)/,"").replace(/[^A-Za-z0-9 \/]/g,"").toLowerCase();
		if (retVal.length>0){
			var firstSlashIndex = retVal.indexOf("/");
			if (firstSlashIndex>0){
				retVal = retVal.substring(0,firstSlashIndex).replace(/ /g,"") + "/video" + retVal.substring(firstSlashIndex).replace(/ /g,"+");
			}else{
				retVal = retVal.replace(/ /g,"") + "/video";
			}
		}else{
			retVal = fullTitle.replace(/[^\/]*(\/|)/,"").replace(/[^A-Za-z0-9 \/]/g,"").toLowerCase().replace(/ /g,"+");
			if(retVal.length == 0)
				retVal = "video";
		}
		return retVal;
	}

	function matchCategoryFromShowPage(){
		var retVal,reMatch = location.href.match(/http:\/\/[^?#\/]*\/(([^#?\/]*\/)+)[^?#\/]*([?].*|[#].*|)$/);
		if (reMatch != null && reMatch.length>1){
			retVal = reMatch[1].substring(0,reMatch[1].length-1);
		}else{
			retVal = "";
		}
		return retVal;
	}
	
	function matchFullTitleFromPending(){
		var pendingTitle = {
			retVal: null,
			userinput: null
		};
		var reMatch = location.href.match(/\#.*$/);
		if (reMatch != null && reMatch.length>0){
			reMatch = reMatch[0].substring(1);
		}else{
			reMatch = "";
		}
		
		if(reMatch.indexOf("/search/") == -1){
			pendingTitle.retVal = reMatch;
			return pendingTitle;
		}else {
			pendingTitle.retVal = reMatch.substring(0, reMatch.indexOf("/search/"));
			pendingTitle.userinput = reMatch.substring(reMatch.indexOf("/search/") + 8);
		}
		return pendingTitle;
	}
	
	function generateClipUrl(rel){
		/* Generate the Clip URL */
		var baseURL = location.href.match(/http:\/\/[^\/]*\//)[0];		
		if (rel.parentCat && rel.parentCat.fullTitle ){
			if (rel.parentCat.ID == "Search"){
				var catFullTitle = cwp.manager.catList[0].getReleaseCategoryFullTitle(rel.categoryIDs);
			}else{
				var catFullTitle = rel.parentCat.getReleaseCategoryFullTitle(rel.categoryIDs);
			}
			if(catFullTitle){
				var catStr = convertCatToURLPath(catFullTitle);
				if (catStr.length>0){catStr += "/"; }
				baseURL += catStr;
			}	else{
				baseURL += "video/";
			}
		}else{
			baseURL += "video/";
		}
		baseURL += rel.title.replace(/ /g,"+").replace(/[^A-Za-z0-9\+]/g,"").toLowerCase();
		var clipURL = baseURL + "/video.html?v=" + rel.contentID + "&p=" + rel.page;
		
		if(rel.parentCat){
			var sorting = "&s=";
			switch(rel.parentCat.currentSortingCriteria){
				case "title":
					sorting += "a";
					break;
				case "requestCount":
					sorting += "p";
					break;
				case "airdate":
				default:
					sorting += "d";
					break;
			}
			if(rel.parentCat.sortDescending){
				sorting += "d";
			}else{
				sorting += "a";
			}
			clipURL += sorting;
			if (rel.parentCat.ID == "Search"){
				clipURL += "&searchQuery=" + escape(rel.parentCat.searchQuery);
				if(rel.parentCat.season){
					clipURL += "&searchSeason=" + rel.parentCat.season;
				}
				if(rel.parentCat.episode){
					clipURL += "&searchEpisode=" + rel.parentCat.episode;
				}
			}	
		}
		
		var reMatch = location.href.match(/\#.*$/);
		if (reMatch != null && reMatch.length>0){
			clipURL += reMatch[0];
		}
		
		return clipURL;
	}
	
	function ClipItem(data){
		var clip = {};
		clip.title = cwp.symbolsToEntities(data.title);
		
		for(var i=0; i<data.contentCustomData.length; i++){
			if(data.contentCustomData[i].title == "Show"){
				clip.show = data.contentCustomData[i].value;
			}
			else if(data.contentCustomData[i].title == "Season"){
				clip.season = data.contentCustomData[i].value;
			}
			else if(data.contentCustomData[i].title == "Episode"){
				clip.episode = data.contentCustomData[i].value;
			}
		}
		clip.thumbnailURL = data.thumbnailURL;
		clip.destinationURL = generateClipUrl({PID:data.PID, contentID: data.contentID, parentCat: null, title: data.title, page: 1 });
		return clip;
	}
	
	function populateEndOfClipComponent(rel){ 
		var playerHandle = document.getElementById("playerwidget");
		var parentCat = cwp.manager.selectedCat;
		if(!parentCat) parentCat = cwp.manager.catList[0];
		var nextClip = null;
		for(var i=1; i< parentCat.rel.length; i++){
			if(rel.PID == parentCat.rel[i].PID){
				if(i+1 > parentCat.rel.length) nextClip = parentCat.rel[1];
				else nextClip = parentCat.rel[i+1];
				break;
			}
		}
		if(nextClip) {
			playerHandle.setNextClip({
				title: cwp.symbolsToEntities(nextClip.title), 
				show: cwp.symbolsToEntities(nextClip.Show),
				season:  cwp.addLeadingZero(nextClip.Season) || null, 
				episode:  cwp.addLeadingZero(nextClip.Episode) || null,
				thumbnailURL: nextClip.thumbnailURL, 
				destinationURL: (nextClip.element)? nextClip.element.children("a").attr("href"): generateClipUrl(nextClip)
			});
		}
	}

	function focusOnTargetRelease(targetRelease, searchQuery, searchSeason, searchEpisode){
		var i,
				targetCat=null, // this is the default cat if we can't find a match
				releaseCat = null,
				releaseBelongInMain = false;
				ReleaseCatBelongTotargetCat = false;
				pendingTitle = matchFullTitleFromPending(),
				fullTitlePath = pendingTitle.retVal;
		
		//find a category that release belongs to.
		for (i=0;i<targetRelease.categories.length;i++){
			// We don't want to search categories not related to 
			if (targetRelease.categories[i].indexOf("SHOWVC")>-1){
				if(targetRelease.categories[i].indexOf("SHOWVC/")>-1){
					targetRelease.categories[i] = targetRelease.categories[i].replace("&amp;","&");
					releaseCat = cwp.manager.findCategoryByFullTitle(targetRelease.categories[i]);
				}
				else{
					releaseBelongInMain = true;
				}
			}
		}
		
		// If we can extract a path from the url
		if (fullTitlePath!="video"){	
			if(fullTitlePath == ""){
				targetCat = releaseCat;
				ReleaseCatBelongTotargetCat = true;
			}else{
				targetCat = cwp.manager.catList[0].getCategoryByFullTitle(fullTitlePath,convertCatToURLPath,true);
				if(releaseCat && targetCat && releaseCat.fullTitle.indexOf(targetCat.fullTitle) != -1 ){
					ReleaseCatBelongTotargetCat = true;
				}
			}
		}else if (fullTitlePath.length>0){ // If we end up with an empty fullTitlePath, it's a malformed url and we shouldn't try to highlight the release		
			targetCat = cwp.manager.catList[0];
			if(releaseBelongInMain){
				releaseCat = targetCat;
				ReleaseCatBelongTotargetCat = true;
			}
		}
		
		//If user was in search
		if(pendingTitle.userinput){
			cwp.manager.previousSelectedCat = targetCat;
			var userinput = unescape(pendingTitle.userinput);
			$("#ContentBrowser-Search-Text").val(userinput);
			$("#ContentBrowser-Search-Text").addClass("ContentBrowser-Search-Text-Focus");
			$("#ContentBrowser-Search-Text-Clear").show();
			if(searchQuery && userinput.indexOf(searchQuery) != -1){
				cwp.manager.loadSearchResult(userinput, searchQuery, searchSeason, searchEpisode,targetRelease);
			}
			else{
				var searchQuery = jQuery.trim(userinput);
				var extractedQuery = extractSearchQuery(searchQuery);
				cwp.manager.loadSearchResult(userinput, extractedQuery.query, extractedQuery.season, extractedQuery.episode, targetRelease, true, releaseCat);
			}
		}else{
			if (releaseCat===null || targetCat === null){
				cwp.manager.catList[0].select();
			}else{
				// If we found a target category, we need to load data until we find the targetRelease
				var qs = new cwpQS();
				var targetPageNum = parseInt(qs.get("p",1),10); // Start searching at 1 if no page has been specified
				if(ReleaseCatBelongTotargetCat){
					targetCat.loadUntilReleaseFound(targetRelease,targetPageNum,0,function(rel,targetPage){
						targetCat.select();
						if (targetPage!=1){
							targetCat.showSelectedPage(targetPage,1,true);	
						}
						rel.select();
					});
				}else{
					releaseCat.loadUntilReleaseFound(targetRelease,targetPageNum,0,function(rel,targetPage){
						targetCat.select();
						rel.select();
					});
				}		
			}
		}
	}

	function focusOnURLCategory(){
		var targetCat = cwp.manager.catList[0].getCategoryByFullTitle(matchCategoryFromShowPage(),convertCatToURLPath,true);
		if (targetCat!=null){
			showPageNotFound = false;
			targetCat.select();
		}else{
			showPageNotFound = true;
			$("#ContentBrowser-NoVideos").show();
			cwp.manager.catList[0].select();
		}
	}

	function focusOnTargetCategory(data){
		var reMatch = location.href.match(/\#.*$/);
		if (reMatch.length>0){
			var catStr = reMatch[0].substring(1);
			if (catStr===""){
				cwp.manager.catList[0].select();
			}else{
				var targetCat = cwp.manager.catList[0].getCategoryByFullTitle(catStr,convertCatToURLPath,true);
				if (targetCat===null){ // if there was no matching category, use the default
					if (data.isShowPage){
						focusOnURLCategory();
					}else{
						cwp.manager.catList[0].select();
					}
				}else{
					targetCat.select();
				}
			}
		}
	}

	function getCategories(data){
		// start loading the categories, use the callback to render
		if (cwp.manager.catList.length===0){
			if(data.sort){
				var sortingDescending = true; // we will default to a descending sort if unspecified
				if(data.sort.charAt(1)=="a"){
					sortingDescending = false;
				}
				var sortType = (cwp.sortTypes[data.sort.charAt(0)])?cwp.sortTypes[data.sort.charAt(0)]:"airdate";
				cwp.manager.currentSortingCriteria = sortType;
				cwp.manager.Descending[sortType] = sortingDescending;
			}
			cwp.manager.getCategories(function(){
				// Create list for categories and ask the manager to render all of them
				if (data.targetRelease){
					focusOnTargetRelease(data.targetRelease, unescape(data.searchQuery), data.searchSeason, data.searchEpisode);
				}else if(data.isShowPage===true){
					focusOnURLCategory();
				}else if(location.href.indexOf("#")>-1){
					focusOnTargetCategory(data);
				}else{
					cwp.manager.catList[0].select();
				}
			});
		}
	}

	function addDefaultSortingClass(){
		if(cwp.manager.currentSortingCriteria == "airdate") {
			$("#sortAirDate").addClass("Selected");
			if(cwp.manager.Descending.airdate === true){
				$("#sortAirDateArrow").html("&#9650;");
			}else{
				$("#sortAirDateArrow").html("&#9660;");
			}
			$("#sortTitleArrow").empty();
			$("#sortTitle").removeClass("Selected");
			$("#sortRequestCountArrow").empty();
			$("#sortRequestCount").removeClass("Selected");
		}else if(cwp.manager.currentSortingCriteria == "title") {
			$("#sortTitle").addClass("Selected");
			if(cwp.manager.Descending.title === true){
				$("#sortTitleArrow").html("&#9650;");
			}else{
				$("#sortTitleArrow").html("&#9660;");
			}
			$("#sortAirDateArrow").empty();
			$("#sortAirDate").removeClass("Selected");
			$("#sortRequestCountArrow").empty();
			$("#sortRequestCount").removeClass("Selected");
		}else if(cwp.manager.currentSortingCriteria == "requestCount"){
			$("#sortRequestCount").addClass("Selected");
			if(cwp.manager.Descending.requestCount === true){
				$("#sortRequestCountArrow").html("&#9650;");
			}else{
				$("#sortRequestCountArrow").html("&#9660;");
			}
			$("#sortAirDateArrow").empty();
			$("#sortAirDate").removeClass("Selected");
			$("#sortTitleArrow").empty();
			$("#sortTitle").removeClass("Selected");
		}
	}

	function removeSelectedSortingClass(){
		if(cwp.manager.currentSortingCriteria == "airdate"){ 
			$("#sortAirDateArrow").empty();
			$("#sortAirDate").removeClass("Selected");
		}
		else if(cwp.manager.currentSortingCriteria == "title"){ 
			$("#sortTitleArrow").empty();
			$("#sortTitle").removeClass("Selected");
		}
		else if(cwp.manager.currentSortingCriteria == "requestCount") {
			$("#sortRequestCountArrow").empty();
			$("#sortRequestCount").removeClass("Selected");
		}
	}

	function updateURLWithCategory(cat){
		var newUrl = location.href.replace(/\#.*$/,"");
		location.href = newUrl + "#" + convertCatToURLPath(cat.fullTitle);
	}
	
	function updateURLWithSearchInput(userinput){
		var recentCategory = location.href.match(/\#.*$/)[0];
		if(recentCategory.indexOf("search") != -1){
			recentCategory = recentCategory.substring(0, recentCategory.indexOf("search") -1);
		}
		var newUrl = location.href.replace(/\#.*$/,"");
		location.href = newUrl + recentCategory + "/search/" + escape(userinput);
	}

	function updateCategoryTileAd(cat,adParameters){
		if (typeof(adSync)=="object"){
			var tileAdUrl = cat.getInheritedProperty("TileAd");
			var sponsorDiv = $("#ContentBrowser-CategorySponsorship");
			if (tileAdUrl.length>0 && tileAdUrl != "inherit"){
				var tileDiv = sponsorDiv.find(".catTileContainer").empty();
				adSync.CreateNewAdiFrame("tile", tileAdUrl, tileDiv)
				sponsorDiv.show();
			}else{
				sponsorDiv.hide();
			}
		}
	}

	function extractLongestCategory(targetRelease){
		var fullTitle = null;
		var i=0,maxDepth=0;
		for (var i=0;i<targetRelease.categories.length;i++){
			if (targetRelease.categories[i].indexOf("SHOWVC")>-1){
				var curDepth = targetRelease.categories[i].split("/").length;
				if (curDepth>maxDepth){
					maxDepth = curDepth;
					fullTitle = targetRelease.categories[i].replace("&amp;","&");
				}
			}
		}
		return fullTitle;
	}

function initializePlayerTemplate(data){
	/* Show Menu Popup */
	$(".popupMenuClose").click(function(){
		$("#ContentBrowser-PopupMenu-Container").hide();
	});
	$('#ContentBrowser-Pagination-Next').click(function(){
		if((cwp.manager.currentPageNum + 1) <= cwp.manager.totalPages){
			cwp.manager.selectedCat.showNextPage();
		}
		return false;
	});
	$('#ContentBrowser-Pagination-Previous').click(function(){
		if((cwp.manager.currentPageNum - 1) <= cwp.manager.totalPages){
			cwp.manager.selectedCat.showPreviousPage();
		}
		return false;
	});
	
	/* Lightbox */
	$(".Lightbox-Link").click(function(){
		$("#Lightbox-Frame").attr("src",$(this).attr("href"));
		$("#Lightbox-Container").show();
		return false;
	});
	$("#Lightbox-Close a").click(function(){
		$("#Lightbox-Container").hide();
		$("#Lightbox-Frame").attr("src","about:blank");
		return false;
	});
	
	/* currentPage selected */
	$("#currentPage").keydown(function(event){
		var keynum;
		if(window.event) // IE
		{
			keynum = window.event.keyCode;
		}
		else if(event.which) // Netscape/Firefox/Opera
		{
			keynum = event.which;
		}
		
		if(keynum == 13){
			cwp.manager.verifyPageInput();
			return false;
		}
	});
	
	/* currentPage selected*/
	$("#currentPage").blur(function(event){
		cwp.manager.verifyPageInput();
	});
	
	cwp.manager.verifyPageInput = function(){
		var userSelectedPageNum = parseInt($("#currentPage").val(),10);
		if (!userSelectedPageNum) {
			cwp.manager.updatePageNum();
		}else{
			if(userSelectedPageNum<1){
				userSelectedPageNum =1;
			}else if(userSelectedPageNum>cwp.manager.totalPages){
				userSelectedPageNum = cwp.manager.totalPages;
			}
			if(userSelectedPageNum!=cwp.manager.currentPageNum){
				cwp.manager.selectedCat.showUserInputPage(userSelectedPageNum);
			}else{
				cwp.manager.updatePageNum();
			}
		}
	};
	
	cwp.manager.updatePageNum = function(){
		$("#totalPage").html(cwp.manager.totalPages);
		$("#currentPage").val(cwp.manager.currentPageNum);
		if(cwp.manager.currentPageNum === 1){
			$("#ContentBrowser-Pagination-Previous").html("&#9668;");
		}else{
			$("#ContentBrowser-Pagination-Previous").html('<a class="" rel="previous" href="javascript:void(0);">&#9668;</a>');
		}
		
		if(cwp.manager.currentPageNum === cwp.manager.totalPages){
			$("#ContentBrowser-Pagination-Next").html('&#9658;');
		}else{
			$("#ContentBrowser-Pagination-Next").html('<a class="" rel="next" href="javascript:void(0);">&#9658;</a>');
		}
	};
	
	/* Dim */
	$("#VideoCentre-Dim").toggle(function(){
		$(".VideoPlayer").css('padding','0 0 0 0');
		$(".VideoPlayer").css('margin','2px 0 0 13px');
		$(this).show();
	},function(){
		$(".VideoPlayer").css('padding','2px 0 0 0');
		$(".VideoPlayer").css('margin','0 0 0 13px');
		$(this).hide();
	});
	
	/* Clip Descriptor */
	$("#ClipDescriptor-Content-Info").hover(
		function(){
			var pos = $("#ClipDescriptor-Content-Info").offset();  
			var width = $("#ClipDescriptor-Content-Info").width();
			var height = $("#ClipDescriptor-Content-Info").height();
			$("#ClipDescriptor-Content-InfoBox").css({"left":(pos.left+width+5)+"px","top":(pos.top-20)+"px"});
			$("#ClipDescriptor-Content-InfoBox").show();
		},
		function(){$("#ClipDescriptor-Content-InfoBox").hide();}
	);
	$(".Shows-Video a").removeAttr("href");

	/* Popup Category Menu */
	$(document).click(function(event){
		var popupShouldClose = true;
		$(event.target).parents().map(function(){if(this.id=="ContentBrowser-PopupMenu-Container" || this.id=="ContentBrowser-LeftMenu" || this.id=="breadcrumb"){popupShouldClose = false;}});
		if (popupShouldClose) $("#ContentBrowser-PopupMenu-Container").hide();
	});
	$(window).resize(function(){$("#ContentBrowser-PopupMenu-Container").hide();});
	$("#ContentBrowser-PopupMenu-Container").mouseleave(function(){
		$("#ContentBrowser-PopupMenu-Container").clearQueue().delay(1000).fadeOut(500,function(){$("#ContentBrowser-Tooltip-Container").css("left",-2000)});
	});
	$("#ContentBrowser-PopupMenu-Container").mouseenter(function(){
		$("#ContentBrowser-PopupMenu-Container").clearQueue().stop().fadeTo(1,1);
	});

	/* Tooltip Commands */
	$("#ContentBrowser-Tooltip-Container").mouseleave(function(){
		$("#ContentBrowser-Tooltip-Container").clearQueue().stop().fadeOut(250,function(){$("#ContentBrowser-Tooltip-Container").css("left",-2000)});
	});
	$("#ContentBrowser-Tooltip-Container").mouseover(function(){
		$("#ContentBrowser-Tooltip-Container").clearQueue().stop().fadeTo(1,1).show();
	});
	
	/* Social Toolbar Events */
	$(".socialtoolbar_button_twitter").click(function(){
		socialPopup($(this).attr('href'),800,450);
		$("#SocialToolbar-Embed-Close").trigger("click");
		$("#SocialToolbar-Email-Close").trigger("click");
		return false;
	});
	$(".socialtoolbar_button_facebook").click(function(){
		socialPopup($(this).attr('href'),800,300);
		$("#SocialToolbar-Embed-Close").trigger("click");
		$("#SocialToolbar-Email-Close").trigger("click");
		return false;
	});
	$(".socialtoolbar_button_embed").click(function(){
		if (!$("#SocialToolbar-Embed-Container").is(":visible") && !$(".socialtoolbar_button_embed").hasClass("NoEmbed")) {
			$("#SocialToolbar-Email-Close").trigger("click");
			$(".socialtoolbar_button_embed").addClass("Selected");
			$("#SocialToolbar-Embed-Container").slideDown();
		}else{
			$("#SocialToolbar-Embed-Close").trigger("click");
		}
		return false;
	});
	$(".socialtoolbar_button_email").click(function(){
		if (!$("#SocialToolbar-Email-Container").is(":visible")) {
			$("#SocialToolbar-Embed-Close").trigger("click");
			$(".socialtoolbar_button_email").addClass("Selected");
			$("#SocialToolbar-Email-Container").slideDown(function(){
			});
		}else{
			$("#SocialToolbar-Email-Close").trigger("click");
		}
	});
	$("#SocialToolbar-Email-Close").click(function(){
		$("#SocialToolbar-Email-Container").slideUp();
		$(".socialtoolbar_button_email").removeClass("Selected");
	});
	$(window).resize(function(){
		if ($("#SocialToolbar-Email-Container").is(":visible")) {
			var emailPosition = $("#SocialToolbar-Container").offset();
			$("#at16p").offset({left:emailPosition.left,top:(emailPosition.top+34)});
		}
	});
	$(".Disabled").removeAttr("href");
	$(".SocialToolbar-Icon").click(function(){
		tpController.pause(true);
	});
	$("#SocialToolbar-Embed-Code-Text").focus(function(){
		$("#SocialToolbar-Embed-Code-Text").select();
	});
	$("#SocialToolbar-Embed-Code-Text").click(function(){
		$("#SocialToolbar-Embed-Code-Text").select();
	});
	$("#SocialToolbar-Embed-Advanced-Checkbox").change(function(){
		populateEmbedCode("advanced");
	});
	$("#SocialToolbar-Embed-Size-Width").change(function(){
		populateEmbedCode("width");
	});
	$("#SocialToolbar-Embed-Size-Height").change(function(){
		populateEmbedCode("height");
	});
	$("#SocialToolbar-Embed-Close").click(function(){
		$("#SocialToolbar-Embed-Container").slideUp();
		$(".socialtoolbar_button_email").removeClass("Selected");
		return false;
	});

	/* Search Box */
	$("#ContentBrowser-Search-Text").focus(function(){
		if($("#ContentBrowser-Search-Text").val()=="Search for videos"){
			$("#ContentBrowser-Search-Text").val("");
			$("#ContentBrowser-Search-Text").addClass("ContentBrowser-Search-Text-Focus");
			$("#ContentBrowser-Search-Text-Clear").show();
		}
	});
	$("#ContentBrowser-Search-Text-Clear").click(function(){
		if (trySearchTimeout != null){
			clearTimeout(trySearchTimeout);
			trySearchTimeout = null;
		}
		cwp.manager.removeSearch();
		$("#ContentBrowser-Search-Text").removeClass("ContentBrowser-Search-Text-Focus");
		$("#ContentBrowser-Search-Text").val("Search for videos");
		$("#ContentBrowser-Search-Text-Clear").hide();
	});
	$("#ContentBrowser-Search-Text").blur(function(){
		if($("#ContentBrowser-Search-Text").val()==""){
			$("#ContentBrowser-Search-Text").removeClass("ContentBrowser-Search-Text-Focus");
			$("#ContentBrowser-Search-Text").val("Search for videos");
			$("#ContentBrowser-Search-Text-Clear").hide();
		}
	});
	
	$("#ContentBrowser-Search-Text").keydown(function(event){
		var keynum = 0;
		if(window.event) { // IE
			keynum = window.event.keyCode;
		}else if(event.which){ // Netscape/Firefox/Opera
			keynum = event.which;
		}
		//clear search timeouts
		if (trySearchTimeout != null){
			clearTimeout(trySearchTimeout);
			trySearchTimeout = null;
		}
		
		if (keynum == 13) {
			doSearch();
			return false;
		}
		else {
			trySearch();
		}
	});
	/* This sets focus to the flash player.  Cannot be done prior to this point without screwing with search binding */
	if(document.getElementById(cwp.flashID)){
		document.getElementById(cwp.flashID).focus();
	}

	$("#sortAirDate").click(function(){
		if(cwp.manager.currentSortingCriteria != "airdate"){
			removeSelectedSortingClass();
			cwp.manager.currentSortingCriteria = "airdate";
			$("#sortAirDate").addClass("Selected");
			cwp.manager.Descending.airdate = true;
			$("#sortAirDateArrow").html("&#9650;");
			cwp.manager.selectedCat.reloadCurrentPageBaseSorting("airdate", true);	
		}else{
			if(cwp.manager.Descending.airdate === true){
				cwp.manager.Descending.airdate = false;
				$("#sortAirDateArrow").html("&#9660;");
				cwp.manager.selectedCat.reloadCurrentPageBaseSorting("airdate", false);
			}else{
				cwp.manager.Descending.airdate = true;
				$("#sortAirDateArrow").html("&#9650;");
				cwp.manager.selectedCat.reloadCurrentPageBaseSorting("airdate", true);
			}
		}
		return false;
	});
	
	$("#sortAirDate").mouseover(function(){
		if(cwp.manager.currentSortingCriteria != "airdate"){
			$("#sortAirDateArrow").html("&#9650;");
		}else if(cwp.manager.Descending.airdate === true){
			$("#sortAirDateArrow").html("&#9660;");
		}else{
			$("#sortAirDateArrow").html("&#9650;");
		}
	});
	
	$("#sortAirDate").mouseout(function(){
		if(cwp.manager.currentSortingCriteria != "airdate"){
			$("#sortAirDateArrow").empty();
		}else if(cwp.manager.Descending.airdate === true){
			$("#sortAirDateArrow").html("&#9650;");
		}else{
			$("#sortAirDateArrow").html("&#9660;");
		}
	});
	
	$("#sortTitle").click(function(){
		if(cwp.manager.currentSortingCriteria != "title"){
			removeSelectedSortingClass();
			cwp.manager.currentSortingCriteria = "title";
			$("#sortTitle").addClass("Selected");
			cwp.manager.Descending.title = false;
			$("#sortTitleArrow").html("&#9660;");
			cwp.manager.selectedCat.reloadCurrentPageBaseSorting("title", false);
		}else{
			if(cwp.manager.Descending.title === true){
				cwp.manager.Descending.title = false;
				$("#sortTitleArrow").html("&#9660;");
				cwp.manager.selectedCat.reloadCurrentPageBaseSorting("title", false);
			}else{
				cwp.manager.Descending.title = true;
				$("#sortTitleArrow").html("&#9650;");
				cwp.manager.selectedCat.reloadCurrentPageBaseSorting("title", true);
			}
		}
		return false;
	});
	
	$("#sortTitle").mouseover(function(){
		if(cwp.manager.currentSortingCriteria != "title"){
			$("#sortTitleArrow").html("&#9660;");
		}else if(cwp.manager.Descending.title === true){
			$("#sortTitleArrow").html("&#9660;");
		}else{
			$("#sortTitleArrow").html("&#9650;");
		}
	});
	
	$("#sortTitle").mouseout(function(){
		if(cwp.manager.currentSortingCriteria != "title"){
			$("#sortTitleArrow").empty();
		}else if(cwp.manager.Descending.title === true){
			$("#sortTitleArrow").html("&#9650;");
		}else{
			$("#sortTitleArrow").html("&#9660;");
		}
	});
	
	$("#sortRequestCount").click(function(){
		if(cwp.manager.currentSortingCriteria != "requestCount"){
			removeSelectedSortingClass();
			cwp.manager.currentSortingCriteria = "requestCount";
			$("#sortRequestCount").addClass("Selected");
			cwp.manager.Descending.requestCount = true;
			$("#sortRequestCountArrow").html("&#9650;");
			cwp.manager.selectedCat.reloadCurrentPageBaseSorting("requestCount", true);
		}else{
			if(cwp.manager.Descending.requestCount === true){
				cwp.manager.Descending.requestCount = false;
				$("#sortRequestCountArrow").html("&#9660;");
				cwp.manager.selectedCat.reloadCurrentPageBaseSorting("requestCount", false);
			}else{
				cwp.manager.Descending.requestCount = true;
				$("#sortRequestCountArrow").html("&#9650;");
				cwp.manager.selectedCat.reloadCurrentPageBaseSorting("requestCount", true);
			}
		}
		return false;
	});
	
	$("#sortRequestCount").mouseover(function(){
		if(cwp.manager.currentSortingCriteria != "requestCount"){
			$("#sortRequestCountArrow").html("&#9650;");
		}else if(cwp.manager.Descending.requestCount === true){
			$("#sortRequestCountArrow").html("&#9660;");
		}else{
			$("#sortRequestCountArrow").html("&#9650;");
		}
	});
	
	$("#sortRequestCount").mouseout(function(){
		if(cwp.manager.currentSortingCriteria != "requestCount"){
			$("#sortRequestCountArrow").empty();
		}else if(cwp.manager.Descending.requestCount === true){
			$("#sortRequestCountArrow").html("&#9650;");
		}else{
			$("#sortRequestCountArrow").html("&#9660;");
		}
	});

	cwp.manager.loadSearchResult = function(userinput, searchQuery, season, episode, targetRelease, focusOnRelCat, RelealseCat){
		var searchCat = cwp.manager.createSearchCat();
		if(!targetRelease){
			searchCat.renderSearchResult(userinput, searchQuery, season, episode, function(){
				searchCat.select();
				searchCat.updateMenuBreadcrumb($(data.menuDiv).empty(), $(data.breadcrumbDiv).empty(), userinput);
				updateURLWithSearchInput(userinput);
			});
		}else{
			searchCat.renderSearchResult(userinput, searchQuery, season, episode, function(){
				var qs = new cwpQS();
				var targetPageNum = parseInt(qs.get("p",1),10); // Start searching at 1 if no page has been specified
				if(focusOnRelCat){
					if(RelealseCat){ 
						RelealseCat.loadUntilReleaseFound(targetRelease,targetPageNum,0,function(rel,targetPage){
							rel.select();
						});
					}
					searchCat.select();
					searchCat.updateMenuBreadcrumb($(data.menuDiv).empty(), $(data.breadcrumbDiv).empty(), userinput);
					updateURLWithSearchInput(userinput);
				}else{
					searchCat.loadUntilReleaseFound(targetRelease,targetPageNum,0,function(rel,targetPage){
						searchCat.select();
						if (targetPage!=1){
							searchCat.showSelectedPage(targetPage,1,true);	
						}
						searchCat.updateMenuBreadcrumb($(data.menuDiv).empty(), $(data.breadcrumbDiv).empty(), userinput);
						updateURLWithSearchInput(userinput);
						rel.select();
					});
				}
			});
		}
	};
	
	// First level category behaviours
	cwp.manager.makeContent = function(targetContainer,cat){ // method for rendering a category
		targetContainer.append("<li><a href='javascript:void(0);'>" + cwp.symbolsToEntities(cat.title) + "</a></li>");
		return targetContainer.children(":last").children(":last");
	};
	
	cwp.manager.makeBreadcrumb = function(targetContainer, cat, withAnchor){
		if (!data.isShowPage || cat.depth>1 || showPageNotFound){
			var title = cwp.symbolsToEntities(cat.title);
			if(cat.depth===0){title = "MAIN";}
		
			if(withAnchor){
				targetContainer.prepend('<h2><a href="javascript:void(0);">'+ title +'</a></h2><div class="ContentBrowser-TopContent-Arrow">&raquo;</div>');
				return targetContainer.children(":first").children(":last");
			}else{
				targetContainer.prepend('<h2>'+ title +'</h2>');
				return targetContainer.children(":first");
			}
		}else{
			return null;
		}
	};

	cwp.manager.removeSearchandText = function(){
		$("#ContentBrowser-Search-Text-Clear").click();
	};
	
	cwp.manager.makeSearchBreadcrumb = function(targetContainer, searchQuery){
		var title =  "SEARCH: " + cwp.symbolsToEntities(searchQuery);
		targetContainer.prepend('<h2><a href="javascript:void(0);" onclick="cwp.manager.removeSearchandText(); return false;">BACK</a></h2><div class="ContentBrowser-TopContent-Arrow">&raquo;</div><h2>'+ title +'</h2>');
		return targetContainer.children(":last").children(":last");
	};

	function displayCategoryPopup(cat, forceHide, pos, addLeft, addTop, arrowDir){
		if ((forceHide===true) || $("#ContentBrowser-PopupMenu-Container").is(":visible") && $("#ContentBrowser-PopupMenu-Container").css("top")==((pos.top+addTop)+"px")) {
			$("#ContentBrowser-PopupMenu-Container").hide();
			$.each(cat.children,function(indexShow,obj){
				obj.setUnrendered(true);
			});
		}else if (forceHide!==true){
			var listLength = 0;
			for(var i=0; i<cat.children.length; i++){
				if(cat.children[i].hasReleases)
					listLength++;
			}
			var listHeight = Math.ceil(listLength/3);
			$(".ContentBrowser-PopupMenu-ShowList").remove();
			var indexObj = 0;
			$.each(cat.children,function(indexShow,obj){
				if (obj.hasReleases){
					if ( indexObj%listHeight===0 ) {
						$("#ContentBrowser-PopupMenu-Content").append('<ul class="ContentBrowser-PopupMenu-ShowList"></ul>');
					}
					indexObj++;
					obj.renderHTML($(".ContentBrowser-PopupMenu-ShowList:last"),2,2);
					//obj.renderHTML($(".AllShows"),2,2);
				}
			});
			$("#ContentBrowser-PopupMenu-Container").css("visibility","hidden").show().removeClass().addClass("ContentBrowser-PopupMenu-"+cat.title.toUpperCase().split(' ').join(''));
			$("#ContentBrowser-PopupMenu-Tag").height($(".ContentBrowser-PopupMenu-ShowList").height()+25).css("background-position","15px "+($(".ContentBrowser-PopupMenu-ShowList").height()-140)+"px");
			$("#ContentBrowser-PopupMenu-Arrow").removeClass().addClass("ContentBrowser-PopupMenu-Arrow"+arrowDir);
			$("#ContentBrowser-PopupMenu-Container").css({"left":(pos.left+addLeft)+"px","top":(pos.top+addTop)+"px"}).css("visibility","visible");
		}
	}
	
	cwp.manager.catBreadcrumbClick(0, function(cat){
		clickTrack(cat.fullTitle);
		if(cat.children.length > 0) {
			$(data.menuDiv).empty();
			$.each(cat.children,function(i,obj){
				obj.renderHTML($(data.menuDiv),1,1);
			});
		}
		cat.makeBreadcrumb($(data.breadcrumbDiv).empty(), false);
		displayCategoryPopup(cat,true);
		cat.select();
	});
	
	cwp.manager.catSelect(0,function(cat){
		$(data.menuDiv).empty();
		if(cat.children.length > 0) {
			$.each(cat.children,function(i,obj){
				obj.renderHTML($(data.menuDiv),cat.depth+1,cat.depth+1);
			});
		}else{
			cat.parentCat.renderHTML($(data.menuDiv),cat.depth,cat.depth);
		}
		cat.makeBreadcrumb($(data.breadcrumbDiv).empty(), false);
		updateURLWithCategory(cat);
		cat.renderRelease();
		addDefaultSortingClass();
		updateCategoryTileAd(cat,data.adParameters);
	});

	cwp.manager.catUnselect(0,function(cat){
	});

	cwp.manager.catClick(1,function(cat){
		clickTrack(cat.fullTitle);
		if(cat.children.length > 10){
			displayCategoryPopup(cat,false,cat.element.offset(),cat.element.width(),-35,"Left");
		}else{
			displayCategoryPopup(cat,true);
			cat.select();
		}
	});
	
	cwp.manager.catBreadcrumbClick(1, function(cat){
		clickTrack(cat.fullTitle);
		if(cat.children.length > 10){
			displayCategoryPopup(cat,false,cat.breadcrumb.offset(),-10,cat.breadcrumb.height()-5,"Up");
		}else{
			displayCategoryPopup(cat,true);
			cat.select();
		}
	});
	
	cwp.manager.catSelect(1,function(cat){
		$(data.menuDiv).empty();
		if (cat.children.length > 0){
			$.each(cat.children,function(i,obj){
				obj.renderHTML($(data.menuDiv),2,2);
			});
			cat.makeBreadcrumb($(data.breadcrumbDiv).empty(), false);
		}
		updateURLWithCategory(cat);
		cat.renderRelease();
		addDefaultSortingClass();
		updateCategoryTileAd(cat,data.adParameters);
	});

	cwp.manager.catClick(2,function(cat){
		clickTrack(cat.fullTitle);
		displayCategoryPopup(cat.parentCat,true);
		$(data.menuDiv).empty();
		if (!cat.isSelected){displayCategoryPopup(cat,true);cat.select();}
	});
	
	cwp.manager.catBreadcrumbClick(2, function(cat){
		clickTrack(cat.fullTitle);
		if (!cat.isSelected){displayCategoryPopup(cat,true);cat.select();}
	});

	cwp.manager.catSelect(2,function(cat){
		$(data.menuDiv).empty();
		if(cat.children.length > 0) {
			$.each(cat.children,function(i,obj){
				obj.renderHTML($(data.menuDiv),cat.depth+1,cat.depth+1);
			});
		}else{
			cat.parentCat.renderHTML($(data.menuDiv),cat.depth,cat.depth);
		}
		cat.makeBreadcrumb($(data.breadcrumbDiv).empty(), false);
		updateURLWithCategory(cat);
		cat.renderRelease();
		addDefaultSortingClass();
		
		updateCategoryTileAd(cat,data.adParameters);
	});

	cwp.manager.catClick(3,function(cat){
		clickTrack(cat.fullTitle);
		if (!cat.isSelected){displayCategoryPopup(cat,true);cat.select();}
	});

	function generateSeaEpStr(rel){
		var retVal = "";
		if (rel.Season) {
			retVal += "S" + cwp.addLeadingZero(rel.Season);
		}
		if (rel.Episode){
			if (retVal.length>0){retVal+=" ";}
			if (rel.ClipType=="episode"){
				retVal += "E" + cwp.addLeadingZero(rel.Episode);
			}else{
				retVal += rel.Episode;
			}
		}
		return retVal;
	}

	cwp.manager.relRendering = function(targetContainer, rel){
		var titleStr = cwp.symbolsToEntities(rel.title);
		if (rel.Part){titleStr += " (" + cwp.symbolsToEntities(rel.Part) + ")";}
		
		var clipURL = generateClipUrl(rel);
		
		var seStr = generateSeaEpStr(rel);
		var newElement = $("<div/>",{
			"class":"ContentBrowser-Thumb" + (rel.isSelected?" ContentBrowser-Thumb-Selected":""),
			id:"rel"+rel.ID
		}).append($("<a/>",{href:clipURL}
			).append($("<img/>",{
				alt:titleStr,
				src:rel.thumbnailURL,
				width:220,
				height:130
			})).append($("<span/>",{"class":"ContentBrowser-Thumb-Play"}))
		).append($("<ul/>",{"class":"ContentBrowser-Thumb-ShowDesc"}
			).append($("<li/>",{"class":"ContentBrowser-Thumb-ShowName"}
				).append($("<span/>",{"class":"ContentBrowser-Thumb-ShowName-Show"}).text(cwp.symbolsToEntities(rel.Show))
				).append($("<span/>",{"class":"ContentBrowser-Thumb-ShowName-Details"}).text(seStr))
			).append(
				$("<li/>",{"class":"ContentBrowser-Thumb-ShowTitle"}).text(titleStr)
			)
		).appendTo(targetContainer);
		
		return newElement;
	};
	
	cwp.manager.relClick(function(rel){
		return !rel.isSelected;
	});

	cwp.manager.relSelect(function(rel){
		if(rel.element){
			rel.element.addClass("ContentBrowser-Thumb-Selected");
		}
	});	
	
	cwp.manager.relUnselect(function(rel){
		if(rel.element){
			rel.element.removeClass("ContentBrowser-Thumb-Selected");
		}
	});	
	
	cwp.manager.relMouseenter(function(rel){
		//Hide then position the tooltip
		$("#ContentBrowser-Tooltip-Container").clearQueue().stop().fadeOut().delay(1000).fadeTo(1,0,function(){
			var pos = rel.element.offset();
			if(pos.left+ 520 < $(document).width()){
				$("#ContentBrowser-Tooltip-Container").css({"left":(pos.left+220)+"px","top":(pos.top-25)+"px"}).addClass("ContentBrowser-Tooltip-Right").removeClass("ContentBrowser-Tooltip-Left");
			}else{
				$("#ContentBrowser-Tooltip-Container").css({"left":(pos.left-260)+"px","top":(pos.top-25)+"px"}).addClass("ContentBrowser-Tooltip-Left").removeClass("ContentBrowser-Tooltip-Right");
			}
			//Populate Tooltip
			var d=new Date(rel.airdate);
			var dateString = d.toDateString();
			var dateStringArray = dateString.split(" ");
			if(dateStringArray.length == 4)
				var metaDateStr = dateStringArray[1] + " " + dateStringArray[2] + ", " + dateStringArray[3];
			else
				var metaDateStr = dateString;
				
			// Write the season/episode info, if available
			var seaEpStr = generateSeaEpStr(rel);
			if (seaEpStr.length>0){metaDateStr += " - " + seaEpStr;}

			$("#ContentBrowser-Tooltip-Meta-Date").html(metaDateStr);
			$("#ContentBrowser-Tooltip-Meta-Show").text(cwp.symbolsToEntities(rel.Show));
			$("#ContentBrowser-Tooltip-Meta-Length").html("Length: " + cwp.convertLength(rel.length));
			$("#ContentBrowser-Tooltip-Body-Title").html(rel.title);
			$("#ContentBrowser-Tooltip-Body-Desc").html(rel.description);
			try{ // Putting this in an exception handler so that when we get malformed start times, we don't screw up the page
				$("#ContentBrowser-Tooltip-Body-Cues").empty();
				if (rel.ChapterStartTimes){
					// If we have multiple start times, the first one happens at the beginning of the clip
					var clipURL = rel.element.children("a").attr("href");
					var partListStr = '<li>&raquo; <a href="' + clipURL + '">Part 1</a></li>';
					var clipbaseURL = clipURL.replace(/\#.*$/,"");
					var paddingCategory = clipURL.match(/\#.*$/)[0];
					var chapterStartTimes = rel.ChapterStartTimes.replace(/ /g,"").split(",");
					for (var i=0;i<chapterStartTimes.length;i++){
						var timeSplit = chapterStartTimes[i].split(":");
						var timeVal = 0;
						for (var j=0;j<timeSplit.length;j++){
							timeVal = timeVal*60+parseInt(timeSplit[j],10);
						}
						partListStr += '<li>&raquo; <a href="' + clipbaseURL + '&t=' + timeVal + paddingCategory +'">Part ' + (i+2) + '</a></li>';
					}
					$("#ContentBrowser-Tooltip-Body-Cues").append(partListStr);
				}
			}catch(e){
				cwp.logDebug("Failed to parse chapter start times correctly: " + rel.ChapterStartTimes);
			}
			//Show Tooltip
			$("#ContentBrowser-Tooltip-Container").fadeTo(250,1);
		});
	});
	
	cwp.manager.relMouseleave(function(rel){
		$("#ContentBrowser-Tooltip-Container").clearQueue().stop().fadeOut(250,function(){$("#ContentBrowser-Tooltip-Container").css("left",-2000);});
	});
	
	getCategories(data);
}

	var emptyCount = 0, blankAdCount = 0, goodTile = null, docWriteReplaced = false;
	function wipeDocWriteParams(){emptyCount = 0;blankAdCount = 0;goodTile = null;}
	function altDocWrite(str){
		if (str.length==0){
			emptyCount++;
		}else{
			if(str.indexOf("817-grey.gif")>-1){
				blankAdCount++;
			}else{
				goodTile = str;
			}
		}
		if (emptyCount==2 && goodTile!==null){
			// draw good tile (wallpaper is taken care of)
			var sponsorDiv = $(".ClipDescriptor-ContentAd");
			sponsorDiv.find(".tileContainer").html(goodTile);
			sponsorDiv.show();
			wipeDocWriteParams();
		}else if(emptyCount==2 && blankAdCount==1){
			// hide previous tile (wallpaper is taken care of)
			$(".ClipDescriptor-ContentAd").hide();
			wipeDocWriteParams();
		}else if(blankAdCount==2){
			// wipe wallpaper and tile
			$(".ClipDescriptor-ContentAd").hide();
			cwChangeWallpaperAd();
			wipeDocWriteParams();
		}else if(blankAdCount==1 && goodTile!==null){
			// wipe wallpaper and display tile
			var sponsorDiv = $(".ClipDescriptor-ContentAd");
			sponsorDiv.find(".tileContainer").html(goodTile);
			sponsorDiv.show();
			cwChangeWallpaperAd();
			wipeDocWriteParams();
		}
	}

	function handleClipSponsorTileAd(adUrl){
		if (typeof(adUrl)=="string"){
			if (!docWriteReplaced){
				document.write = altDocWrite;
				docWriteReplaced = true;
			}
			$(".ClipDescriptor-ContentAd .tileContainer").html("<script src='" + adUrl.replace("adi","adj") + "' type='text/javascript'/>");
		}
		return false;
	}

	function handleWallpaperAd(adUrl){
		if (typeof(adUrl)=="string"){
			if (!docWriteReplaced){
				document.write = altDocWrite;
				docWriteReplaced = true;
			}
			$(".wallpaperContainer").append("<script src='" + adUrl.replace("adi","adj") + "' type='text/javascript'/>");
		}
		return false;
	}
	// set defaults
	data.videoWidth = data.videoWidth || 608;
	data.videoHeight = Math.floor(data.videoWidth / 16 * 9 );
	data.clipsPerPage = data.clipsPerPage || 6;
	data.relThumbnailWidth = data.relThumbnailWidth || 220;
	data.relThumbnailHeight = data.relThumbnailHeight || 130;
	data.targetRelease = data.targetRelease || null;
	data.skipFlash = data.skipFlash || data.targetRelease===null;
	data.menuDiv = data.menuDiv || "#ContentBrowser-LeftMenu";
	data.breadcrumbDiv = data.breadcrumbDiv || "#breadcrumb";
	data.site = data.site || "shaw.showcase.ca"; 
	data.PID = data.PID || "sx9rVurvXUY4nOXBoB2_AdD1BionOoPy";
	data.playerTag = data.playerTag || "z/Showcase Video Centre";
	
	var qs = new cwpQS();
	data.sort = qs.get("s",null);
	data.auto = qs.get("auto",null);
	data.searchQuery = qs.get("searchQuery",null);
	data.searchSeason =  qs.get("searchSeason",null); 
	data.searchEpisode  =  qs.get("searchEpisode",null);
	
	activateFlashHashFix();

	// We are moving the initialization of the manager here so that we can include the release name in the flash	
	var initData = {
		categoryFields:"title,fullTitle;TileAd",
		releaseFields:"thumbnailURL,title,length,description,assets;Part,Clip Type,Web Exclusive,ChapterStartTimes",
		PID:data.PID,
		playerTag:data.playerTag,
		site:data.site,
		siteZone:data.siteZone,
		clipsPerPage: data.clipsPerPage,
		relThumbnailWidth: data.relThumbnailWidth,
		relThumbnailHeight: data.relThumbnailHeight,
		targetRelease: data.targetRelease
	};
	if (typeof(adSync)=="object"){
		initData.adParameters = data.adParameters = adSync.GetAdParameters(data.adParameters);
		adSync.adParams["tile"].callback = handleClipSponsorTileAd;
		adSync.adParams["wallpaper"].callback = handleWallpaperAd;
	}
	cwp.initThePlatform({swfFolder:"/video/swf/"});
	// initialize Canwest Player object
	cwp.init(initData);
	// Create ad trigger before writing flash to ensure that we get the first play start event
	cwp.manager.relOnVideoStart(function(rel,pdkEvent){
		// If the ad synching library is available, we will let it handle companion ads
		if (typeof adSync == "object"){
			adSync.TriggerVideoAdSynch(pdkEvent);
			if (!adHasTriggered && pdkEvent.data.isAd || pdkEvent.data.baseClip.isAd){
				adHasTriggered = true;
				$("#VideoPlayer-BigBox").show();
			}
		}
		// Now that we've located the release, it's time to load the information for the End of Clip Component
		populateEndOfClipComponent(rel);
	});

	var auto = (data.auto=="n")?"false":"true";
	
	addVideoEvtHandlers();

	if (!data.skipFlash){
		cwp.loadFlashObjects({
			width:data.videoWidth,
			height:data.videoHeight,
			suppressDimensionVars:true,
			akamaiRoot:akamaiRoot,
			rssURL:data.rssURL,
			targetContainer:playerDiv.substring(1),
			swfFolder:"/video/swf/",
			omnitureAccount:"canshowcase",
			comscoreSiteId:"7293795",
			omniturePlayerName:extractLongestCategory(data.targetRelease),
			gaAccount:"UA-840802-8",
			portal:"Showcase",
			targetRelease:data.targetRelease,
			initialTime:data.initialTime,
			companionAdInfo:"|bannerSizes=120x240,468x60,250x250,160x90,122x62,1x1|bannerRegions=sky,banner,bbox,button,tile,wallpaper",
			variables:{
				controlColor:"0xbebebe",
				controlHoverColor:"0xff0000",
				controlSelectedColor:"0xffffff",
				textBackgroundColor:"0x383838",
				textColor:"0xbebebe",
				autoPlay:auto,
				useDefaultPlayOverlay:"false",
				layoutURL:"FLASHPATH/metaLayout_Showcase.xml",
				skinURL:"FLASHPATH/skinShowcase.swf"
			},
			bgcolor:"0x131313"
		});
	}
	
	$(document).ready(function(){
		activatePNGFix();
		initializePlayerTemplate(data);
	});
}

