var plDiv = "#cwpPlaylist", playerDiv = "#cwpPlayerDiv", cwpDetailsDiv = "#cwpCurrentReleaseDiv", fullPlayerDiv = "#cwpVCPlayer", releaseList = "#cwpReleaseList";
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.";
var akamaiRoot = "http://a123.g.akamai.net/f/123/41524/60m/webdata.globaltv.com/";
var ScriptRoot = akamaiRoot + "ScriptBuilder.ashx";
var cwpInitializing = true;

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){
			if ($(fullPlayerDiv).css("display")=="none"){
				$(fullPlayerDiv).show();
			}
			cwpLoadFlashObjects({finishPlayerOutput:true}); // Because of a FF bug, we have to wait until the div is fully visible before displaying the flash
			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"),1,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){
					for (var i=0;i<cwpManager.rootCats[0].children.length;i++){
						if (cwpManager.rootCats[0].children[i].hasReleases){
							cwpManager.rootCats[0].children[i].select();
							break;
						}
					}
				}
			}
		}else{
			if (key=="PID"){
				var constructedZone = location.href.match(/^(?:http\:\/{2})?[^\/]+((?:\/+[^\/.?]+)*)\/.*$/)[1].substring(1);
				var rel = cwpManager.getReleaseFromPid(id,constructedZone);
				// Display player
				if ($(fullPlayerDiv).css("display")=="none"){
					$(fullPlayerDiv).show();
				}
				cwpLoadFlashObjects({finishPlayerOutput:true}); // Because of a FF bug, we have to wait until the div is fully visible before displaying the flash
				// We do not perform a select because we do not have release details
				if (rel) rel.requestVideoPlay();
				for (var i=0;i<cwpManager.rootCats[0].children.length;i++){
					if (cwpManager.rootCats[0].children[i].hasReleases){
						cwpManager.rootCats[0].children[i].select();
						break;
					}
				}
			}
		}
	});
}

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"),1,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(data){
	// 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($(data.targetMenuContainer),1,1);
			// 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){
						cwpManager.rootCats[0].children[i].select();
						break;
					}
				}
			}
		});
	}
}

