var plDiv = "#cwpPlaylist", playerDiv = "#cwpPlayerDiv", cwpDetailsDiv = "#cwpCurrentReleaseDiv", fullPlayerDiv = "#cwpVCPlayer";
var sDetailsTitle = {normal:"You're Watching",ad:"Coming Up"};
var sDescTitle = {episode:"Episode Description",webisode:"Webisode Description",other:"Description",ad:"Advertisement"};
var sAdMessage = "Your video will play after this advertisement.";

function isCollapseCat(cat){
	return (cat.children.length==1 && cat.title==cat.children[0].title);
}

function expandDetails(doSlideIn){
	var sliderDiv = $("#relSlider");
	sliderDiv.stop(true,false);
	if (doSlideIn){
		if (sliderDiv.css("marginLeft")!="-290px"){
			sliderDiv.animate({marginLeft:"-290px"},(290+parseInt(sliderDiv.css("marginLeft")))/290*666);
		}
	}else if (sliderDiv.css("marginLeft")!="0px"){
		sliderDiv.animate({marginLeft:"0px"},parseInt(sliderDiv.css("marginLeft"))/-290*666);
	}
}

function performInitialAnimation(stepNum){
	if (stepNum==0){
		expandDetails(true);
		setTimeout("performInitialAnimation(" + (stepNum+1) + ")",6000);
	}else if (stepNum==1){
		expandDetails(false);
	}
}

function writeReleaseDetails(rel){
	var infoStr = sDetailsTitle.normal, info2Str = sDescTitle[rel.ClipType];
	var h3Str = "", h4Str = "", h5Str = "", pStr = "";
	if (rel.Show){h3Str += symbolsToEntities(rel.Show);}
	switch (rel.ClipType){
		case "episode":
			h4Str = symbolsToEntities(rel.title);
			if (rel.Season){h5Str += "Season " + symbolsToEntities(rel.Season) + ", ";}
			if (rel.Episode){h5Str += "Episode " + symbolsToEntities(rel.Episode) + ", ";}
			if (rel.Part){h5Str += symbolsToEntities(rel.Part) + ", ";}
			break;
		case "webisode":
			if (rel.Episode){h4Str = symbolsToEntities(rel.Episode);}
			if (rel.Part){h5Str += symbolsToEntities(rel.Part) + ", ";}
			break;
		case "other":
		default:
			if (rel.Episode){h4Str = symbolsToEntities(rel.Episode) + "<br />";}
			h4Str += symbolsToEntities(rel.title);
			if (rel.Part){h5Str += symbolsToEntities(rel.Part) + ", ";}
			break;
	}
	if (cwpManager.queuedRelease && rel.ID==cwpManager.queuedRelease.ID && cwpManager.firstPlayHappened){
		infoStr = sDetailsTitle.ad;
		info2Str = sDescTitle.ad;
		pStr = sAdMessage;
	}else if (rel.description){pStr = symbolsToEntities(rel.description);}
	h5Str += convertLength(rel.length);

	var htmlStr = "<div id='relSlider'><div id='relInfoDiv1'><h6 id='cwpRelInfo'>" + infoStr + "</h6>";
	if (h3Str){htmlStr += "<h3>" + h3Str + "</h3>";}
	if (h4Str){htmlStr += "<h4>" + h4Str + "</h4>";}
	if (h5Str){htmlStr += "<h5>" + h5Str + "</h5>";}
	htmlStr += "</div>";

	if (pStr){
		htmlStr += "<div id='relInfoDiv2'><h6 id='cwpRelInfo2'>" + info2Str + "</h6>";
		htmlStr += "<p id='cwpDesc'>" + pStr + "</p>";
		htmlStr += "</div>";
	}
	htmlStr += "</div>";

	$(cwpDetailsDiv).html(htmlStr);
	if ($("#relInfoDiv2").length>0){
		$("#relInfoDiv2").mouseenter(function(){expandDetails(true);});
		$("#relInfoDiv2").mouseleave(function(){expandDetails(false);});
		setTimeout("performInitialAnimation(0)",5000);
	}
};

