var waitingSection = 'SHOWS';
var authBool = false;
var currentBitrateId = "";
var isSwitching = false;
var hqBitrateId = "";
var standardBitrateId = "";
var defaultBitRate = "true";
var bitRateJson = "";
var switchingState = "switching";
var timeOutState = true;
var timeoutTimer;
var authVideoId = "";
var setState = false;
var provider = 'CartoonNetwork-VZ';
var bIsHD = false;
// swfLoadedvar = false;
logAdobe = false;


function checkFlashVersion() {
	var isFlashCurrent = FlashDetect.versionAtLeast(10, 1, 51);
	if (isFlashCurrent != true) {
//		document.getElementById('introSwfContainer').style.visibility = 'visible';

		jQuery.facebox('This website requires the Flash 10.1 (or higher) player.<br><br>You may upgrade your Flash plug-in by visiting the <a href="http://get.adobe.com/flashplayer/" style="color:black;text-decoration:underline;">Flash Download Center.</a><br><br>Please note you may need to reboot your system.');

	} else {
		// log("checkFlashVersion returing "+checkFlashVersion);
		return isFlashCurrent;
	}
}

function onVideoPlayerCompleted() {
}

function onAdStarted() {
//	var syncUrl = player.getCompanionAd('300x250');
	$('hdBtnBox').addClass('hiddenbox');
	// var syncUrl = TURNERPLAYER.getCompanionAd('300x250');
/*
	document.getElementById('advert').innerHTML = '<iframe id="banner_ad_iframe" width="300" scrolling="no" height="250" frameborder="0" style="position: absolute;" border="0" src="'
			+ syncUrl
			+ 'domId=banner_ad_iframe" marginwidth="0" marginheight="0" vspace="0" hspace="0">';
*/
}

function onVideoPlayerBegin(videoId) {
	// $('#adCountdown').html('now playing');
	try {
		player.emptyQueue();
		log('|-o-| player.emptyQueue')
	} catch (e) {
		try {
			this.emptyQueue();
			log('|-o-| this.emptyQueue')
		} catch (e) {
			log('|-o-| emptyQueue error: ' + e.name + ' : ' + e.message);
		}
	}

	Scenes.highlightPlaying(videoId);

	if (currentScenesArray.length > 0) {
		for ( var i = 0; i < currentScenesArray.length; i++) {
			if (currentScenesArray[i].videoId == videoId) {
				if ((i + 1) < currentScenesArray.length) {
					queueVideoId = currentScenesArray[(i + 1)].videoId;
					try {
						player.queue(currentScenesArray[(i + 1)].videoId);
						log('|-o-| player.queue')
					} catch (e) {
						try {
							this.queue(currentScenesArray[(i + 1)].videoId);
							log('|-o-| this.queue')
						} catch (e) {
							log('|-o-| queue error: ' + e.name + ' : '
									+ e.message);
						}
					}
					// TURNERPLAYER.queue(currentScenesArray[(i + 1)].videoId);
				}
			}
		}
	}
	// check and see if there's a segment/scene after the current video
}

function showMarketingSWF() {
	log("showMarketingSWF");
	cvpReady = false;
	try {
		document.getElementById('dramavisionReturnTNT').style.display = 'none';
	} catch (e) {
	}
	;
	try {
		document.getElementById('videoContainer').style.display = 'none';
	} catch (e) {
	}
	;
	try {
		document.getElementById('introSwfContainer').style.display = 'block';
	} catch (e) {
	}
	;
	// try{document.getElementById('logoutContainer').style.display =
	// 'inline';}catch(e){};
	log("@@-@@ logoutContainer");

	$('#logoutContainer').show();
	introSwf();
}

function onPlayerReady() {
	// log("onPlayerReady");
	cvpReady = true;
	if (waitingVideo != "") {
		$('#showTitleBox span').html(firstVidShow);
		$('#epiTitleBox span').html(firstVidTitle);
		var rateImgSrc = "http://i.cdn.turner.com/toon/tools/img/schedule/ratings/" + firstRating + ".gif";
		$('#infoRateBox img').attr('src',rateImgSrc);
		Dramavision.playScene(waitingVideo);
		waitingVideo == "";
	}
}

function onAdFinished(token, mode) {
	$('hdBtnBox').removeClass('hiddenbox');
//	document.getElementById('adCountdown').innerHTML = "now playing";
}

