var DD_belatedPNG;
var videos_visible;
var VideoController = {
	activateVideo: null,
	flowplayerUrl: '/videos/customer-widget/flowplayer-3.2.5.swf',
	analyticsCompanyKey: 'eCommera',
	analyticsTopicKey: 'Optimizing Online Marketing',
	analyticsActiveTab: 'Company',
	autoPlayCount: 0,
	autoPauseCount: 0,
	tabTriggerCount: 0,
	modalTriggerCount: 0,
	init: function() {
		VideoController.initTabs();
		VideoController.initCarousel();
		$('#ModalWrapper .videoCarousel li a').live('click', VideoController.thumbClick);
		$('.ui-widget-overlay').live('click', VideoController.closeModal);
		$('#ModalWrapper a.close').live('click', VideoController.closeModal);
		$('.customerWidgetContainer .videoCarousel li a, #VideoSpotlight a, #RHSBar a.customerVideo').live('click', VideoController.modalTriggerClick);
		$('.customerWidgetContainer a.viewAll').live('click', VideoController.modalTriggerClick);
		$('#ModalWrapper .videoInfo a').live('click', function() {
			// Pause videos on both tabs
			VideoController.pauseVideo(0);
			VideoController.pauseVideo(1);			
		});
		VideoController.initVideos();
		
		// Handle selecting a video based on URL value for iOS devices
		var pathname = document.location.hash.substr(1);
		if (pathname) {
			VideoController.activateVideo = pathname;
			VideoController.selectVideo();
		}
		VideoController.fixPngs1();
	},
	initVideos: function() {
		if (!!document.createElement('video').canPlayType)
			VideoController.initHtml5Videos();
		else
			VideoController.initIEVideos();	
	},
	initHtml5Videos: function() {
		$('#ModalWrapper .tabContent').each(function(j) {
			var $$ = $(this).find('video');
			if ($$.length == 0)
				return;
			
			var video = $$.get(0);
			video.addEventListener('play', VideoController.handleHtml5PlayEvent, false);
			video.addEventListener('pause', VideoController.handleHtml5PauseEvent, false);
			video.addEventListener('ended', VideoController.handleHtml5EndedEvent, false);
		});
	},
	handleHtml5PlayEvent: function() {
		// console.log("triggered play event - autoPlayCount: " + VideoController.autoPlayCount);
		// Don't track auto play events
		if (VideoController.autoPlayCount > 0) {
			VideoController.autoPlayCount--;
			return;
		}
		VideoController.trackVideoPlay();
	},
	trackVideoPlay: function() {
		cmCreatePageElementTag(
			'Play - ' + VideoController['analytics' + VideoController.analyticsActiveTab + 'Key'],
			VideoController.analyticsActiveTab + ' Video'
		);		
	},
	handleHtml5PauseEvent: function() {
		// console.log("triggered pause event");
		// Don't track auto pause events
		if (VideoController.autoPauseCount > 0) {
			VideoController.autoPauseCount--;
			return;
		}
		VideoController.trackVideoPause();
	},
	trackVideoPause: function() {
		cmCreatePageElementTag(
			'Pause - ' + VideoController['analytics' + VideoController.analyticsActiveTab + 'Key'],
			VideoController.analyticsActiveTab + ' Video'
		);		
	},
	handleHtml5EndedEvent: function() {
		VideoController.trackVideoEnd();
	},
	trackVideoEnd: function() {
		cmCreatePageElementTag(
			'End - ' + VideoController['analytics' + VideoController.analyticsActiveTab + 'Key'],
			VideoController.analyticsActiveTab + ' Video'
		);		
	},
	initIEVideos: function() {
		$('#ModalWrapper .tabContent').each(function(j) {
			// alert("initIEVideos");
			// var sources = this.getElementsByTagName("source");
			// var video_url = "";
			// for (var i = 0; i < sources.length; i++) {
			// 	var source = sources[i];
			//     			var type = source.getAttribute("type");
			//     			type = type.toLowerCase();
			//     			type = type.split(";", 1)[0];
			//     			if (type == "video/mp4") {
			//       				video_url = source.getAttribute("src");
			// 		break;
			// 	}
			// }

			// alert("pathname: " + VideoController.activateVideo.href + " && video_url: " + video_url);

			// By default don't autoplay
			var autoPlay = false;
			// If the video is visible, we want to autoplay, but only if the user has asked to view the video
			// that is already setup. If they want to view a different video (which is selected in a later
			// code block) having the autoplay enabled makes that other video not work.
			// if ($(this).is(':visible') && VideoController.activateVideo.href.match(new RegExp(video_url))) {
			// 	// alert("autoplay");
			// 	autoPlay = true;
			// }

			// alert("autoPlay: " + autoPlay);
			
			var config = {
				plugins: {
					controls: { autoHide: 'always', hideDelay: 1000 }				
				},
				clip: {
					// url: video_url,
					autoPlay: autoPlay,
					autoBuffering: true
				},
				onFinish: VideoController.handleFlowplayerFinishEvent,
				onPause: VideoController.handleFlowplayerPauseEvent,
				onStart: VideoController.handleFlowplayerStartEvent,
				onResume: VideoController.handleFlowplayerResumeEvent
			};
			var id = (j == 0) ? 'CustomersVideoPlayer' : 'QuestionsVideoPlayer';
			flowplayer(id, {
				src: VideoController.flowplayerUrl,
				version: [9, 115],
				wmode: 'opaque'
			}, config);
		});		
	},
	handleFlowplayerStartEvent: function() {
		// console.log("handleFlowplayerStartEvent");
		// Keep counts sane
		if (VideoController.autoPlayCount > 0) {
			VideoController.autoPlayCount--;
			return;
		}
	},
	handleFlowplayerResumeEvent: function() {
		// console.log("handleFlowplayerResumeEvent");
		// Don't track auto play events
		if (VideoController.autoPlayCount > 0) {
			VideoController.autoPlayCount--;
			return;
		}
		VideoController.trackVideoPlay();		
	},
	handleFlowplayerPauseEvent: function() {
		// console.log("handleFlowplayerPauseEvent - " + VideoController.autoPauseCount);
		// Don't track auto pause events
		if (VideoController.autoPauseCount > 0) {
			VideoController.autoPauseCount--;
			return;
		}
		VideoController.trackVideoPause();
	},
	handleFlowplayerFinishEvent: function() {
		VideoController.trackVideoEnd();		
	},
	initTabs: function() {
		$('#ModalWrapper .hideOnLoad').removeClass('hideOnLoad');
		$('#ModalWrapper .channel').tabs({
			// Prevent outline on selection
			select: function(event, ui) {
				// console.log("tab select event");
				$(ui.tab).blur();
				// Find index of tab to disable
				var idx = (ui.index == 1) ? 0 : 1;
				// And stop the video from playing
				VideoController.pauseVideo(idx);
			},
			show: function(event, ui) {
				// console.log("tab show event");
				// Init the carousel if necessary
				VideoController.initCarousel();
				if (ui.index == 0) {
					cmCreatePageElementTag("By Company Tab", "Video Player - 2010SummitCustomers Tab");
					VideoController.analyticsActiveTab = 'Company';
				} else {
					cmCreatePageElementTag("By Topic Tab", "Video Player - 2010SummitCustomers Tab");
					VideoController.analyticsActiveTab = 'Topic';
				}
				var $$ = $(ui.panel).find('li.active');
				if ($$.length == 0)
					$(ui.panel).find('.videoCarousel ul:first li:first').addClass('active');
				VideoController.tabTriggerCount++;

				// Since each tab switch plays the video, we want to track that
				// because the analytics will look odd if someone keep switching tabs
				// then pausing w/out playing
				if (VideoController.tabTriggerCount >= 2)
					VideoController.trackVideoPlay();
					
				// For testing w/out a modal
				if (VideoController.modalTriggerCount == 0 && VideoController.tabTriggerCount == 1)
					VideoController.trackVideoPlay();
					
				// And start the other video
				VideoController.unPauseVideo(ui.index);
			}
		});
	},
	selectTab: function(id) {
		$('#ModalWrapper .channel').tabs('select', id);
	},
	initCarousel: function() {
		var $$ = $('.videoCarousel:visible:not(.carouseled)');
		if ($$.length == 0)
			return;

		// no carousel in modal on iPad or iPhone
		if ($$.parents('#ModalWrapper').length > 0 && navigator.platform == "iPad" || navigator.platform == "iPod" || navigator.platform == "iPhone")
			return;
		
		$$.find('li.hideOnLoad').removeClass('hideOnLoad');
		var scroll = 1;
		if (videos_visible == 4)
			scroll = 4;
			
		if (! videos_visible)
			videos_visible = 6;

		// Only enable jCarousel if there are enough videos to warrant it
		if ($$.find('> ul > li').length <= videos_visible) {
			$$.addClass('carouseled');
			return;
		}
		
		$$.jcarousel({
			scroll: scroll,
			visible: videos_visible,
			// size: 8,
			wrap: 'both',
			buttonNextHTML: '<div />',
			buttonPrevHTML: '<div />'
		}).addClass('carouseled');
	},
	modalTriggerClick: function(e) {
		e.preventDefault();
		cmCreatePageviewTag("Video Player - 2010SummitCustomers", "Video Player");
		// iOS devices don't work to play in a modal
		if (navigator.platform == "iPad" || navigator.platform == "iPod" || navigator.platform == "iPhone") {
			window.open("/videos/customer-widget/index.html#" + this.pathname);
			return;
		}
		videos_visible = 6;
		VideoController.activateVideo = this;
		VideoController.modalTriggerCount++;
		$(this).parent().addClass('active').siblings('.active').removeClass('active');
		var $ModalContainer = $('#ModalContainer');
		var setupModal = false;
		var loadWidget = false;
		if ($ModalContainer.length == 0) {
			$ModalContainer = $('<div id="ModalContainer" />').hide();
			$('body').append($ModalContainer);
			setupModal = true;
			loadWidget = true;
		}
		// Firefox doesn't like to restart the video in a re-opened modal
		// so we need to reload the widget every time we open the modal
		if (loadWidget || $.browser.mozilla) {
			$ModalContainer.load('/videos/customer-widget/index.html #ModalWrapper', function() {
				VideoController.initTabs();
				if (setupModal)
					VideoController.setupModal();
				VideoController.openModal();
				VideoController.initCarousel();
				VideoController.initVideos();
				VideoController.selectVideo();
				VideoController.fixPngs2();
			});
		} else {
			VideoController.openModal();
			VideoController.selectVideo();
			VideoController.fixPngs2();
		}
	},
	closeModal: function(e) {
		e.preventDefault();
		$('#ModalContainer').dialog('close');
		// Pause videos on both tabs
		VideoController.pauseVideo(0);
		VideoController.pauseVideo(1);
	},
	setupModal: function() {
		$('#ModalContainer').dialog({
			autoOpen: false,
			modal: true,
			draggable: false,
			resizable: false,
			width: 800,
			height: 523,
			closeText: ''
		});
	},
	openModal: function() {
		$('#ModalContainer').dialog('open');
	},
	selectVideo: function() {
		if (VideoController.activateVideo) {
			// Support for having stored simple string pathname value
			var pathname;
			if (VideoController.activateVideo.pathname)
				pathname = VideoController.activateVideo.pathname;
			else
				pathname = VideoController.activateVideo;
			var $link = $('#ModalContainer a[href*="' + pathname + '"]');
			if ($link.length == 1) {
				// activate tab
				if (! $link.is(':visible')) {
					var id = $link.parents('.tabContent').attr('id');
					VideoController.selectTab('#' + id);
				}
				// play video
				VideoController.playVideo($link);
			}
		}
	},
	thumbClick: function(e) {
		e.preventDefault();
		cmCreatePageElementTag(
			VideoController.analyticsActiveTab
				+ ' - '
				+ VideoController['analytics' + VideoController.analyticsActiveTab + 'Key'],
			'Video Player Nav Tiles'
		);
		VideoController.playVideo($(this));
	},
	playVideo: function($link) {
		// console.log("called playVideo");
		var $$ = $link.parents('div.tabContent:first');
		var $li = $link.parent();
		VideoController.autoPlayCount++;

		// Ignore clicks on active item except in IE
		if ($li.hasClass('active') && !$.browser.msie)
			return;
		
		var data = $link.metadata();
		if ( data.analyticsKey )
			VideoController['analytics' + VideoController.analyticsActiveTab + 'Key'] = data.analyticsKey;

		var $relatedContent = $li.find('div.relatedContent');
		$$.find('.videoInfo p.nowPlaying').html($relatedContent.find('p.nowPlaying').html());
		$$.find('.videoInfo ul.relatedResources').html($relatedContent.find('ul.relatedResources').html());
		$li.addClass('active').siblings().removeClass('active');
		
		var pathname = $link.get(0).pathname;
		// Modern browsers
		if (!!document.createElement('video').canPlayType)
		{
			// Update H.264
			var sourceMP4 = $$.find("source[type^='video/mp4']").get(0);
			sourceMP4.src = pathname;

			// Update ogg
			// Switching src doesn't work so need to replace node in DOM
			var $sourceOgg = $$.find("source[type^='video/ogg']");
			var $new_sourceOgg = $sourceOgg.clone();
			$new_sourceOgg.attr('src', pathname.substring(0, pathname.length - 3) + 'ogv');
			$sourceOgg.replaceWith($new_sourceOgg);
			
			// Update WebM
			var sourceWebM = $$.find("source[type^='video/webm']").get(0);
			sourceWebM.src = pathname.substring(0, pathname.length - 3) + 'webm';
			
			var video = $(sourceMP4).parent().get(0);
			video.load();
			video.play();
		}
		
		// IE
		else {
			var id = $$.find('.videoContainer > div').attr('id');
			var player = flowplayer(id);
			VideoController.playIEVideo(player, pathname);
		}
		cmCreatePageElementTag(
			'Play - ' + VideoController['analytics' + VideoController.analyticsActiveTab + 'Key'],
			VideoController.analyticsActiveTab + ' Video'
		);
	},
	playIEVideo: function(player, pathname) {
		if (!player.isLoaded()) {
			setTimeout(function() { VideoController.playIEVideo(player, pathname); }, 1000);
			return;
		}
		// alert("player is ready");
		pathname = '/' + pathname;
		// player.stop();
		player.setClip({ url: pathname });
		player.play();
	},
	pauseVideo: function(idx) {
		// console.log("called pauseVideo");
		VideoController.autoPauseCount++;
		var $$ = $('.tabContent:eq(' + idx + ')');
		if (!! document.createElement('video').canPlayType)
		{
			var video = $$.find('video').get(0);
			if (video)
				video.pause();
		}
		
		else
		{
			var id = $$.find('.videoContainer > div').attr('id');
			var player = flowplayer(id);
			player.pause();
		}
	},
	unPauseVideo: function(idx) {
		// console.log("called unPauseVideo");
		VideoController.autoPlayCount++;
		var $$ = $('.tabContent:eq(' + idx + ')');
		if (!! document.createElement('video').canPlayType)
		{
			var video = $$.find('video').get(0);
			if (video)
				video.play();
		}
		
		else
		{
			VideoController.unPauseIEVideo($$);
		}		
	},
	unPauseIEVideo: function($$) {
		var id = $$.find('.videoContainer > div').attr('id');
		var player = flowplayer(id);
		if (player) {
			if (!player.isLoaded()) {
				setTimeout(function() { VideoController.unPauseIEVideo($$); }, 1000);
				return;
			}
			if (player.isPaused()) {
				player.play();			
			} else {
				// Not paused from before, figure out what video to play
				var sources = $$.get(0).getElementsByTagName("source");
				var video_url = "";
				for (var i = 0; i < sources.length; i++) {
					var source = sources[i];
	    			var type = source.getAttribute("type");
	    			type = type.toLowerCase();
	    			type = type.split(";", 1)[0];
	    			if (type == "video/mp4") {
	      				video_url = source.getAttribute("src");
					}
				}
				VideoController.playIEVideo(player, video_url);
			}
		}
	},
	fixPngs1: function() {
		if (DD_belatedPNG) { // Only execute for IE6
			// Selectors need to match what's in the CSS exactly
			// DD_belatedPNG.fix(' .jcarousel-prev, .jcarousel-next');
		}		
	},
	fixPngs2: function() {
		if (DD_belatedPNG) { // Only execute for IE6
			// Selectors need to match what's in the CSS exactly
			DD_belatedPNG.fix('#ModalWrapper');
		}		
	}

};
$(document).ready(VideoController.init);


var cmCreatePageElementTag;
if (! cmCreatePageElementTag) {
	cmCreatePageElementTag = function(id, category) {
		console.log("cmCreatePageElementTag: " + id + " [" + category + "]");
	};
}

var cmCreatePageviewTag;
if (! cmCreatePageviewTag) {
	cmCreatePageviewTag = function(id, category) {
		console.log("cmCreatePageviewTag: " + id + " [" + category + "]");
	};
}
