// ========================================
// Requires jQuery
// ========================================

var FDMVideo = {

	player:	'',
	video:	'',
	content: '',
	ad: '',
	adPlaying: 0,
	clearSkin: 0,
	clearTimer: false,
	cuePoints: '',
	countEpisode: 1,
	visibleAgeGate: 0,
	adRulesReady: false,
	currentVideo: {
		videoseries: '',
		videoid:	0,
		videotitle:	'',
		episodenum:	''
	},
	initialize: function(series, id, title, episodenum) {
		console.log('initialize')
		FDMVideo.currentVideo.videoseries	= (series) ? series : '';
		FDMVideo.currentVideo.videoid		= (id) ? id : 0;
		FDMVideo.currentVideo.videotitle	= (title) ? title : '';
		FDMVideo.currentVideo.episodenum	= (episodenum) ? episodenum : '';
	},

	playCurrentTitle: function() {
		//asynchronous call, listen for mediaLoad when complete and fires doMediaLoad
		//FDMVideo.content.getMediaAsynch(FDMVideo.currentVideo.videoid);

		console.log('playCurrentTitle');
		tpController.pause(false);
	},

	playTitleFromList: function(videoid) {
		//asynchronous call, listen for mediaLoad when complete and fires doMediaLoad
		//FDMVideo.content.getMediaAsynch(videoid);
		console.log('playTitleFromList');
		tpController.pause(false);
	},
	onVideoLoad: function(event) {
	},

	// if success, FDMVideo.checkAdManager(event)
	AgeGate: function(event) {
		console.log('AgeGate');
		console.log(event.data)
		//if TV-MA we need an age gate
		var clipObj = event.data.baseClips[0];

		if (clipObj){

			if (clipObj.ratings){

				if(clipObj.ratings.length > 0){

					console.log('clipObj.ratings[0].rating:'+clipObj.ratings[0].rating)

					if(clipObj.ratings[0].rating == "TV-MA"){
						console.log('clipObj.ratings[0].rating == TV-MA')
						// begin age-gate
						var verified;
						this.jar = new CookieJar({
							expires:30* 1000 * 60 * 60 * 24,   // 30 days
							path: '/'
						});

						if(this.jar.get('age') == null){ //Cookie has not been previously set
							FDMVideo.showAgeGateForm();
							return;

						}else { //The cookie has been previously set
							verified = this.jar.get('age').verified;
							if (verified == false){
								console.log('showAgeGateFail')
								FDMVideo.showAgeGateFail();

							}else if (verified == true){

								//FDMVideo.showPlayer(event);
								FDMVideo.checkAdManager(event);
							}
						}

					}else{
						console.log('clipObj.ratings[0].rating != TV-MA')
						FDMVideo.checkAdManager(event);
					}
				}else{
					console.log('clipObj.ratings.length == 0')
					FDMVideo.checkAdManager(event);
				}

				// end age-gate

			}else{
				console.log('no clipObj.ratings')
				//	FDMVideo.showPlayer(event);
				FDMVideo.checkAdManager(event);
			}
		}else{
			console.log('no clipObj')
		}
	},

	// called from AgeGate - if ads ready, showPlayer()
	// if success, showPlayer(event)
	// TODO: validate that adds are stil being found to _fw_admanager with thePlatform player
	checkAdManager: function(event,count) {
		console.log('checkAdManager')

		if(!count) {
			count = 1;
		}
		if (window._fw_admanager && window._fw_admanager.version  && FDMVideo.adRulesReady){
			FDMVideo.showPlayer(event);
			console.log('AdManager: ready')
		}
		else {

			console.log('AdManager: not ready')
			FDMVideo.showPlayer(event);
			//setTimeout(function() { FDMVideo.checkAdManager(event,count); }, 50);
		}
	},

	// called from checkAdManager
	// calls initPlayer(), cueVideo(), play(), updateEpisodeInfo()
	showPlayer: function(event) {
		console.log('showPlayer')

		//$('player').show();
		if(event) {
			FDMVideo.initPlayer();	//hides age gate

			if(event.data.baseClips[0].URL) {
				//FDMVideo.video.cueVideo(event.media.id);
			}
			//FDMVideo.video.play();
			if(event.media.id) {
				FDMVideo.updateEpisodeInfo(event.media);
			}
		}

	},

	//called by AgeGate()
	showAgeGate: function() {
		console.log('showAgeGate');
		//set age gate flag
		FDMVideo.visibleAgeGate = 1;

		// need to stop current video
		//FDMVideo.video.pause(true);
		tpController.pause(true);
	},

	showAgeGateFail: function() {
		$('age-verification').show();
		$('age-verification-failed').show();
		FDMVideo.showAgeGate();
	},

	showAgeGateForm: function() {
		$('age-verification').show();
		$('age-verification-form').show();
		FDMVideo.showAgeGate();
	},

	initPlayer: function() {
		console.log('initPlayer')

		$('age-verification').hide();
		$('age-verification-form').hide();
		//unset age gate flag
		FDMVideo.visibleAgeGate = 0;
	},

	updateEpisodeInfo: function(video) {

		var displayStr = '';
		if(video) {
			FDMVideo.currentVideo.videotitle	= video.displayName;
			FDMVideo.currentVideo.videoid		= video.id;
			FDMVideo.currentVideo.episodenum	= video.referenceId;

			// Episode Title
			if(video.displayName) {
				displayStr += video.displayName + ', ';
			}
			if(video.customFields) {
				// Season
				if(video.customFields.season) {
					displayStr += 'Season ' + video.customFields.season + ', ';
				}
				// Episode Number
				if(video.customFields.episode) {
					displayStr += 'Ep ' + video.customFields.episode + ', ';
				}
			}
			// Duration
			if(video.length) {
				displayStr += FDMVideo.convertDuration(video.length);
			}

		}

		// Display Title
		$jq('#episodeDetails').text(displayStr);

		// change transparency for selected clip
		$jq('.thumbnailLink').css('opacity','1.0');
		$jq('.thumbnailLink[rel='+FDMVideo.currentVideo.videoid+']').css('opacity','0.4');
	},
	doCuePoint: function() {
		var pos = FDMVideo.video.getVideoPosition();
		if(pos != undefined || pos != 0) {
			//FDMVideo.doSubscriptions(Math.round(pos));
		}
	
	
	},
	
	doMediaLoad: function(e) {
		console.log('doMediaLoad')

		//if (FDMVideo.countEpisode != 1)
		//{
			if(e) {
				FDMVideo.AgeGate(e);
			}
		//}
		FDMVideo.countEpisode++;
	},
	

	doMediaStart: function() {
	},

	doMediaStop: function() {
	},

	// Called by the events dispatcher plugin
	doAdStart: function(e) {
		//if(e && e.type && (e.type == "preroll" || e.type == "midroll" || e.type == "postroll" || e.type == "brandedslate" || e.type == "interactive")) {
		//}
		FDMVideo.adPlaying = 1;
	},

	// Called by the events dispatcher plugin
	doAdEnd: function() {
		FDMVideo.adPlaying = 0;
	},

	// Called by Brightcove at the start of an ad (pod?).
	doPodStart: function(e) {
	},

	// Called by Brightcove at the end of an ad (pod?).
	doPodEnd: function() {
	},

	// Called by FreeWheel at the start of ad the pod.
	doAdPodStart: function() {
		if(FDMVideo.clearSkin == 1) {
			FDMVideo.clearBrandedSkin();
			FDMVideo.clearSkin = 0;
		}
	},

	// Called by FreeWheel at the end of ad the pod.
	doAdPodComplete: function() {
		FDMVideo.clearSkin = 1;
	},

	doPause: function() {
	},

	clearBrandedSkin: function() {
		var HTML = '<span id="brandedCanvas" class="_fwph"><form id="_fw_form_brandedCanvas" style="display:none"><input type="hidden" name="_fw_input_brandedCanvas" id="_fw_input_brandedCanvas" value="w=1500&h=423&envp=display&sflg=-nrpl;"></form><span id="_fw_container_brandedCanvas" class="_fwac"></span></span>';
		$jq('#playerAdBgSkin').html(HTML);
	},

	doSubscriptions: function(pos) {
	},

	message: function(str) {
	},

	setRating: function(num) {
		save_rating(num, 'thanks_rating_bottom');
	},

	getRating: function() {
		return get_rating_average_num(FDMVideo.currentVideo.videoseries, FDMVideo.currentVideo.videoid,'/fod/includes/user_reviews.php');
	},

	postReview: function(str) {
		document.getElementById("body_body").value = str;
		pluckgbl.postComment(str, "_body", true);
	},

	isLoggedIn: function() {
		return pluckgbl.cCheck('AT');
	},

	doLogin: function() {
		ActiveUser.doSignInClick();
	},

	doSignup: function() {
		open_signup_popup('signup');
	},

	convertDuration: function(duration) {
		duration = Math.floor(duration * 0.001);
		value = {
			years:		0,
			days:		0,
			hours:		0,
			minutes:	0,
			seconds:	0
		};

		if(duration >= 31556926) {
			value.years = Math.floor(duration/31556926);
			duration = (duration%31556926);
		}
		if(duration >= 86400) {
			value.days = Math.floor(duration/86400);
			duration = (duration%86400);
		}
		if(duration >= 3600) {
			value.hours = Math.floor(duration/3600);
			duration = (duration%3600);
		}
		if(duration >= 60) {
			minutes = String(Math.floor(duration/60));
			if(minutes.length < 2) { minutes = '0' + minutes; }
			value.minutes = minutes;
			duration = (duration%60);
		}
		seconds = String(Math.floor(duration));
		if(seconds.length < 2) { seconds = String('0' + seconds); }
		value.seconds = seconds;

		durationStr = (value.hours > 0) ? value.hours + ':' : '' +
			value.minutes + ':' +
			value.seconds;

		return durationStr;
	},

	adRulesReadyFn: function( e ){
		FDMVideo.adRulesReady = true;
	},

	thisMovie: function(movieName) {
		if (navigator.appName.indexOf("Microsoft") != -1) return window[movieName];
		else return document[movieName];
	}

};

