var allEpisodeGroups ="";
changing = false;
changingPosition = false;
// videoSpeed = "Low";
function getVideoSpeed(){
// alert(document.cookie);
if(vidPrefCookie = /(video_preference)=([^;]+)/i.exec(document.cookie)){
if(vidPrefCookie[2]=="low"){
return "High";
 }
 else{
 return "High";
 }}

}
function hideAllEpisodes() {
var episodeDivs = allEpisodeGroups.split(",")
  var episodeDivs = allEpisodeGroups.split(",");
  for (i=0;i< episodeDivs.length-1;i++){
    document.getElementById(episodeDivs[i]+"Group").style.display = 'none';
  }
}
function changeColor(foreground,background,element){
	element.style.backgroundColor=background;
	// anchortags = element.getElementsByTagName('a');
	paragraphs = element.getElementsByTagName('p');
	headers =  element.getElementsByTagName('h3');
	for (j=0; j<paragraphs.length; j++){
		paragraphs[j].style.color=foreground;
		try{
		paragraphs[j].getElementsByTagName('a')[0].style.color=foreground;}
		catch(e){}
	}
        for (k=0; k<headers.length; k++){
                headers[k].style.color=foreground;
		try{
		headers[k].getElementsByTagName('a')[0].style.color=foreground;}
		catch(e){}
        }

}
function timeConvert(seconds){
newSeconds = (seconds%60);
if(newSeconds < 10 ){newSeconds = "0" + newSeconds }
var newTime = parseInt(seconds/60) + ":" + newSeconds;
return newTime;
}
function convertTime(timeToConvert){
	// alert(timeToConvert);

	timeArray = /(\d+):(\d+):(\d+)/.exec(timeToConvert);
	
	// alert(timeArray[1]);
	newTime = 3600*parseFloat(timeArray[1]) + 60*parseFloat(timeArray[2]) + parseFloat(timeArray[3]);
	// alert(newTime);
	return newTime;
}

function isComplete(){
	if(( currentDuration - PlayerObj.controls.currentPosition) < 2){		
		return true;
	}
	else{return false;}
}
function setAdsCookie(){
var tmpDate1=new Date();
var tmpDate2=new Date();
var tmpSeconds = tmpDate1.getSeconds() + (8*60);
tmpDate2.setSeconds(tmpSeconds);
var cookieE = document.cookie.indexOf(escape("playVideo") + '=');
if (cookieE == -1)
{
setCookie("playVideo", "playVideo", tmpDate2, "/");
}
}
function highlightVideo(thisVideo){
	allHighlighted = getElementsByClass(document,'(box|currentVideo)','div');
	for(i=0;i<allHighlighted.length;i++){
		changeColor("#2c2c69","#dcdcdc",allHighlighted[i]);
	}
	changeColor("#000000","#dcdcdc",thisVideo)
}
function checkIsNews(){
var newsTest = false;
var newsCookieTest = false;
var newsPageTest = false;
// var newsCookieTest = (/(playVideoNews)=([^;]+)/i.test(document.cookie) || /(playVideoWFive)=([^;]+)/i.test(document.cookie) || /(playVideoElevenP)=([^;]+)/i.test(document.cookie) || /(playVideoIdol)=([^;]+)/i.test(document.cookie) || /(playVideorelated)=([^;]+)/i.test(document.cookie));*>


var newsCookieTest = (/(playVideo)-([^;]+1)/i.test(document.cookie));
if (currentTabId == "News" || currentTabId == "ElevenP" || currentTabId == "WFive" || currentTabId == "Idol"){
newsPageTest = true;}

if(newsPageTest == true && newsCookieTest == true){
newsTest = true;
}
return newsTest;
}