function onVideoTrackingAdCountdown(secs, mode) {
//	document.getElementById('adCountdown').innerHTML = '<b>Advertisement: The next video will start in  ' + secondsToTime(secs) + ' </b>';
}

function secondsToTime(secs) {
	var mins = Math.floor(secs / 60);
	var secs = secs % 60;
	return (tenify(mins) + ':' + tenify(secs));
}

function tenify(num) {
	return ((num < 10) ? ('0' + num) : num);
}

function checkExTime() {

	var cookieFullValue = $.cookie('authz_tv');
	if (cookieFullValue !== null) {
		var cookieExTime = cookieFullValue.substring(cookieFullValue
				.indexOf("|") + 1, cookieFullValue.lastIndexOf("|"));
		cookieExTime = cookieExTime * 1000;
		var d = new Date();
		var utc = d.getTime();

		if (utc >= cookieExTime) {
			setTimeout("location.reload(true);", 10);
		}
	}
}
function loadCVP() {
	player = new CVP(
			{
				id : 'cvp_1',
				width : '640',
				height : '360',
				flashVars : {
					contentId : '',
					context : 'main'
				},

				embed : {
					containerSwf : 'cartoonnetwork_video_f10.swf',
					expressInstallSwf : 'http://i.cdn.turner.com/xslo/cvp/assets/flash/expressInstall.swf',
					options : {
						quality : 'high',
						bgcolor : '#000000',
						allowFullScreen : 'true',
						allowScriptAccess : 'always'
					}
				},

				onPlayerReady : function() {
//					logOutput = document.getElementById("logger");
					log('Player is ready');
				},

				onAdPrerollUrl : function(videoId, adUrl) {
					log('onAdPrerollUrl');
					// returning false will skip the ad
				},

				onAdPostrollUrl : function(videoId, adUrl) {
					log('onAdPrerollUrl');
					// returning false will skip the ad
				},

				onAdStarted : function(token) {
				},

				onAdFinished : function(token) {
				},

				onAdError : function(message) {
				},

				onContentBegin : function(videoId) {
					var json = player.getContentEntry(videoId);
					var myObject = eval('(' + json.toString() + ')');

					//Utilities.log('json: ' + json);
					//Utilities.log('json.toString(): ' + json.toString());
					//Utilities.log('myObject: ' + myObject);
					//Utilities.log('myObject.tvemode: ' + myObject);
					//Utilities.log('Browse.newvid.tveMode: ' + Browse.newvid.tveMode);
					
					if (myObject.tveMode == 'C3') {
						if (provider == "CartoonNetwork-VZ") {
							player.setTrackingContext('short_interval_c3');
						} else {
							player.setTrackingContext('long_interval_c3');
						}
					} else if (myObject.tveMode == 'C4') {
						if (provider == "CartoonNetwork-VZ") {
							player.setTrackingContext('short_interval_c4');
						} else {
							player.setTrackingContext('long_interval_c4');
						}
					} else {
						player.setTrackingContext('clips');
					}
					bitRateJson = player.getAvailableBitrates('window');
					disableHQButton();
					if (bitRateJson != null) {
						for ( var i = 0; i < bitRateJson.length; i++) {
							if (bitRateJson[i].label == "standard") {
								standardBitrateId = bitRateJson[i].rateId;
							} else if (bitRateJson[i].label == "hq") {
								hqBitrateId = bitRateJson[i].rateId;
							}
						}
					}
					Dramavision.updateVideoInfo(videoId);
					// Dramavision.queueNext();
				},

				onContentBuffering : function() {
					//Utilities.log('Buffering: ' + this.isBuffering() + ' - ' + this.getBufferProgress());
				},

				onContentPlay : function() {
					Utilities.log("~~~~~~ Playing: " + player.getBitrateId() + ' : ' + bIsHD);
					if(bIsHD){
						showHDToggleOn();
					}
					if (bitRateJson == null) {
						disableHQButton();
					} else {
						enableHQButton();
					}
					Browse.bOverrideVid = false; // remove override
					//Utilities.log(':-o-: ' + Browse.bOverrideVid + ' :: ' + this.getContentEntry(this.getContentId()));

					document.getElementById("adCountdown").innerHTML = "";
				},

				onContentPlayHead : function() {
					// log('Playhead - ' + this.getPlayhead() + '...isPaused - '
					// + this.isPaused());
				},

				onContentStop : function(videoId) {
					log('Player - stopped');
				},

				onContentPause : function(videoId, paused) {
					log('Player - Paused( ' + this.getContentId() + ' ): '
							+ this.isPaused());
				},

				onContentCompleted : function() {
					log("Completed : " + this.getContentId());
				},

				onContentVolume : function(muted, volume) {
					document.getElementById('muteBt').disabled = muted;
					document.getElementById('unmuteBt').disabled = !muted;
					document.getElementById('volume05Bt').disabled = (volume == 0.5);
					document.getElementById('volume1Bt').disabled = (volume == 1);
				},
				onStreamSwitchComplete : function(newRate) {
					timeOutState = false;
					switchHD(newRate);
				},

				/***************************************************************
				 * Tracking callbacks
				 **************************************************************/
				onVideoTrackingAdClick : function(videoId, url) {
					log('Ad clicked( ' + videoId + ' ): ' + url);
				},

				onVideoTrackingProgress : function(videoId, percent) {
					log('Progress( ' + videoId + ' ): ' + percent);
				},

				onVideoTrackingLifetime : function(seconds) {
					log('Lifetime: ' + seconds);
				},

				onVideoTrackingFullscreen : function(videoId, fullscreen) {
					log('Fullscreen( ' + videoId + ' ): ' + fullscreen);
				},

				onVideoTrackingMuted : function(videoId, muted) {
					log('Muted( ' + videoId + ' ): ' + muted);
				},

				onVideoTrackingPaused : function(videoId, paused) {
					log('Paused( ' + videoId + ' ): ' + paused);
				},

				onVideoTrackingCompleted : function(videoId) {
					log('Completed( ' + videoId + ' ) ');
				},

				onVideoTrackingReplay : function(videoId) {
					log('Replay( ' + videoId + ' ) ');
				},

				onVideoTrackingPlay : function(videoId) {
					log('Play( ' + videoId + ' ) ');
				},

				onContentTrackingAdCountdown : function(secs) {
					log("onContentTrackingAdCountdown: " + secs);
					// document.getElementById("adCountdown").innerHTML =
					// 'ADVERTISEMENT: video will resume in ' + secs + ' secs';
				}
			});

	player.embedSWF("cvPlayer");
/*
	currentBitrateId = player.getBitrateId();
	isSwitching = false;

	if (currentBitrateId == standardBitrateId) {
		isSwitching = player.setBitrateId(hqBitrateId);
		showHDToggleOn();
	} else if (currentBitrateId == hqBitrateId) {
		isSwitching = player.setBitrateId(standardBitrateId);
		showHDToggleOff();
	}
*/
}
function loadCVP_OLDE() {
	// log("in tina loadCVP");
	if (checkFlashVersion()) {

		// document.getElementById('dramavisionReturnTNT').style.display =
		// 'block';
		var flashvars = {};
		flashvars.player = "main"; // player instance
		var params = {};
		params.quality = "high";
		params.bgcolor = "#000000";
		params.wmode = "transparent";
		params.allowFullScreen = "true";
		params.allowScriptAccess = "always";
		TURNERPLAYER.embedSWF("tools/swf/adultswim_video_staging_f10.swf",
				"playerarea", "992", "442", "/tve/expressInstall.swf",
				flashvars, params);
		// &accessEnablerUrl=https://entitlement.auth-staging.adobe.com/entitlement/AccessEnabler.swf
		// TURNERPLAYER.embedSWF("flash/dev/dev_container.swf?playerUrl=/flash/dev/TurnerPlayer.swf&configUrl=/tve/config.xml",
		// "playerarea", "684", "385", "/tve/expressInstall.swf", flashvars,
		// params);

		// http://i.cdn.turner.com/v5cache/TBS/mvpd/flash/dev/tve_dev_container20100318_f10.swf?playerUrl=http://i.cdn.turner.com/v5cache/TBS/mvpd/flash/dev/TurnerPlayer20100318_f10.swf&dmtdebug=true&configUrl=/tools/xml/tve_config.xml
	}
}