function onTemplateLoaded(pEvent) {
	//FDMVideo.player		= brightcove.getExperience(pEvent);
	//FDMVideo.video		= FDMVideo.player.getModule(APIModules.VIDEO_PLAYER);
	//FDMVideo.content	= FDMVideo.player.getModule(APIModules.CONTENT);
	//FDMVideo.ad			= FDMVideo.player.getModule(APIModules.ADVERTISING);

	//FDMVideo.content.addEventListener(BCContentEvent.VIDEO_LOAD, FDMVideo.onVideoLoad);
	//FDMVideo.ad.addEventListener(BCAdvertisingEvent.AD_RULES_READY, FDMVideo.adRulesReadyFn);
	//FDMVideo.ad.addEventListener(BCAdvertisingEvent.AD_START, FDMVideo.doPodStart);
	//FDMVideo.ad.addEventListener(BCAdvertisingEvent.AD_COMPLETE, FDMVideo.doPodEnd);

	//FDMVideo.content.addEventListener("mediaLoad", FDMVideo.doMediaLoad);
	//FDMVideo.video.addEventListener("mediaBegin", FDMVideo.doMediaStart);
	//FDMVideo.video.addEventListener("mediaPlay", FDMVideo.doMediaStart);

	//FDMVideo.playTitleFromList(FDMVideo.currentVideo.videoid);
}