function startVideo(clip_start,clip_end,video_link_High,video_link_Low,clip_caption,clip_id){

videoSpeed = getVideoSpeed();
if (videoSpeed == "Low" && (currentTabId=="News" || currentTabId=="related" )){
videoWidth="302";
videoHeight="257";
linkSpd = "lo";
videoLink = video_link_Low;
}
else {
videoWidth="417";
videoHeight="339";	
linkSpd = "hi";
videoLink = video_link_High;
}
currentStartTime = convertTime(clip_start);
currentDuration = convertTime(clip_end);

playAd = "true";

//cookieTestExpr = new RegExp("(playVideo"+ currentTabId +")=([^;]+)")*>
cookieTestExpr = new RegExp("(playVideo" + ")=([^;]+)")

var isNews = checkIsNews();

if(isNews ==true){
playAd="false";
}
else if(adCookie = cookieTestExpr.exec(document.cookie)){
if((currentTabId!="Shows" && !currentTabId.indexOf("VG")==0) ){
playAd="false";
}

}

if (currentTabId=="Shows") {
  var subgroupArray = clip_id.split("_");
  var subgroup = subgroupArray[0].substring(1);
  WMVWriter(videoWidth,videoHeight,videoLink, subgroup, clip_start, clip_end, linkSpd, playAd);
} else {
  WMVWriter(videoWidth,videoHeight,videoLink, currentTabId, clip_start, clip_end, linkSpd, playAd);
}
setTimeout(setAdsCookie,10000);
if(captionText = document.getElementById('clipCaption'))
{captionText.innerHTML = "Now Playing: " + clip_caption;}
// window.location.href="#" + clip_id;

if(currentVideo = document.getElementById(clip_id)){
	highlightVideo(currentVideo);
	nextVideo = getNextVideo(currentVideo);
	previousVideo = getPreviousVideo(currentVideo);
// if(document.all){
//	document.getElementById('videoLinks').scrollTop = currentVideo.offsetTop;
// }
// else{
//	document.getElementById('videoLinks').scrollTop = currentVideo.offsetTop -40;
// }
}
else{
// alert("not"+currentVideo);
	nextVideo = -1;
	previousVideo = -1;
	currentVideo = getElementsByClass(document,'currentVideo','div')[0];
}
}
function delayPlayNext(){
playCurrentByObject(nextVideo);
}
function delayPlayPrevious(){
playCurrentByObject(previousVideo);

}

function playCurrentVideo(){
playCurrentByObject(currentVideo);
}
function playPrevious(){
	if(previousVideo != -1){
setTimeout(delayPlayPrevious,20);}
}
function playCurrentByObject(thisVideo){
                clip_start = thisVideo.getAttribute('start_time');
                clip_end = thisVideo.getAttribute('end_time');
	
                video_link_High = thisVideo.getAttribute('video_high');
                video_link_Low = thisVideo.getAttribute('video_low');
                clip_caption = thisVideo.getAttribute('caption');
                clip_id= thisVideo.getAttribute('id');

// added so that ads on the shows tab are also categorized
subject= thisVideo.getAttribute('subject');
if(subject!="" && subject!=null){

currentTabId =  subject;
szone = getSzone();
}
                startVideo(clip_start,clip_end,video_link_High,video_link_Low,clip_caption,clip_id);}
function playNext(){
	if(nextVideo != -1){
setTimeout(delayPlayNext,20);
//		clip_start = nextVideo.getAttribute('start_time');
//		clip_end = nextVideo.getAttribute('end_time');
//		video_link_High = nextVideo.getAttribute('video_high');
//		video_link_Low = nextVideo.getAttribute('video_low');
//		clip_caption = nextVideo.getAttribute('caption');
//		clip_id= nextVideo.getAttribute('id');
//		startVideo(clip_start,clip_end,video_link_High,video_link_Low,clip_caption,clip_id);
		// alert('yes!');
	}
}

function getFirstVideo(thisContainer){
	
	playList = getElementsByClass(thisContainer,'(box|currentVideo)','div');
	return playList[0];	

}
function getPreviousVideo(thisVideo){
        container = thisVideo.parentNode
                playList = getElementsByClass(container,'(box|currentVideo)','div');

        for(i=0;i<playList.length;i++){
                if(playList[i] == thisVideo){currentVideoIndex = i}
        }
        if (currentVideoIndex == 0){
                // alert('this is the first one')
                return -1;
        }
        else{
                previousVideoIndex = currentVideoIndex-1;
                return playList[previousVideoIndex];

        }
}