function introSwf() {
	log('introSwf');
//	$('#introSwfContainer').html('');
//	Slideshow.init();
	/*
	 * if (checkFlashVersion()) { var nav_fo = new
	 * FlashObject('/flash/tbs_tve_promo.swf', "featured", "992", "442", "8",
	 * "#000000"); nav_fo.addParam("quality", "high");
	 * nav_fo.addParam("AllowScriptAccess", "always"); nav_fo.addParam("wmode",
	 * "transparent"); nav_fo.addVariable("xmlPath",
	 * '/astv/mvpd/services/marketOutput.do?contentId=49046');///tve/marketOutput.jsp
	 * nav_fo.addVariable("baseURL",
	 * "http://i.cdn.turner.com/v5cache/TNT/flash/home/transitions");
	 * nav_fo.write("introSwfContainer"); }
	 */
}

function loadFromSWF(videoId, franchiseId) {
	TeaserArea.loadGrouper(videoId);
	Dramavision.loadRelated(videoId, franchiseId);
}

function faceboxLogin() {
	log("fbl");
	if (!AUTHBOOL) {
		getAuthorization("CartoonNetwork");
	}
	$.facebox.close();
}

function noAuthLogin() {
	log('{-o-} authBool ' + authBool)
	if (!authBool) {
		log("in noAuthLogin");
//		getAuthorization("CartoonNetwork");
	}
}

