var cnnVideoUtils = {
	default_div			:	"playerarea",
	instance_count		:	0,
	cvp_swf				:	"http://i.cdn.turner.com/sivault/.element/swf/1.1/video/sivault_video.swf",
	players				:	[],
	play				:	function (video_id,context,h,w){
		var instance_id = this.instance_count;
		if (h===null || w===null) { h = 373; w = 662; }
		if (context === null) { context = 'main'; }
		this.players[instance_id] = new CVP({
			id : 'cvp_'+this.instance_count, 
			width : w, 
			height : h,
			flashVars : { contentId : video_id, context : context, wmode : 'transparent' },	
			embed : {
				containerSwf : this.cvp_swf,
				expressInstallSwf : 'http://i.cdn.turner.com/sivault/.element/swf/1.1/video/expressInstall.swf',
				options : {
					quality : 'high', bgcolor : '#000000', allowFullScreen : 'true', 
					allowScriptAccess : 'always', wmode : 'transparent'
				}
			}
		});
		this.players[instance_id].embedSWF(this.default_div);			
		this.instance_count++;
	},
	noflash				:	function(id) {
		var msg = '<a href="http://get.adobe.com/flashplayer/" target="_blank" class="msg">This video requires a Flash client to play. <br/> Please click here to download the latest version of Flash.<\/a>';
		if(navigator.userAgent.indexOf('iPad')>-1) {
			msg = '<a href="/video" target="_blank" class="msg">This video is not available for your device at this time. <br/> Please click here for more SI videos.<\/a>';
		}
		if (document.getElementById(id)) { document.getElementById(id).innerHTML = msg; }
		this.generic_ad();
	},
	generic_300x250		:	'http://ad.doubleclick.net/adi/3475.si/video/;path=video;file=index_html;dcove=d;sz=300x250;tile=2',
	generic_ad			:	function() {
		if (document.getElementById('ad300x250')) { document.getElementById('ad300x250').src = this.generic_300x250; }
		else if (typeof cnnPageOnload == 'function') {
			var old_func = cnnPageOnload;
			cnnPageOnload = function() {
				if (document.getElementById('ad300x250')) { document.getElementById('ad300x250').src = this.generic_300x250; }
				old_func();
			};
		}	
	},
	"last"				:	""
};


/* 
instantiate cvp
	videoId - video to play
	vArea - div id to embed player
	vContext - player context name
	vReturn - return the name of the player if mulitple players on the page (0,1)
	
	//need category and source value 
*/
// define global var for default player
var cnnCVP;
var cvpPlayers = new Array();
function cnnVideoNewPlayer(videoId, vArea, vContext, vReturn) {

	if (vArea.length == 0) { vArea = "player"+videoId;}
	if (vContext.length == 0) { vContext = "swim09";}
	var cvpTmp;	var vWidth; var vHeight; var autoStart = 1;
	if (vContext == "swim09small") {
		vWidth = 320; vHeight = 180;
    } else { 
		vWidth = 662; vHeight = 373;
	}

	
	/* Test for iPAD */
	if(navigator.userAgent.indexOf('iPad')>-1) {
		cnnVideoAlt( vWidth, vHeight, vArea, videoId, autoStart); return;
	}	
	
	cvpTmp = new CVP({
		id : 'cvp_'+videoId,
		width : vWidth,
		height : vHeight,
		flashVars : {
			contentId : videoId,
			context : vContext
		},
		embed : {
			containerSwf : 'http://i.cdn.turner.com/sivault/.element/swf/1.1/video/sivault_video.swf',
			expressInstallSwf : 'http://i.cdn.turner.com/sivault/.element/swf/1.1/video/expressInstall.swf',
			options : {
				quality : 'high',
    	        bgcolor : '#000000',
        	    allowFullScreen : 'true',
	            allowScriptAccess : 'always',
	            wmode : 'transparent'
			}
		}
	});
	cvpPlayers.push(cvpTmp);
	
	// return a new named player instance
	if (vReturn == 1 || vReturn == 'true') {
		cvpTmp.embedSWF(vArea);
		return cvpTmp;
	// else use default cnnCVP
	} else {
		cnnCVP = cvpTmp;
		cnnCVP.embedSWF(vArea);
	}
}

/* 
instantiate cvp
	videoId - video to play
	vArea - div id to embed player
	vContext - player context name
 */
function cnnVideoPlayer(videoId, vArea, vContext) {
	cnnVideoNewPlayer(videoId, vArea, vContext, 0);
}

/* ALTERNATIVE HTML5 PLAYER */
function cnnVideoAlt(width, height, domIdStr, videoId, autoStart) {
	cnn_html5video.init(width, height, domIdStr, videoId, autoStart);
}