function writeErrorDetails(heading,message){
	$(cwpDetailsDiv).html("<h6>" + heading + "</h6><p>" + message + "</p>");
}

function startWaitingAnimation(){$(plDiv).html("<div class='animFrame'></div>");}

function focusOnTargetRelease(key, id){
	cwpManager.fetchSingleRelease(key + "s",id,function(relExists){
		if (relExists){
			cwpManager.singleRelease.requestVideoPlay();
			// make this next line share code with the release select
			writeReleaseDetails(cwpManager.singleRelease);
			var cat = cwpManager.findFirstParentCategory(cwpManager.singleRelease);
			if (cat){
				var loadedCat = cat.loadChildrenAtDesiredDepth($("#playlist"),2,function(targetCat){
					targetCat.select();
					var rel = cat.getRelease(key,id);
					if (rel){rel.selectWithParents(1);}
					if (rel){cwpManager.setPlayingRelease(rel);}
					scrollToReleaseID = "#rel"+rel.ID;
				});
				if (!loadedCat){logError("Could not load category corresponding to target release.");}
			}
		}else{writeErrorDetails("!! Error !!","This video is no longer available.");}
	});
}

function focusOnTargetCategory(key, id){
	var cat = cwpManager.getCategory(key, id);
	// If we find the category and it has releases, or we should show empty categories
	if (cat && cat.hasReleases || !cwpManager.hideEmptyCats){
		var loadedCat = cat.loadChildrenAtDesiredDepth($("#playlist"),2,function(targetCat){
			targetCat.select();
			cat.selectWithParents(1);
			scrollToReleaseID = "#cat"+cat.ID;
		});
		if (!loadedCat){writeErrorDetails("!! Error !!","This category is no longer available.");}
	}else{writeErrorDetails("!! Error !!","This category is no longer available.");}
}

function getCategories(){
	// start loading the categories, use the callback to render
	if (cwpManager.rootCats.length===0){
		startWaitingAnimation();
		cwpManager.getCategories(function(){
			// Create list for categories and ask the manager to render all of them
			cwpManager.renderCategories($("#cwpMenu"),1,2);
			// Hook up the scrolling for the category menu
			var qs = new cwpQS();
			if (qs.contains("releaseID")){focusOnTargetRelease("ID",qs.get("releaseID"));}
			else if (qs.contains("releaseid")){focusOnTargetRelease("ID",qs.get("releaseid"));}
			else if (qs.contains("releasePID")){focusOnTargetRelease("PID",qs.get("releasePID"));}
			else if (qs.contains("releasepid")){focusOnTargetRelease("PID",qs.get("releasepid"));}
			else if (qs.contains("categoryID")){focusOnTargetCategory("ID",qs.get("categoryID"));}
			else if (qs.contains("categoryid")){focusOnTargetCategory("ID",qs.get("categoryid"));}
			else{
				for (var i=0;i<cwpManager.rootCats[0].children.length;i++){
					if (cwpManager.rootCats[0].children[i].hasReleases){
						var testCat = cwpManager.rootCats[0].children[i];
						testCat.select();
						// If this isn't a collapsed category, we have to select the first sub-category
						if (!isCollapseCat(testCat)){
							for (var j=0;i<testCat.children.length;j++){
								if (testCat.children[j].hasReleases){
									testCat.children[j].select();
									break;
								}
							}
						}
						break;
					}
				}
			}
		});
	}
}