function getNextVideo(thisVideo){
	container = thisVideo.parentNode
		playList = getElementsByClass(container,'(box|currentVideo)','div');
	
	for(i=0;i<playList.length;i++){
		if(playList[i] == thisVideo){currentVideoIndex = i}
	}
	if (currentVideoIndex == (playList.length - 1)){
		// alert('this is the last one')
		return -1;
	}
	else{
		nextVideoIndex = currentVideoIndex+1;
		return playList[nextVideoIndex];
	
		// alert('the next video is' + nextVideoIndex);
	}
}

function showCurrent(){

	navItemsContainer = document.getElementById('videoNav');
navItems =  getElementsByClass(navItemsContainer,'over','li');
if( navItems.length>=2){
currentTab = navItems[1]
}
else {
currentTab = navItems[0]
}	
				showTab(currentTab);


}

function unhighlight(section){
try{
	if(!document.getElementById(section + 'Group')){
	}
	else{
		document.getElementById(section+'Group').style.display = 'none';
	}
	document.getElementById(section).style.color = "#7c879e";
}
catch(e){}
}

function highlight(section){
	
	if(!document.getElementById(section + 'Group')){
	}
	else{
		document.getElementById(section+'Group').style.display = 'block';
	}
	if(section == "ETalk" || section == "Shows" || section == "Discovery"){
		document.getElementById('newsNav').style.visibility = 'hidden';
	}
	else{
		document.getElementById('newsNav').style.visibility = 'visible';

	}
	if(section=="NewsTab"){
		document.getElementById('NewsGroup').style.display = 'block';
		document.getElementById('News').style.color = '#adb5c5';
	}
	if(section == "related" || section == "WFive" || section == "News" || section == "ElevenP" || section == "Docs"){
try{		document.getElementById("NewsTab").style.color = "#adb5c5";}
catch(e){}
	}
	document.getElementById(section).style.color = "#adb5c5";
}

function showTab(thisTab){

	currentTabId =	thisTab.getAttribute('id');
	unhighlight('related');
	unhighlight('News');
	unhighlight('ETalk');
	unhighlight('Shows');
	unhighlight('ElevenP');
	unhighlight('WFive');
	unhighlight('NewsTab');
//        unhighlight('Discovery');
	unhighlight('Docs');
hideAllEpisodes();
	// highlight current tab
	highlight(currentTabId);
if(currentTabId=="News" || currentTabId=="related"){
document.getElementById('videoSpeedControls').style.display = "block";
}
else{document.getElementById('videoSpeedControls').style.display = "none";}
}