window.onunload = function() {
	/**
	 * Brightcove method
	 **
	 FDMVideo.thisMovie("myExperience").onOmnitureUnload(); //FoxOmniture.as
	 */

	/**
	 * thePlatform version?
	 **
	FDMVideo.thisMovie("_playerPdkSwfObject").onOmnitureUnload(); //FoxOmniture.as
	*/
};

$jq(document).ready(function() {

	/**
	*	Add click to video rows thumbnails
	*/
	$jq('.dashPageHolder .thumbnailLinkText, .dashPageHolder .thumbnailLink').bind('click',function(e) {

		e.preventDefault();

		if(FDMVideo.adPlaying == 0) {

			videoId	 = $jq(this).attr('rel');
			videoRef = $jq(this).attr('ref');
			//if(videoId != FDMVideo.currentVideo.id) {

				//FDMVideo.currentVideo.videoid = videoId;
				//FDMVideo.playTitleFromList(videoId);
				setReleaseCall(videoId);
			//}
		}
	});


	/**
	 *  rating disable for thePlatform?
	 **
	$jq('#subRateButton').bind('click',function(e) {
		e.preventDefault();
		FDMVideo.thisMovie("myExperience").showRateReviewMenu();
	});
	*/
});

if(typeof(console) == "undefined") {
	console		= new Object();
	console.log	= new Function();
}