function initializePlayerTemplate(data){
	initData = {
		categoryFields:"title,fullTitle,thumbnailURL",
		releaseFields:"thumbnailURL,title,length,description;Part,Clip Type,Web Exclusive",
		PID:data.PID,
		playerTag:data.playerTag,
		hideEmptyCats:data.hideEmptyCats,
		adParameters:data.adParameters,
		playAllInCat:data.playAllInCat,
		site:data.site,
		siteZone:data.siteZone
	};
	// initialize Canwest Player object
	cwpInitializeManager(initData);
	var autoplayTriggered = false;

	// First level category behaviours
	cwpManager.catRendering[1] = new catRender(function(targetContainer,cat){ // method for rendering a category
		targetContainer.append("<li><a href='javascript:void(0);'>" + symbolsToEntities(cat.title) + "</a></li>");
		var newTarget = targetContainer.children(":last").children(":last")
		if (isCollapseCat(cat)){
			newTarget.addClass("cwpNoSubcats");
		}
		return newTarget;
	},function(targetContainer, rel){
		targetContainer.after('<ul class="children"></ul>');
		return targetContainer.next();;
	});

	cwpManager.catClick(1,function(cat){
		if (cat.isSelected){cat.unselect();}
		else{cat.select();}
	});

	cwpManager.catSelect(1,function(cat){
		if (isCollapseCat(cat)){
			// Clicking this should have the same effect as depth 2 click
			if (cat.children.length>0) cat.children[0].select();
		}else{
			cat.element.parent().addClass(CWP_CLASS_SEL);
			cat.element.next().slideToggle("normal");
		}
	});

	cwpManager.catUnselect(1,function(cat){
		if (isCollapseCat(cat)){
			if (cat.children.length>0) cat.children[0].unselect();
		}else{
			cat.element.next().slideToggle("normal");
			cat.element.parent().removeClass(CWP_CLASS_SEL);
		}
	});
	
		// Second level category behaviours
	cwpManager.catRendering[2] = new catRender(function(targetContainer,cat){ // method for rendering a category
		targetContainer.append("<li>" + symbolsToEntities(cat.title) + "</li>");
		return targetContainer.children(":last");
	},function(targetContainer, rel){
		return targetContainer;
	});

	cwpManager.catClick(2,function(cat){
		if (!cat.isSelected){cat.select();}
	});

	cwpManager.catSelect(2,function(cat){
		if (!cat.releasesLoaded){startWaitingAnimation();}
		cat.loadChildren(function(){
			cat.showChildren($(plDiv),3,4);

			if (data.enableAutoplay && !autoplayTriggered){
				var rel = cat.getFirstRelease();
				if (rel){
					rel.requestVideoPlay();
					rel.select();
				}
				autoplayTriggered = true;
			}
		});	
	});

	cwpManager.catUnselect(2,function(cat){
		if (!isCollapseCat(cat.parentCat)){
			cat.element.parent().removeClass(CWP_CLASS_SEL);
		}
	});

	// Third level category behaviours
	cwpManager.catRendering[3] = new catRender(function(targetContainer,cat){ // method for rendering a category
		var htmlStr = "<div class='cwpCategoryHeader'><h2>" + symbolsToEntities(cat.title) + "</h2>";
		// If we have more than 12 items (and we aren't the only category), or we are not the first category and we have more than 6, we need to be able to expand
		if ((cat.children.length > 12 && cat.parentCat.children.length>1) || (cat.parentCat.children[0] != cat && cat.children.length>6)){
			htmlStr += "<a class='cwpPlaylistExpand' href='javascript:void(0);'>See All(+)</a>";
		}
		htmlStr	+= "</div>";
		targetContainer.append(htmlStr);
		return targetContainer.children(":last");
	},function(targetContainer, rel){
		targetContainer.after("<div class='cwpChildren'></div>");
		return targetContainer.next();
	});

	cwpManager.catClick(3,function(cat){
		if (cat.isSelected){cat.unselect();}
		else{cat.select();}
	});

	cwpManager.catSelect(3,function(cat){
		if ((cat.children.length > 12 && cat.parentCat.children.length>1) || (cat.children.length>6 && cat.parentCat.children[0]!=cat)){
			var itemHeight = cat.element.next().children(":first").outerHeight(true);
			cat.element.next().animate({height:itemHeight*Math.ceil(cat.children.length/6)},1000);
			cat.element.find(".cwpPlaylistExpand").html("Collapse(-)");
		}
	});

	cwpManager.catUnselect(3,function(cat){
		if (cat.children.length>6){
			var itemHeight = cat.element.next().children(":first").outerHeight(true);
			if (cat.children.length>12 && cat.parentCat.children[0]==cat){
				if (cat.parentCat.children.length>1){
					cat.element.next().animate({height:itemHeight*2},1000);
					cat.element.find(".cwpPlaylistExpand").html("See All(+)");
				}
			}else{
				cat.element.next().animate({height:itemHeight},1000);
				cat.element.find(".cwpPlaylistExpand").html("See All(+)");
			}
		}
	});

	// Release behaviours
	cwpManager.relRendering = function(targetContainer,rel){
		var thumbnailURL = rel.thumbnailURL;
		// If the release thumbnail is the default, replace it with the category thumbnail
		if (data.replaceDefaultThumbnail && rel.thumbnailURL==data.replaceDefaultThumbnail){
			thumbnailURL = rel.parentCat.thumbnailURL;
		}
		// If we aren't at depth 4 and we are outputting the first release, we need to re-use the category title
		if (rel.depth<4){
			if (rel.parentCat.children[0]==rel){
				var htmlStr = "<div class='cwpCategoryHeader'><h2>" + symbolsToEntities(rel.parentCat.title) + "</h2></div><div class='cwpChildren'></div>";
				targetContainer.append(htmlStr);
			}
			targetContainer = targetContainer.children(":last");
		}

		var htmlStr = "<div id='rel"+rel.ID+"' class='cwpRelease'><div class='cwpReleaseThumb'>" +
			"<a href='javascript:void(0);'><img alt='' src='"+ thumbnailURL + "' width='100' height='70'/></a><a class='cwpPlayButton' href='javascript:void(0);'></a></div>";
		switch (rel.ClipType){
			case "webisode":
				htmlStr += "<h3>" + symbolsToEntities(rel.title) + "</h3>";
				titleStr = "";
				if (rel.Episode){
					titleStr = symbolsToEntities(rel.Episode);
					if (rel.Part){titleStr += "<br /> (" + symbolsToEntities(rel.Part) + ")";}
				}else if (rel.Part){titleStr += symbolsToEntities(rel.Part);}
				if (titleStr){htmlStr += "<p>" + titleStr + "</p>";}
				break;
			case "episode":
				titleStr = symbolsToEntities(rel.title);
				if (rel.Part){titleStr += "<br />  (" + symbolsToEntities(rel.Part) + ")";}
				if (rel.Episode){htmlStr += "<h3>Episode " + symbolsToEntities(rel.Episode) + "</h3><p>" + titleStr + "</p>";}
				else{htmlStr += "<h3>" + titleStr + "</h3>";}
				break;
			case "other":
			default:
				titleStr = symbolsToEntities(rel.title);
				if (rel.Part){titleStr += "<br />  (" + symbolsToEntities(rel.Part) + ")";}
				if (rel.Episode){htmlStr += "<h3>" + symbolsToEntities(rel.Episode) + "</h3><p>" + titleStr + "</p>";}
				else{htmlStr += "<h3>" + titleStr + "</h3>";}
				break;
		}
		htmlStr += "</div>";
		targetContainer.append(htmlStr);
		var newElement = targetContainer.children(":last");
		// If this is the first release we are writing, let's figure out if we need to lock the height
		if (rel.depth>=4 && rel.parentCat.children[0]==rel){
			rel.parentCat.element.next().height(newElement.outerHeight(true)*Math.ceil(rel.parentCat.children.length/6));
			if (rel.parentCat.children.length>6){
				if (rel.parentCat.parentCat.children[0]==rel.parentCat){
					if (rel.parentCat.children.length>12 && rel.parentCat.parentCat.children.length>1){
						rel.parentCat.element.css("cursor","pointer");
						rel.parentCat.element.next().height(newElement.outerHeight(true)*2);
					}
				}else{
					rel.parentCat.element.css("cursor","pointer");
					rel.parentCat.element.next().height(newElement.outerHeight(true));
				}
			}
		}
		return newElement;
	};

	cwpManager.relClick(function(rel){
		rel.requestVideoPlay();
		$.scrollTo(0);
		rel.select();
	});

	cwpManager.relSelect(function(rel){
		if ($(fullPlayerDiv).css("display")=="none"){
			$(fullPlayerDiv).slideDown(0);
		}
		writeReleaseDetails(rel);
	});	

	cwpManager.OnPlayBlocked = function(blockPlay,rel){
		if (!blockPlay){
			// Replace the "wait on advertisement" text
			$("#cwpRelInfo").html(sDetailsTitle.normal);
			$("#cwpRelInfo2").html(sDescTitle[rel.ClipType]);
			if (rel.description){$("#cwpDesc").html(symbolsToEntities(rel.description));}
			else{$("#cwpDesc").remove();}
		}
	};

	cwpManager.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);
		}
	});

	cwpManager.OnPlayClick = function(){
		var rel = cwpManager.rootCats[0].getFirstRelease();
		if (rel){
			rel.requestVideoPlay();
			rel.selectWithParents(2);
		}
	};

	cwpManager.OnNoCategories = function(){
		$(plDiv).html("<div style='margin:20px;margin-top:20px !important;font-size:larger;'>There are currently no clips available for this player.  Please check back later.</div>");
	};
	getCategories();
	cwpAjaxLinks();
}

