var nascarVideoPlayer;
var nascarDefaultImages = {
	'default': "url('http://i.cdn.turner.com/nascar/.element/img/2.2/sect/video/bg.aboveFold.jpg')",
	'speed': "url('http://i.cdn.turner.com/nascar/.element/img/2.1/sect/promos/speed/bg.aboveFold.png')"
};
function init_nascarVideoPlayer() {
	var _player = 'main';
	var _context = 'nascar';
	var _width = '640';
	var _height = '360';
	if (arguments.length != 0 ) {
		switch ( arguments[0] ) {
			case 'live':
				_player = 'live';
				_context = 'live';
				break;
			case 'hp':
				_player = 'homepage';
				_context = 'homepage';
				_width = '665';
				_height = '334';
				break;
			case 'Roush':
				_player = 'roush';
				_context = 'roush';
				_width = '464';
				_height = '266';
				break;
			case 'bristol':
				_player = 'bristol';
				_context = 'microsite';
				break;
		}
	}
	if ( location.search.indexOf('adTest') != -1 ) {
		// Change the player if requesting an ad test
		_player = 'mainTest';
		_context = 'nascarTest';
	}
	nascarVideoPlayer = new CVP({
		id: 'main',
		width: _width,
		height: _height,
		flashVars: {
			player: _player,
			context: _context
		},
		embed: {
			containerSwf: 'http://i.cdn.turner.com/nascar/.element/swf/2.2/sect/video/nascar_video.swf',
			options: {
				allowFullScreen: 'true',
				allowScriptAccess: 'always',
				wmode: 'transparent'
			}
		},
	    // Methodes
	    onPlayerReady: function () {
	        // Lets set the ad section
	        var _adSection = nascarVideoMappings[nascarVideoSection][nascarVideoCategory][nascarVideoSubcategory];
			_log_("Set ad section to " + _adSection);
	        if (_adSection) this.setAdSection(_adSection);
	        // Need to get the index of the current video, play it, and queue the rest
	        var index = nascarPlaylist.inArray(nascarVideoStartHere);
	        if (index == -1) {
	        	nascarPlaylist.unshift(nascarVideoStartHere);
	        	index = 0;
	        }
	        // Start at index, queue the rest; but don't if you're on the homepage
	        if (_player != 'homepage') {
	            this.play(nascarCleanVideoId(nascarPlaylist[index]));
	            _log_('Player Ready, calling this.play(' + nascarPlaylist[index] + ')');
	            var len = (nascarPlaylist.length - 1);
	            for (var i = index + 1; i <= len; i++) {
	                _log_('Queue video ' + i + ' of ' + len);
	                this.queue(nascarCleanVideoId(nascarPlaylist[i]));
	            }
	        }
	        else {
	        	document.getElementById('nascarVideoLoadingImage').style.display = 'none';
	        	var ele = document.getElementById('nascarVideoSlateImage');
	        	if (ele.addEventListener) {
	        		ele.addEventListener('click', nascarStartVideo, true);
	        	}
	        	else if (ele.attachEvent) {
	        		ele.attachEvent('onclick', nascarStartVideo);
	        	}
	        	$('#nascarVideoSlateImage').addClass('pointer');
	        }
	    },
		onContentPlay: function() {
			_log_("Playing: "+ this.getContentId() );

			sendVideoEvent(this.getContentEntry(this.getContentId()), "video-start");

			// Returns a string of JSON, this.getContentEntry(this.getContentId());
			var obj = null, str = this.getContentEntry(this.getContentId());
			eval('obj = '+ str);
			// Change out the healine and blurb, unless you're on the homepage
			if ( _player != 'homepage' ) {
				document.getElementById('cnnVideoHeadline').innerHTML = obj.headline;
				document.getElementById('cnnVideoBlurb').innerHTML = obj.description;
			}
			// Extend the playlist indefinitely, unless your'e on the homepage
			if (_player != 'homepage') {
				var index = nascarPlaylist.inArray('/video/'+ this.getContentId());
				var len = nascarPlaylist.length;
				if ( index == len - 1 ) {
					_log_("Last video, empty queue and requeue playlist");
					this.emptyQueue();
					// Queue playlist
					for ( var i = 0; i < len; i++ ) {
						_log_('Queue video '+( i + 1 )+' of '+ len);
						this.queue( nascarCleanVideoId(nascarPlaylist[i]) );
					}
				}
			}
			// Tracking called
			this.doVideoTracking(obj);
		},

		onVideoPlayerError: function(errorMessage) {
			_log_('[VideoPlayer] '+ errorMessage, 'err');
		},

		/*************************
			Additional callbacks
		**************************/
		onAdPrerollUrl : function(videoId, adUrl) {
			sendVideoEvent(this.getContentEntry(this.getContentId()), "video-preroll");
			_log_('[AD] Try to load ad: videoId('+ videoId +') adUrl('+adUrl+')', 'ad');
			// Clear the background?
		},

		onAdPostrollUrl : function(videoId, adUrl) {
			_log_('[AD] onAdPostrollUrl - returning false to skip add', 'ad');
			return false;// returning false will skip the ad
		},

		onAdStarted : function(token) {
			_log_('[AD] Start '+ token, 'ad');
		},

		onAdFinished : function(token) {
			_log_('[AD] Finish '+ token, 'ad');
		},

		onContentBegin : function(videoId) {
			_log_('Content begin. ('+videoId+')');
			/* Set the category/sub-category so we can get the right default background */
			var obj = null, str = this.getContentEntry(this.getContentId());
			eval('obj = '+ str);
			/* Clear background here? Yes */
			this.clearBackground(obj.metas.category, obj.metas.subCategory);
		},

		onContentPause : function(videoId) {
			_log_('Content paused. ('+videoId+')');

			sendVideoEvent(this.getContentEntry(this.getContentId()), "video-pause");
		},

	    onContentCompleted: function () {
	        _log_("Completed: " + this.getContentId());

	        sendVideoEvent(this.getContentEntry(this.getContentId()), "video-complete");

	        // Homepage player at end reverts to image
	        if (_player == 'homepage') {
	            nascarToggleHomepagePlayer(false);
	        }
	    },

		onAdError : function(message) {
			_log_('Error: [AD] '+ message, 'err');
		},

		onContentVolume : function(muted, volume) {
			/* Don't need after testing */
			_log_('Muted('+ muted +') Volume('+ volume +')');
		},

		onContentTrackingAdCountdown : function(secs) {
			// Show the ad countdown, unless you're on the homepage
			if ( _player != 'homepage' ) {
				document.getElementById('cnnVideoHeadline').innerHTML = '';
				document.getElementById('cnnVideoBlurb').innerHTML = "Your video will play in 00:"+( secs < 10 ? '0'+ secs : secs );
			}
		},

		/************************
			Video Tracking callbacks
		 ************************/
		onVideoTrackingAdClick : function(videoId, url) {
			_log_('[VT] Ad clicked( ' + videoId + ' ): ' + url);
		},

		onVideoTrackingProgress : function(videoId, percent) {
			_log_('[VT] Progress( ' + videoId + ' ): ' + percent);
		},

		onVideoTrackingLifetime : function(seconds) {
			_log_('[VT] Lifetime: ' + seconds);
		},

		onVideoTrackingFullscreen : function(videoId, fullscreen) {
			_log_('[VT] Fullscreen( ' + videoId + ' ): ' + fullscreen);
		},

		onVideoTrackingMuted: function(videoId, muted) {
			_log_('[VT] Muted( ' + videoId + ' ): ' + muted);
		},

		onVideoTrackingPaused : function(videoId, paused) {
			_log_('[VT] Paused( ' + videoId + ' ): ' + paused);
		},

		onVideoTrackingCompleted : function(videoId) {
			_log_('[VT] Completed( ' + videoId + ' ) ');
		},

		onVideoTrackingReplay : function(videoId) {
			_log_('[VT] Replay( ' + videoId + ' ) ');
		},

		onVideoTrackingPlay : function(videoId) {
			_log_('[VT] Play( ' + videoId + ' ) ');
		}

	});
	nascarVideoPlayer.embedSWF('nascarVideoPlayerDiv');
}
CVP.prototype.doVideoTracking = function(metaData) {
	nascarVideoTracking.videoId = metaData.id;
	nascarVideoTracking.onVideoStart();
};
CVP.prototype.clearBackground = function(cat, sub) {
	_log_("Clear background :"+ document.getElementById('cnnAboveFold').style.backgroundImage +":" );
	var defaultBackgroundImage = null;
	switch ( cat ) {
		case 'speed': defaultBackgroundImage = nascarDefaultImages.speed; break;
		default:      defaultBackgroundImage = nascarDefaultImages['default']; break;
	}
	_log_("Default BG: "+ defaultBackgroundImage );
	if ( document.getElementById('cnnAboveFold').style.backgroundImage != '' ) {
		_log_("CLEAR THE BACKGROUND!");
		document.getElementById('cnnAboveFold').style.backgroundImage = defaultBackgroundImage;
	}
};
function nascarStartVideo() {
	document.getElementById('nascarVideoSlateImage').style.display = 'none';
	nascarVideoPlayer.play( nascarCleanVideoId(nascarPlaylist[0]) );
}
function nascarToggleHomepagePlayer(bool) {
	if ( bool ) {
		// turn on, start playing
		document.getElementById('nascarVideoSlateImage').style.display = 'none';
		nascarVideoPlayer.play( nascarCleanVideoId(nascarPlaylist[0]) );
	}
	else {
		document.getElementById('nascarVideoSlateImage').style.display = 'block';
	}
}
function nascarCvpHomepageCleanUrl(url) {
	return url;
}
function _log_(msg, type) {
	if ( document.getElementById('cnnVideoMessages') ) {
		type = type ? type : 'msg';
		var ele = document.getElementById('cnnVideoMessages');
		ele.innerHTML += '<li class="'+ type +'">'+ msg +'</li>';
	}
}
Array.prototype.inArray = function(item) {
	var arr = this;
	var len = arr.length;
	for ( var i = 0; i < len; i++ ) {
		if ( nascarCleanVideoId(arr[i]) == nascarCleanVideoId(item) ) {
			return i;
		}
	}
	return -1;
}
function nascarCleanVideoId(str) {
	var url = '';
	// End with /index.html?
	var end = str.indexOf('/index.html');
	if ( end == -1 ) {
		url = str;
	}
	else {
		url = str.slice(0, end);
	}
	// End with /?
	if ( str.lastIndexOf('/') == (str.length - 1) ) {
		end = str.length - 1;
		url = str.slice(0, end);
	}
	// Add /video if missing
	if ( url.indexOf('/video') == -1 ) {
		url = '/video' + url;
	}
	// Do I have a category/subCat?
	var ele = url.match(/^(\/video.+\d{4}).+(\d{2}\/+\d{2}.+)$/);
	if ( ele && typeof ele == 'object' ) {
		// is array
		url = ele[1] +'/'+ ele[2];
	}
	// Convert nationwide-series to busch
	// But NOT if this is a webcast
	if ( url.indexOf('/nationwide-series/') != -1 && url.indexOf('/multimedia/webcast/') == -1 ) {
		var bits = url.split('/nationwide-series/');
		url = bits.join('/busch/');
	}
	return url;
}