function initializePlayerTemplate(data){
	initData = {
		categoryFields:"title",
		releaseFields:"thumbnailURL,title,length,description;Part,Clip Type,Web Exclusive",
		PID:data.PID,
		playerTag:data.playerTag,
		hideEmptyCats:data.hideEmptyCats,
		site:data.site,
		siteZone:data.siteZone,
		syncPageTitle:true
	};
	if (adSync){
		initData.adParameters = adSync.GetAdParameters(data.adParameters);
	}
	// initialize Canwest Player object
	cwpInitializeManager(initData);
	cwpManager.miscFormatPageTitle(function(rel){
		return rel.title + " - Video Centre";
	});

	// First level category behaviours
	cwpManager.catRendering[1] = new catRender(function(targetContainer,cat){ // method for rendering a category
		targetContainer.append("<li" + (cat.isCollapseCat()?" class='cwpFeatured'":"") + "><h4><a href='javascript:void(0);'>" + symbolsToEntities(cat.title) + "</a></h4></li>");
		return targetContainer.children(":last").children(":last").children(":last");
	},function(targetContainer, rel){
		targetContainer.parent().after('<ul class="cwpMenuChildren" style="display:none"></ul>');
		return targetContainer.parent().next();
	});

	cwpManager.catClick(1,function(cat){
		if (!cat.isSelected){cat.select();}
	});

	cwpManager.catSelect(1,function(cat){
		if (!cat.releasesLoaded){startWaitingAnimation();}
		cat.loadChildren(function(){
			cat.showChildren($(plDiv),2,3);

			// Special case, if we have loaded the Featured category for the first time, load the next category with releases as well
			if (cwpInitializing){
				if (cat.parentCat.isCollapseCat()){
					for (var i=0;i<cwpManager.rootCats[0].children.length;i++){
						if (cwpManager.rootCats[0].children[i].hasReleases && !cwpManager.rootCats[0].children[i].isCollapseCat()){
							cwpManager.rootCats[0].children[i].select();
							break;
						}
					}
				}
				cwpInitializing = false;
			}
		});	
	});

	cwpManager.catUnselect(1,function(cat){
		if (!cat.parentCat.isCollapseCat()){
			cat.element.parent().removeClass(CWP_CLASS_SEL);
		}
	});

	// Third level category behaviours
	cwpManager.catRendering[2] = 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(2,function(cat){
		if (cat.isSelected){cat.unselect();}
		else{cat.select();}
	});

	cwpManager.catSelect(2,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(2,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(+)");
			}
		}
		//cat.element.parent().next().slideToggle("normal");
	});

	// Release behaviours
	cwpManager.relRendering = function(targetContainer,rel){
		var htmlStr = "";
		// Reproduce the header
		if (rel.parentCat.children[0]==rel && rel.depth<3){
			if (rel.parentCat.fullTitle=="GLBCVC/Health Headlines"){
				htmlStr += "<a href='http://ad.doubleclick.net/clk;222248436;6744467;o?http://www.pharmasave.com' target='_blank'><img src='/images/video/pharma_vid.jpg' width='698' height='40' alt='Sponsored by PHARMASAVE' style='margin-bottom:10px;' /></a>"
			}
			htmlStr += "<div class='cwpCategoryHeader'><h2>" + symbolsToEntities(rel.parentCat.title) + "</h2></div>";
			targetContainer.append(htmlStr);
		}
		htmlStr = '<div id="rel'+rel.ID+'" class="cwpRelease"><div class="cwpReleaseThumb">' +
			'<a href="javascript:void(0);"><img alt="" src="'+ rel.thumbnailURL + '" width="100" height="70"/></a><a class="cwpPlayButton" href="javascript:void(0);"></a></div>';
		switch (rel.ClipType){
			case "webisode":
				htmlStr += "<h5>" + symbolsToEntities(rel.title) + "</h5>";
				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 += "<h5>Episode " + symbolsToEntities(rel.Episode) + "</h5><p>" + titleStr + "</p>";}
				else{htmlStr += "<h5>" + titleStr + "</h5>";}
				break;
			case "other":
			default:
				titleStr = symbolsToEntities(rel.title);
				if (rel.Part){titleStr += "<br />  (" + symbolsToEntities(rel.Part) + ")";}
				if (rel.Episode){htmlStr += "<h5>" + symbolsToEntities(rel.Episode) + "</h5><p>" + titleStr + "</p>";}
				else{htmlStr += "<h5>" + titleStr + "</h5>";}
				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.parentCat.getFirstRelease(false)==rel && rel.parentCat.depth>1){
			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.select();
		rel.requestVideoPlay();
		$.scrollTo(0);
	});

	cwpManager.relSelect(function(rel){
		if ($(fullPlayerDiv).css("display")=="none"){
			$(fullPlayerDiv).slideDown("normal",function(){
				cwpLoadFlashObjects({finishPlayerOutput:true}); // Because of a FF bug, we have to wait until the div is fully visible before displaying the flash
			});
		} 
		
		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.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(data);
	cwpAjaxLinks();
}

/**********
* The first function called, which launches everything
**********/
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.videoWidth = data.videoWidth || 608;
	data.videoHeight = Math.floor(data.videoWidth / 16 * 9 )+20;

	if (!data.skipFlash){
		cwpLoadFlashObjects({
			skipPlayerOutput:true, // Because of a FF bug, we will not output the player flash until we have expanded that section
			width:data.videoWidth,
			height:data.videoHeight,
			akamaiRoot:akamaiRoot,
			rssURL:data.rssURL,
			targetContainer:playerDiv.substring(1),
			omnitureAccount:data.omnitureAccount || "canglobaltvnews",
			variables:{
				backgroundColor:"0x131313",
				controlBackgroundColor:"0x212025",
				controlColor:"0xffffff",
				controlFrameColor:"0x545759",
				controlHoverColor:"0xFFFFFF",
				controlSelectedColor:"0xFFFFFF",
				frameColor:"0x000000",
				pageBackgroundColor:"0x000000",
				playProgressColor:"0xB42816",
				scrubberColor:"0x79797B",
				scrubberFrameColor:"0x333333",
				scrubTrackColor:"0xFF0000",
				loadProgressColor:"0xFFFFFF",
				textBackgroundColor:"0x79797B",
				textColor:"0xFFFFFF",
				previewImageURL:data.overlayImage || ""
			},
			bgcolor:"0x131313"
		});
	}
	// Notify the player tracker that this player is in use
	var parsedLocation = window.location.href.replace(/(&|)(release|category)(ID|id|PID|pid)=[^&]*/,"").replace(/[?]$/,"");
	var sbStr = ScriptRoot + "?type=Video&u=" + escape(parsedLocation) + "&PID=" + data.PID + "&playerTag=" +data.playerTag;
	logDebug("Scriptbuilder: " + sbStr);
	//$.get(sbStr);
	$(document).ready(function(){initializePlayerTemplate(data);});
}