function insertScript(data, extraSwfParams){
	if (!data.skipFlash){
		var parsedLocation = window.location.href.replace(/[?].*/,"");
		var rootURL = parsedLocation.match(/^[^\/]*\/\/[^\/]*/);
		var playerURL = "&playerURL=" + escape(parsedLocation + "?releasePID={releasePID}");
		var rssURL = "&RSSURL=";
		if (data.rssURL){rssURL += escape(data.rssURL);}
		else{
			var akamaiRoot = ScriptRoot.replace(/[^\/\\]*$/,"");
			rssURL += escape(akamaiRoot + "MRSS.ashx?U=" + parsedLocation);
		}
		
		var sbStr = ScriptRoot + "?type=Video&u=" + escape(parsedLocation) + playerURL + rssURL + ((data.theme == "default")?"":"&theme="+data.theme) + "&width=" + data.videoWidth + "&height=" + data.videoHeight + "&PID=" + data.PID + "&playerTag=" +data.playerTag + "&name=" + playerDiv.substring(1);
		if (data.overlayImage){sbStr += "&plugin6=type=overlay|URL=/global/canwestPlayer/swf/ImageOverlayPlugin.swf|image_path=" + data.overlayImage;}
		if(extraSwfParams) {sbStr += extraSwfParams;}
		logDebug("Scriptbuilder: " + sbStr);
		$.ajaxSetup({cache:true});
		$.getScript(sbStr,function(){
			$(document).ready(function(){initializePlayerTemplate(data);});
		});
		$.ajaxSetup({cache:false});
	}else{
		$(document).ready(function(){initializePlayerTemplate(data);});
	}
}

function cwpInsertPlayer(data){
	// set defaults
	if(!ScriptRoot){alert("ScriptRoot must be defined somewhere in the page or the template.");}
	if(!data.PID){alert("You must specify the PID.");return;}
	if(!data.playerTag){alert("You must specify the playerTag.");return;}
	if(!data.site){alert("You must specify the site.");return;}
	data.theme = data.theme || "default";
	data.videoWidth = data.videoWidth || 400;
	data.videoHeight = Math.floor(data.videoWidth / 16 * 9 + 20);
	data.playerWidth = data.playerWidth || 400;
	data.playerHeight = data.playerHeight || data.videoHeight;
	// If the user hasn't specified adParameters, look for a global adParameters object
	data.adParameters = data.adParameters || window["adParametersVideo"] || window["adParameters"] || null;
	data.playAllInCat = (data.playAllInCat!==false);
	$(playerDiv).before('<div class="commManager" id="commManagerDiv"></div>');

	insertScript(data);
}