var cnn_html5video = {
	"playerDomId"		:	"",
	"videoId"			:	"",
	"containerDomId"	:	"",
	"width"				:	662,
	"height"			:	373,
	"autoplay"			:	0,
	"headline"			:	"",
	"halfway"			:	0,
	"video"				:	"",
	"omniture_acct"	:	"aolturnersi",
	"init"				:	function(width, height, domIdStr, videoId, autoplay) {
		/* Object to be returned */
		// NO FLASH - WebKit
		this.height = height;
		this.width = width;
		this.autoplay = autoplay;
		this.playerDomId = domIdStr + '_html5videoplayer';
		this.videoId = videoId;
		this.containerDomId = domIdStr;
		var videoXmlUrl = '/.element/auto/video/tvp_mdf/'+this.videoId+'.xml';
		this.req = new XMLHttpRequest();
		this.req.onreadystatechange = function(response) {
			if(cnn_html5video.req.readyState!=4) { return;}
			cnn_html5video.request(response); 
		};
		this.req.open("GET", videoXmlUrl, true);
		this.req.send('');
	},
	
	"request" 			:	function(response) {
			this.halfway = 0;
			var data = this.req.responseText;
			var flvurl = false;
			var matchArr = data.match(/<file bitrate="1200"[^>]+>([^<]+)<\/file>/);
			if(matchArr) {
				flvurl = matchArr[1].replace(/\d+\.f4v/,'mp4');
				flvurl = flvurl.replace(/f[l4]v$/,'mp4');
				if (flvurl.indexOf('swimsuit')>-1) { flvurl = flvurl.replace(/\%[20\%]+/g,'.'); }
				if(flvurl.indexOf('mp4:turner-si/')>-1) {
					// DANPATRICK
					cnnVideoUtils.noflash(this.containerDomId); return;
				} else {
					flvurl = 'http://ht.cdn.turner.com/si/big/video/'+flvurl;
				}
			} else {
				cnnVideoUtils.noflash(this.containerDomId); return;
			}
			this.posterurl = '';
			matchArr = data.match(/<image name="lg" [^>]+>([^<]+)<\/image>/);
			if( matchArr) { this.posterurl = matchArr[1]; }
			matchArr = data.match(/<headline[^>]*>([^<]+)<\/headline>/);
			if( matchArr) { this.headline = matchArr[1]; }
			this.video = document.getElementById(this.playerDomId);
			if ( this.video !== null ) {
				this.video.setAttribute('poster',this.posterurl);
				this.video.setAttribute('src', flvurl);
			} else {
				document.getElementById(this.containerDomId).innerHTML = '';
				html = '<div class="html5player"><video id="'+this.playerDomId+'" width="'+this.width+'" height="'+this.height+'" poster="'+this.posterurl+'" '+
						'controls="controls" src="'+flvurl+'" ></video></div>';
				document.getElementById(this.containerDomId).innerHTML = html;
			}

			/* Add Trackers - none */
			this.video = document.getElementById(this.playerDomId);
			/* Omniture bug for Swimsuit */
			if (flvurl.indexOf('swimsuit')==-1) {
				this.video.addEventListener('playing', function () { cnn_html5video.event('playing'); }, false);
				this.video.addEventListener('timeupdate', function () { cnn_html5video.event('timeupdate'); }, false);
				this.video.addEventListener('ended', function () { cnn_html5video.event('ended'); }, false);
			}
			/* Other actions */
			cnnVideoUtils.generic_ad();
			if (window.mycarousel_itemList) { jQuery( '#mycarousel_homevideo' ).parent().hide(); }
			
	},
	"event"		:	function(event) {
		switch(event) {
			case 'playing':
				this.nielsen();
				this.omni('playing');
				/* pause T1 */
				if (window.cnnT1) { 
					cnnT1.play(false); 
					document.getElementById('cnnCredit').style.visibility="hidden";
				} 
				break;
			case 'timeupdate':
				if (this.halfway) { return; }
				if (this.video.currentTime / this.video.duration >= 0.5 ) {
					this.halfway = 1;
					this.video.removeEventListener( 'timeupdate', this, false );
					this.omni('halfway');
				}
				break;
			case 'ended':
				this.omni('ended');
				break;
			default:
				break;
		}
	},
	
	"nielsen"		:	function(){
		var bug = document.createElement('img');
		bug.setAttribute('src', 'http://secure-us.imrworldwide.com/cgi-bin/m?cc=1&ci=us-100120&c6=vc,c03&tl=dav0-HTML5&cg=HTML5&rnd='+Date.now().toString().slice( 0, -3 ) );
		document.getElementById(this.containerDomId).appendChild(bug);
	},
	"omni"	:	function(event){
		if (window.s_account) { this.omniture_acct = window.s_account; }
		/* Skip Vault */
		if (this.omniture_acct.indexOf('vault')>-1) { return; }
		var s = s_gi(this.omniture_acct);
		if (event == 'playing') {
		/* PLAYING */
			s.linkTrackVars = 'prop11,prop13,eVar7,eVar8,eVar9,channel,events';
			s.linkTrackEvents = 'event8';
			s.events = 'event8';
			s.channel = 'HTML5 SI';
			s.prop11 = 'video play|mainnull|' + this.videoId;
			s.prop13 = 'video player|HTML5';
			s.eVar7 = 'video play|mainnull|' + this.videoId; 
			s.eVar8 = 'video player|HTML5';
			s.eVar9 = '';
			s.tl( this, 'o', this.headline );
		} else if (event == 'halfway') {
		/* HALFWAY */
			s.linkTrackVars = 'eVar7,eVar8,eVar9,channel,events';
			s.linkTrackEvents = 'event11';
			s.events = 'event11';
			s.channel = 'HTML5 SI';
			s.eVar7 = 'video play|mainnull|' + this.videoId; 
			s.eVar8 = 'video player|HTML5';
			s.eVar9 = '';
			s.tl( this, 'o', this.headline );
		} else if (event == 'ended') {
		/* ENDED */
			s.linkTrackVars = 'eVar7,eVar8,eVar9,channel,events';
			s.linkTrackEvents = 'event12';
			s.events = 'event12';
			s.channel = 'HTML5 SI';
			s.eVar7 = 'video play|mainnull|' + this.videoId; 
			s.eVar8 = 'video player|HTML5';
			s.eVar9 = '';
			s.tl( this, 'o', this.headline );
		}
	}

};