function autoPlay(thisTab){
if ( urlquery=/[\?\&]clipId=([^\&#]+)/.exec(location.href)){
// alert(urlquery);
newTab = urlquery[1];
nextVideo = document.getElementById(newTab);
}else{
currentTab = document.getElementById(thisTab);
currentGroup = document.getElementById(thisTab + "Group");
showTab(currentTab);
newTab =  getURLParam("vid");
if ( newTab!=""){
nextVideo = document.getElementById(newTab);
} else {
nextVideo = getFirstVideo(currentGroup);
previousVideo = -1;
}
}

playNext();
}


function popUpLink(thisURL){
	if(!window.opener){
		window.location.href=thisURL
	}
	else{
		window.opener.location.href=thisURL;
		window.opener.focus;
	}
}

function setVideoPref(p_pref, p_vidtype)
{
// alert(currentVideo)
	var tmpDate1 = new Date()
		var tmpDate2 = new Date(tmpDate1.getYear() + 2010, tmpDate1.getMonth(), tmpDate1.getDay())
		setCookie("video_preference", p_pref, tmpDate2, "/")

if(currentVideo){
playCurrentVideo()
}
else{
window.location.href = window.location.href;
}
}

function startVolume(thisEvent){
	changing=true;
	volPointerStart = thisEvent.clientX;
	document.attachEvent('onmousemove',checkVolume);
	document.attachEvent('onmouseup',stopVolume);


	
}
function startPosition(thisEvent){

	changingPosition=true;
	posPointerStart = thisEvent.clientX;
	document.attachEvent('onmousemove',checkPosition);
	document.attachEvent('onmouseup',stopPosition);
	
}
function checkPosition(){
	if(changingPosition==true){
	
		newPointerPosition = oldPointerPosition + ((event.clientX - posPointerStart )  );
		if(newPointerPosition < 10){newPointerPosition=10}
		if(newPointerPosition > 396){newPointerPosition=396	}
//		currentVolume = ((newPointerPosition - 39) * 1.2);
		document.getElementById('positionButton').style.left=newPointerPosition+"px";
		
// newVol(PlayerObj,currentVolume);
}
	return false;
}
function checkVolume(){

	if(changing==true){
	
		newVolume = oldVolume + ((event.clientX - volPointerStart )  );
		if(newVolume < 30){newVolume=30}
		if(newVolume > 113){newVolume=113}
		currentVolume = ((newVolume - 39) * 1.2);
		document.getElementById('volumeButton').style.left=newVolume+"px";
newVol(PlayerObj,currentVolume);
	}
		
	return false;
}
function stopVolume(anObj){

	changing=false;
	document.detachEvent('onmousemove',checkVolume);
	document.detachEvent('onmouseup',stopVolume);
	oldVolume = newVolume;
}
function stopPosition(anObj){

	changing=false;
	document.detachEvent('onmousemove',checkPosition);
	document.detachEvent('onmouseup',stopPosition);
	oldPointerPosition = newPointerPosition;

	var totalTime =  parseInt(PlayerObj.currentMedia.duration);
	newPosition = ((newPointerPosition-10)/386)*totalTime;
	jumpToPosition(PlayerObj,newPosition)
}
function PlayIt(anObj){
		// check if method if available 
		if (anObj.controls.isAvailable('Play'))
        // start playback
			anObj.controls.play();
		document.getElementById('playPauseButton').src='http://images.ctv.ca/mar/images/video/pause4_button.gif';
}

function StopIt(anObj) {
		// check if method if available 
		if (anObj.controls.isAvailable('Stop'))
		// stop playback
		anObj.controls.stop();
}
function stopVideo(){
try{ StopIt(PlayerObj);
}
catch(e){}

}
function PlayPause(anObj){
	if(anObj.playState==3){
		PauseIt(anObj);
		
	}
	else{
PlayIt(anObj)
	}
}
function PauseIt(anObj) {
		// check if method is available
		if (anObj.controls.isAvailable('Pause'))
		// pause the movie
			anObj.controls.pause();
		document.getElementById('playPauseButton').src='http://images.ctv.ca/mar/images/video/play4_button.gif';
}

function ForwardIt(anObj) {
		//check if the method is available
if (anObj.controls.isAvailable('FastForward'))
        anObj.controls.fastForward();
}

function ReverseIt(anObj) {
		//check if the method is available
if (anObj.controls.isAvailable('FastReverse'))
        anObj.controls.fastReverse();
}

function NextIt(anObj) {
playNext();
}

function PreviousIt(anObj) {
playPrevious();
}

function muteClick(anObj) {
	if(anObj.settings.mute==true){
		anObj.settings.mute=false;
		document.getElementById('muteButton').src='http://images.ctv.ca/mar/images/video/mute4_off.gif';
	}
	else
	{
		anObj.settings.mute=true;
		document.getElementById('muteButton').src='http://images.ctv.ca/mar/images/video/mute4_on.gif';
	}
// anObj.settings.mute=(anObj.settings.mute ? false : true);
}

function startCheckingAds(){
var newAdURL= PlayerObj.currentMedia.getItemInfo('coAd')
if(newAdURL != ""){
doAd(newAdURL,currentTabId);
}
}

function simpleAd(){
if(!ord){var abc=Math.random()+"";var ord=abc.substring(2,abc.length);}
szone=getSzone();
sadpg=szone;
isbroadband=true;
placeRandom("728x90");
}

function loopAd(){
// alert(adLoop);
if(adLoop){
simpleAd();
	adLoop = setTimeout(loopAd,'60000');
}
}

function doAd(iframeSrc,hub){
var adString = "";
adString += '<iframe src="'+iframeSrc+'" id="adiframe" width="728" height="90" scrolling="no" frameborder="0"></iframe>';
adString += '<img src="http://adcounter.theglobeandmail.com/servlet/AdletCounter?ad1=ctv_Video'+hub+'Dart_728x90_ctv" width="1" height="1" border="0" alt="counter" style="display: none" />';
document.getElementById('728x90temp').innerHTML=adString;

}

function startCheckingTime(){
if(isIE && isWMV){
if(PlayerObj.playState == 6) {
document.getElementById('VideoPlayer').style.display = 'none';
document.getElementById('positionButton').style.display = 'none';
}

// alert(PlayerObj.playState);
if(((PlayerObj.playState == 3) || (PlayerObj.playState == 4) || (PlayerObj.playState == 5)) && !changingPosition){
document.getElementById('VideoPlayer').style.display = 'block';
document.getElementById('positionButton').style.display = 'block';
var currentTime = parseInt(PlayerObj.controls.currentPosition);

var totalTime =  parseInt(PlayerObj.currentMedia.duration);
// var displayTotal = convertTime(clip_end);
newPointerPosition = (( currentTime / totalTime ) * 386) + 10;
oldPointerPosition = newPointerPosition;
document.getElementById('positionButton').style.left=newPointerPosition+"px";
document.getElementById('time').innerHTML =  timeConvert(currentTime) + "/" + timeConvert(totalTime);

setTimeout(startCheckingTime,'1000');}
}
}

function fullScreenIt(anObj) {
anObj.DisplaySize = 3;
anObj.fullScreen = 'true';
}

// function to increase volume
function upVol(anObj){
	alert(anObj.settings.volume);
	anObj.settings.volume = anObj.settings.volume + 20;
}
function newVol(anObj,Volume){

	anObj.settings.volume = Volume;
}
function jumpToPosition(anObj,Position){
// playerPosition = ((Position -10)/386)*(convertTime(clip_start) + convertTime(clip_end));
anObj.controls.currentPosition = Position;
changingPosition = false;
startCheckingTime();
}
// function to decrease volume
function downVol(anObj){
	anObj.settings.volume = anObj.settings.volume -20;
}

function showAllEpisodes(thisTab) {
  currentTabId= thisTab;
szone = getSzone(); // for ads
  document.getElementById('ShowsGroup').style.display = 'none';
  hideAllEpisodes();
  currentGroup=document.getElementById(thisTab + "Group");
  currentGroup.style.display = "block";
  nextVideo = getFirstVideo(currentGroup);
  previousVideo = -1;
  playNext();
}

function getSzone(){
// if currentTabId is 'related', bzone is related plus the BN hub
if(currentTabId == "related"){
return "Video" + currentTabId + originHub;
}
else {return "Video" + currentTabId;}
}

//Disable right mouse click Script
//By Maximus (maximus@nsimail.com) w/ mods by DynamicDrive
//For full source code, visit http://www.dynamicdrive.com

var message="Function Disabled!";

///////////////////////////////////
function clickIE4(){
if (event.button==2){
// alert(message);
return false;
}
}

function clickNS4(e){
if (document.layers||document.getElementById&&!document.all){
if (e.which==2||e.which==3){
// alert(message);
return false;
}
}
}

if (document.layers){
document.captureEvents(Event.MOUSEDOWN);
document.onmousedown=clickNS4;
}
else if (document.all&&!document.getElementById){
document.onmousedown=clickIE4;
}

document.oncontextmenu=new Function("return false")