function checkAuth() {
	log('checkFlashVersion() ' + checkFlashVersion());
	var locString = location.href;

	if (locString.indexOf('www.cartoon') > -1 ) {
		swfSrc = "https://entitlement.auth.adobe.com/entitlement/AccessEnabler.swf";
	} else { 
		swfSrc = "https://entitlement.auth-staging.adobe.com/entitlement/AccessEnabler.swf";
	}

	if (checkFlashVersion()) {
		var nav_fo = new FlashObject(
				swfSrc,
				"AccessEnabler", "5", "5", "8", "#869ca7");
		nav_fo.addParam("quality", "high");
		nav_fo.addParam("wmode", "transparent");
		nav_fo.addParam("align", "middle");
		nav_fo.addParam("AllowScriptAccess", "always");
		nav_fo.addParam("logAdobe", "true");
		nav_fo.write("accessEnablerContainer");
	}
}

function checkExTime() {
	// not being used unless needed to check after a video is selected
}

function onAuthenticationError(errorType, errorMessage, errorCode) {
	switch (errorType) {
	case "code":
		log("Error code = " + errorCode);
		break;
	case "message":
		log("Error message = " + errorMessage);
		break;
	default:
		log("Unknown error type: " + errorType);
		break;
	}
}

function killCookies() {
}
function enableHQButton() {
	$('hdBtnBox').removeClass('hiddenbox');
}
function disableHQButton() {
	$('hdBtnBox').addClass('hiddenbox');
}
function showHDToggleOn() {
	if (player.getBitrateId() == hqBitrateId) {
		$('#hdBtnBox').addClass('hdboxon');
		$('#hdBtnBox').removeClass('hdbox');
	} else {
		showHDToggleOff();
	}
}
function showHDToggleOff() {
	//////alert('showHDToggleOff ' + player.getBitrateId());
	if (player.getBitrateId() == standardBitrateId) {
		$('#hdBtnBox').addClass('hdbox');
		$('#hdBtnBox').removeClass('hdboxon');
	} else {
		showHDToggleOn();
	}
}
function switchHD(newRate) {
	if (newRate == switchingState) {
		theLoadingButton();
	} else if (newRate == standardBitrateId) {
		showHDToggleOff();
	} else if (newRate == hqBitrateId) {
		showHDToggleOn();
	}
}
function hqReady() {
	var currentBitrateId = player.getBitrateId();
	var isSwitching = false;
	Utilities.log('!!!!!! hqReady: ' + currentBitrateId + ' :: ' + switchingState);
	if (currentBitrateId == standardBitrateId) {
		isSwitching = player.setBitrateId(hqBitrateId);
		showHDToggleOn();
		bIsHD = true;
		Utilities.log('@@@@@@ c=s: '+ player.getBitrateId() + '==' + standardBitrateId);
	} else if (currentBitrateId == hqBitrateId) {
		isSwitching = player.setBitrateId(standardBitrateId);
//		showHDToggleOff();
		bIsHD = false;
		Utilities.log('###### c=h: '+ player.getBitrateId() + '==' + hqBitrateId);
		$('#hdBtnBox').removeClass('hdboxon');
		$('#hdBtnBox').addClass('hdbox');
	}
	if (isSwitching) {
//		switchHD(switchingState);
	}
	Utilities.log('$$$$$$ switched: ' + currentBitrateId + ' :: ' + switchingState);
}

$(document).ready(function() {
	checkAuth();
	$("#logoutBtnBox").click(function() {
		logout();
	});
	
});
	