/* Video Analytics  */
/* These variables are necessary for vidPlay, vidFiftyPercent, vidSeek to operate properly */
var hasScrubbed = false;
var isAuto = false;
var isHalf = false;
var isBuffering = false;
var isPaused = false;
var vidObj;
var videoPage = (location.pathname.indexOf('/video') === 0) ? 'main' :
		(location.pathname.indexOf('/swimsuit') === 0 || location.pathname.indexOf('_swimsuit') === 5) ? 'swimsuit' : 'other';

if(typeof console != 'undefined'){
	console.log('videoPage: ' + videoPage );
}

/* NEW */
function onVideoPlayerBegin(videoId) {
	for(var i=0; i<cvpPlayers.length; i++) {
		var cvpData = cvpPlayers[i].getContentEntry(videoId);
		var cvpObject = window.JSON.parse(cvpData);
		if (cvpObject.id == videoId) {
			if (cvpObject.source.toLowerCase() == 'nba') {
				cvpPlayers[i].setTrackingContext("nba");
			} else {
				cvpPlayers[i].setTrackingContext("si_default");
			}
		}
		try {
			siVideoBegin(cvpPlayers[i], videoId);
		} catch(e) {
			siLog.debug('onVideoPlayerBegin: '+e);
		};
	}
	siLog.debug('onVideoPlayerBegin: Complete');
}

function onVideoPlayerPlay(videoId) {
	for(var i=0; i<cvpPlayers.length; i++) {
		try {
			var cvpData = cvpPlayers[i].getContentEntry(videoId);
			var cvpObject = window.JSON.parse(cvpData);
			vidObj = cvpObject;
			if (cvpObject.id == videoId) {
				var path = window.location.pathname.substring(1);
				var path_array = path.split("/");
				var yearPattern = /\d+/;
				var swimsuitYear;
				var swimRes;
				if(path_array[0].indexOf("swimsuit") > -1){
					swimsuitYear = yearPattern.exec(path_array[0]);
					swimRes = (swimsuitYear != null ? swimsuitYear + "_swimsuit" : "swimsuit");
				}
				if((path_array[0] == "video" && path_array[1] == "") ||
				   (path_array[0] == swimRes && path_array[1] == "") ||
				   (window.location.pathname.indexOf('/vault/swimsuit/home/index.htm') === 0) ||
				   (window.location.hostname.indexOf("fannation.com") > -1)){
					isAuto = true;
				}
				if(isAuto != null && isAuto == false){
					trackMetrics({
						type: "video-start",
						data: {
							video: {
								title: cvpObject.headline,
								id: cvpObject.id,
								category: cvpObject.category,
								subcategory: cvpObject.subcategory,
								source: cvpObject.source
							}
						}
					});
					isAuto = true;
				} else {
					trackMetrics({
						type: "video-autostart",
						data: {
							video: {
								title: cvpObject.headline,
								id: cvpObject.id,
								category: cvpObject.category,
								subcategory: cvpObject.subcategory,
								source: cvpObject.source
							}
						}
					});
				}
			}
		} catch(e) {
			siLog.debug('onVideoPlayerPlay: '+e);
		};
		try {
			siVideoPlay(cvpPlayers[i], videoId);
		} catch(e) {
			siLog.debug('onVideoPlayerPlay: '+e);
		};
	}
	siLog.debug('onVideoPlayerPlay: Complete');
}

function onAdStarted(token, videoId) {
	for(var i=0; i<cvpPlayers.length; i++) {
		try {
			var cvpData = cvpPlayers[i].getContentEntry(videoId);
			var cvpObject = window.JSON.parse(cvpData);
			trackMetrics({
				type: "video-preroll",
				data: {
					video: {
						title: cvpObject.headline,
						id: cvpObject.id,
						category: cvpObject.category,
						subcategory: cvpObject.subcategory,
						source: cvpObject.source
					}
				}
			});
		} catch(e) {
			siLog.debug('onAdStarted: '+e);
		};
		try {
			siVideoAdStarted(cvpPlayers[i], videoId);
		} catch(e) {
			siLog.debug('onAdStarted: '+e);
		};
	}
	siLog.debug('onAdStarted: Complete');
}

function onVideoTrackingAdCountdown(seconds) {
	try {
		siVideoTrackingAdCountdown(seconds);
	} catch(e) {
		siLog.debug('onVideoTrackingAdCountdown: '+e);
	};
	//siLog.debug('onVideoTrackingAdCountdown: Complete');
}

function onVideoPlayerPlayHead(videoId, playheadTime, totalDuration) {
	for(var i=0; i<cvpPlayers.length; i++) {
		if(hasScrubbed != true){
			while((playheadTime > (totalDuration / 2)) && isHalf == false){
			 	try {
					var cvpData = cvpPlayers[i].getContentEntry(videoId);
					var cvpObject = window.JSON.parse(cvpData);
					if (cvpObject.id == videoId) {
						trackMetrics({
							type: "video-fifty_percent",
							data: {
								video : {
									title: cvpObject.headline,
									id: cvpObject.id,
									category: cvpObject.category,
									subcategory: cvpObject.subcategory,
									source: cvpObject.source
								}
							}
						});
					}
				} catch(e){
					siLog.debug('onVideoPlayerPlayHead: '+e);
				};
				isHalf = true;
				break;
			};
		};
		try {
			siVideoPlayHead(cvpPlayers[i], playheadTime, totalDuration);
		} catch(e) {
			siLog.debug('onVideoPlayerPlayHead: '+e);
		};
	}
	//siLog.debug('onVideoPlayerPlayHead: Complete');
} 

function onVideoPlayerCompleted(videoId) {
	for(var i=0; i<cvpPlayers.length; i++) {
		try {
			var cvpData = cvpPlayers[i].getContentEntry(videoId);
			var cvpObject = window.JSON.parse(cvpData);
			trackMetrics({
				type: "video-complete",
				data: {
					video: {
						title: cvpObject.headline,
						id: cvpObject.id,
						category: cvpObject.category,
						subcategory: cvpObject.subcategory,
						source: cvpObject.source
					}
				}
			});
			isHalf = false;
			isBuffering = false;
			isPaused = false;
			hasScrubbed = false;
		} catch(e) {
			siLog.debug('onVideoPlayerCompleted: '+e);
		};
		try {
			siVideoComplete(cvpPlayers[i], videoId);
		} catch(e) {
			siLog.debug('onVideoPlayerCompleted: '+e);
		};
	}
	siLog.debug('onVideoPlayerCompleted: Complete');
}

function onVideoPlayerPause(videoId, paused) {
	if(isBuffering == false){
		try {
			trackMetrics({
				type: "video-pause",
				data: {}
			});
		} 
		catch(e) {
			siLog.debug(e);
		};
		try {
			siVideoPause(cvpPlayers[i], videoId, paused);
		} catch(e) {
			siLog.debug(e);
		};
	}
	
	siLog.debug('onVideoPlayerPause: Complete');
	
	if(isPaused == false){
		isPaused = true;
	} else {
		isPaused = false;
	}
}

function onVideoPlayerBuffering(videoId, buffering){
	if(isPaused == false){
		try {
			trackMetrics({
				type: "video-pause",
				data: {}
			});
		} 
		catch(e) {
			siLog.debug(e);
		};	
	}
	
	siLog.debug('onVideoPlayerBuffering: Complete');
	
	if(isBuffering == false){
		isBuffering = true;
	} else {
		isBuffering = false;
	}
}

function onVideoTrackingSeek() {
	hasScrubbed = true;
	try {
		siVideoSeek();
	} catch(e) {
		siLog.debug(e);
	};
	siLog.debug('onVideoTrackingSeek: Complete');
}

function onVideoPlayerError(errorMessage) {
	siLog.debug('CVP error: '+errorMessage);
}


