function NBAVideoPlayer() {
	this._AUTOPLAY = '_auto';

	this.playlist = [];
	this.playlistLength = 7;
	//this.arrAvailableVideo = [];
	this.pageType = null;
	this.playerDiv = null;
	this.adDiv = null;
	this.playlistUpdater = null;
	this.overridePreRoll = null;
	this.overrideSyncUnit = null;
	this.overrideTopSyncUnit = null;
	this.autoplay = false;
	this.sideSyncAdData = '';
	this.topSyncAdData = '';
	this.backgroundDiv = null;
	this.current_tab = '';

	this.initialize = function(pageType, playerDiv, adDiv, playlistUpdater, arrPlaylist, overridePreRoll, overrideSyncUnit, overrideTopSyncUnit) {
		this.pageType = pageType;
		this.playerDiv = $(playerDiv);
		this.adDiv = $(adDiv);
		this.playlistUpdater = playlistUpdater;

		this.overridePreRoll = overridePreRoll;
		this.overrideSyncUnit = overrideSyncUnit;
		this.overrideTopSyncUnit = overrideTopSyncUnit;
		this.createPlayer();
		this.backgroundDiv = $('nbaVideoPodFull');
		if (pageType.indexOf(this._AUTOPLAY) > -1) {
			this.autoplay = true;
		}
		this.setCurrentTab();

		var ct = arrPlaylist.length;
		for (var i=0; i<ct; i++) {
			var thisVid = arrPlaylist[i];
			thisVid = thisVid.replace(/\.json$/i, '');
			this.playlist[i] = thisVid;
		}
	}

	this.setAvailableVideo = function(arr_vidId) {
		this.arrAvailableVideo = arr_vidId		
	}


	this.createPlayer = function(){
		var flashvars = {};
		flashvars.player = "main"; // player instance

		var params = {};
		params.quality = "high";
		params.bgcolor = "#000000";
		params.allowFullScreen = "true";
		params.allowScriptAccess = "always";
		CVP_player.embedSWF(this.playerDiv.id);
		//TURNERPLAYER.embedSWF('/.element/swf/1.1/cvp/nba_staging.swf', this.playerDiv.id, '576', '324', 'expressInstall.swf', flashvars, params);
	}


	this.setCurrentTab = function() {
		if ($('nbaVideoFilePath') && $('nbaVideoFileMap')) {
			this.current_tab = $('nbaVideoFilePath').innerHTML + $('nbaVideoFileMap').innerHTML;
		}
	}

	this.setPlaylist = function(arrPlaylist) {
		this.playlist = arrPlaylist;
		this.play(this.playlist[0]);
	}

	this.start = function(){
		this.play(this.playlist[0]);
	}

	this.play = function(videoId) {
		NBAVideoPlayerWrapper.log('[CVP] NBAVideoPlayer.play(' + videoId + ')');
		var getAdSection = function()
		{
			if( nbaCVPAdConfig )
			{
				if( nbaCVPAdConfig.adSectionMap[ currCVPTabName+'.'+currCVPSubTabName ] )
				{
					return nbaCVPAdConfig.adSectionMap[ currCVPTabName+'.'+currCVPSubTabName ];
				}
				else if( nbaCVPAdConfig.adSectionMap[ currCVPTabName ] )
				{
					return nbaCVPAdConfig.adSectionMap[ currCVPTabName ];
				}
			}
			return '';
		};
		var sect = getAdSection();
		CVP_player.setAdSection(sect);
		NBAVideoPlayerWrapper.clearBrandedBackground();
		CVP_player.play(videoId);
		// next video will be queued in cvp_player.onContentPlay()
	}

	this.queueNextUp = function(videoId) {
		NBAVideoPlayerWrapper.log('[CVP] NBAVideoPlayerWrapper.queueNextUp(' + videoId + ')');
		videoId = videoId.replace(/\.xml/i, '');
		var marker = this.playlist.indexOf('/video/' + videoId)
		var ct = this.playlist.length - 1;
		if ((marker > -1) && (marker < ct)) {
			marker++;
			NBAVideoPlayerWrapper.log('[CVP] queueing next id: ' + marker);
			CVP_player.queue(this.playlist[marker]);
		}
	}

	this.addNowPlayingOverlay = function(videoId) {
		var divID = '';
		var videoIdMatch = videoId.match(/\/([0-9]{4})\/([0-9]{2})\/([0-9]{2})\/(.*)\.(.*)/);
		if (!videoIdMatch) {
			videoIdMatch = videoId.match(/\/([0-9]{4})\/([0-9]{2})\/([0-9]{2})\/(.*)/);
		}
		divID = videoIdMatch[4];
		var arrSelected = $$('div.nbaSpanOverlayNow');
		var ct = arrSelected.length;
		for (var i=0; i < ct; i++) {
			if (arrSelected[i] != divID + '_overlay') {
				arrSelected[i].className = 'nbaSpanOverlay'
			}
		}
		$(divID + '_overlay').className = 'nbaSpanOverlayNow';
	}
	this.clearBrandedBackground = function() {
		if (this.backgroundDiv != null) {
			this.backgroundDiv.style.backgroundImage = 'url(http://i.cdn.turner.com/nba/nba/.element/img/1.1/savp/genericBackground.jpg)';
		}
	}

	this.log = function(message) {
		if (typeof(console) != 'undefined') {
			console.log(message)
		}
	}
	this.error = function(message) {
		if (typeof(console) != 'undefined') {
			console.error(message)
		}
	}
}
/* CVP instantiation */
var CVP_player = new CVP({
	id : 'cvp_player',
	width : '576',
	height : '354',
	flashVars : {
		player : 'main',
		context :(typeof pageType !== 'undefined' && pageType === 'teamsite') ? 'team' : 'nba'
	},
	embed : {
		containerSwf : 'http://i.cdn.turner.com/nba/nba/.element/swf/1.1/cvp/nba_container.swf',
		expressInstallSwf : 'http://i.cdn.turner.com/v5cache/turnerplayer/flash/expressInstall.swf',
		options : {
			quality : 'high',
			bgcolor : '#222222',
			allowFullScreen : 'true',
			allowScriptAccess : 'always',
			wmode : 'transparent'
		}
	},

	onPlayerReady : function() {
		NBAVideoPlayerWrapper.log('[CVP] onPlayerReady()');
		NBAVideoPlayerWrapper.start();
	},

	onAdPrerollUrl : function(videoId, adUrl) {
		NBAVideoPlayerWrapper.log('[CVP] onAdPrerollUrl(' + videoId + ', ' + adUrl + ')');
		NBAVideoPlayerWrapper.clearBrandedBackground();
		NBAVideoPlayerWrapper.addNowPlayingOverlay(videoId);
	},

	onAdPostrollUrl : function(videoId, adUrl) {
		return false;
	},

	onAdStarted : function(token) {
		NBAVideoPlayerWrapper.log('[CVP] onAdStarted(' + token + '):');
	},

	onAdFinished : function(token) {
		NBAVideoPlayerWrapper.log('[CVP]: onAdFinished(token)');
	},

	onContentBegin : function(videoId, json) {
	},

	onContentBuffering : function() {
	},

	onContentPlay : function() {
		var videoId = this.getContentId();
		NBAVideoPlayerWrapper.log('[CVP] onVideoPlayerPlay(' + videoId + ')');
		//taboola
		if (typeof(TRC) != 'undefined') {
			var tab = videoId.slice(videoId.lastIndexOf('/')+1,videoId.lastIndexOf('.nba'));
			var gotourl = 'http://www.nba.com' + videoId.replace(/\.xml$/i, '/index.html');
			TRC.playVideo(tab,gotourl);
		}
	
		// if ad didn't play, set "now Playing" overlay
		NBAVideoPlayerWrapper.addNowPlayingOverlay(videoId);
	
		// queue next video in playlist
		NBAVideoPlayerWrapper.queueNextUp(videoId);

		//Omniture Implementation
		var videoMetaData = this.getContentEntry(videoId).evalJSON(true);
		if (videoMetaData.isExpired == 'no') {
			w.nbaOmCurrentVideo = videoMetaData.id;
			nbaOmEvent.videoSource = 'L';
			nbaOmEvent.videoContext = 'M';
			nbaOmEvent.videoId = videoMetaData.id;
			nbaOmEvent.videoTitle = videoMetaData.headline;
			nbaOmEvent.videoRunTime = videoMetaData.trt;
			nbaOmEvent.videoPlayerType = 'CVP';
			var tempFolders = videoMetaData.category.split('/');
			var sectionName = tempFolders[tempFolders.length-1];
			nbaOmEvent.videoCategory = (nbaOmSuiteInfo.currentTeam ? nbaOmSuiteInfo.currentTeam : nbaOmSuiteInfo.currentLeague)+':'+sectionName;
			nbaOmEvent.onStreamStart();
		}
	},
	onContentError : function(errorMessage) {
		NBAVideoPlayerWrapper.log('[CVP] onContentError: ' + errorMessage);
	},
	onContentPlayHead : function() {
		//log('Playhead - ' + this.getPlayhead() + '...isPaused - ' + this.isPaused());
	},

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

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

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

	onAdError : function(message) {
		NBAVideoPlayerWrapper.clearBrandedBackground();
		NBAVideoPlayerWrapper.log('[CVP] onAdError:' + message);
	},

	onContentVolume : function(muted, volume) {
	},

	/************************
	    Tracking callbacks
	 ************************/
	onVideoTrackingAdClick : function(videoId, url) {
		NBAVideoPlayerWrapper.log('[CVP] onVideoTrackingAdClick( ' + videoId + ' ): ' + url);
	},

	onVideoTrackingProgress : function(videoId, percent) {},
	onVideoTrackingLifetime : function(seconds) {},
	onVideoTrackingFullscreen : function(videoId, fullscreen) {},
	onVideoTrackingMuted : function(videoId, muted) {},
	onVideoTrackingPaused : function(videoId, paused) {},
	onVideoTrackingCompleted : function(videoId) {},
	onVideoTrackingReplay : function(videoId) {},
	onVideoTrackingPlay : function(videoId) {},
	onContentTrackingAdCountdown : function(secs) {}
});

// BEGIN videoplayer.js CODE

var nbaLeagueTeams = [
	{teamCode: "ATL", shortName: "hawks", fullName: "Atlanta Hawks"},
	{teamCode: "BOS", shortName: "celtics", fullName: "Boston Celtics" },
	{teamCode: "CHA", shortName: "bobcats", fullName: "Charlotte Bobcats" },
	{teamCode: "CHI", shortName: "bulls", fullName: "Chicago Bulls" },
	{teamCode: "CLE", shortName: "cavaliers", fullName: "Cleveland Cavaliers" },
	{teamCode: "DAL", shortName: "mavericks", fullName: "Dallas Mavericks" },
	{teamCode: "DEN", shortName: "nuggets", fullName: "Denver Nuggets" },
	{teamCode: "DET", shortName: "pistons", fullName: "Detroit Pistons" },
	{teamCode: "GSW", shortName: "warriors", fullName: "Golden State Warriors" },
	{teamCode: "HOU", shortName: "rockets", fullName: "Houston Rockets" },
	{teamCode: "IND", shortName: "pacers", fullName: "Indiana Pacers" },
	{teamCode: "LAC", shortName: "clippers", fullName: "Los Angeles Clippers" },
	{teamCode: "LAL", shortName: "lakers", fullName: "Los Angeles Lakers" },
	{teamCode: "MEM", shortName: "grizzlies", fullName: "Memphis Grizzlies" },
	{teamCode: "MIA", shortName: "heat", fullName: "Miami Heat" },
	{teamCode: "MIL", shortName: "bucks", fullName: "Milwaukee Bucks" },
	{teamCode: "MIN", shortName: "timberwolves", fullName: "Minnesota Timberwolves" },
	{teamCode: "NJN", shortName: "nets", fullName: "New Jersey Nets" },
	{teamCode: "NOH", shortName: "hornets", fullName: "New Orleans Hornets" },
	{teamCode: "NYK", shortName: "knicks", fullName: "New York Knicks" },
	{teamCode: "OKC", shortName: "thunder", fullName: "Oklahoma City Thunder" },
	{teamCode: "ORL", shortName: "magic", fullName: "Orlando Magic" },
	{teamCode: "PHI", shortName: "sixers", fullName: "Philadelphia 76ers" },
	{teamCode: "PHX", shortName: "suns", fullName: "Phoenix Suns" },
	{teamCode: "POR", shortName: "blazers", fullName: "Portland Trail Blazers" },
	{teamCode: "SAC", shortName: "kings", fullName: "Sacramento Kings" },
	{teamCode: "SAS", shortName: "spurs", fullName: "San Antonio Spurs" },
	{teamCode: "TOR", shortName: "raptors", fullName: "Toronto Raptors" },
	{teamCode: "UTA", shortName: "jazz", fullName: "Utah Jazz" },
	{teamCode: "WAS", shortName: "wizards", fullName: "Washington Wizards" }
];

var goto_top_type = -1;
var goto_top_itv = 0;

function goto_top_timer() {
	var y = goto_top_type == 1 ? document.documentElement.scrollTop : document.body.scrollTop;
	var moveby = 15; // set this to control scroll seed. minimum is fast

	y -= Math.ceil(y * moveby / 100);
	if (y < 0) y = 0;

	if (goto_top_type == 1) document.documentElement.scrollTop = y;
	else document.body.scrollTop = y;

	if (y == 0) {
		clearInterval(goto_top_itv);
		goto_top_itv = 0;
	}
}

function goto_top() {
	if (goto_top_itv == 0) {
		if (document.documentElement && document.documentElement.scrollTop)
			goto_top_type = 1;
		else if (document.body && document.body.scrollTop)
			goto_top_type = 2;
		else
			goto_top_type = 0;

		if (goto_top_type > 0)
			goto_top_itv = setInterval('goto_top_timer()', 25);
	}
}

function getQueryParam(param) {
	var queryHash = $H(window.location.href.toQueryParams());
	return queryHash.get(param);
}

function getURLParam(param) {
	var queryHash = $H(window.location.href.toQueryParams());
	return queryHash.get(param);
}

function getTeamName() {
    var match = window.location.pathname.match(/\/video\/teams\/([a-z]+?)\/originals/);
    if (match&&match[1]) return match[1];
    return '';
}

function wordToUpper(param) {
    return param.toLowerCase().replace(/\b[a-z]/g, convertToUpper);

    function convertToUpper()
    {
        return arguments[0].toUpperCase();
    }
}

function getTeamSiteName() {
    var match = window.location.pathname.match(/\/([a-z]+?)\/video\/([0-9]{4})\/([0-9]{2})\/([0-9]{2})/);
    if (match&&match[1]) {
    	var urlTeamName = match[1];
    	var teamObj = nbaLeagueTeams.detect(function(team) {
			return team.shortName == urlTeamName;
    	});
		if (teamObj && teamObj.shortName) {
			return teamObj.shortName;
		}
    }
    return '';
}

function getNBATeamCode(shortName) {
	var teamObj = nbaLeagueTeams.detect(function(team) {
		return team.shortName == shortName;
	});
	if (teamObj && teamObj.shortName) { return teamObj.teamCode; }
	return null;
}

function verifyTeamSite() {
	var param_fromteamsite = getQueryParam("fromteamsite");
	var teamIdTeamVideo = getTeamName();
	var teamSiteId = getTeamSiteName();
	if (param_fromteamsite) { return param_fromteamsite.toUpperCase(); }
	else if (teamIdTeamVideo!='') { return getNBATeamCode(teamIdTeamVideo).toUpperCase(); }
	else if (teamSiteId!='') { return  getNBATeamCode(teamSiteId).toUpperCase(); }
	return null;
}

// arrays for XMP player
var jsonListArray = null;
//var teamListArray = null;
var nbaListArray = null;

// ad override vars
var overridePrerollAdTag = null;
var overrideSynchAdTag = null;
var overrideTopSynchAdTag = null;

// first time flag
var loadFirstVideo = true;

function initializeVideo() {
	var playArray = new Array();
	var tempArray = null;
	
	var tabName = 'mostrecent';
	var useVideoId = latestVideoId;
	
	// match channel and special shortcut urls
	var urlRegex = /playoftheday|chrispaul|strength|performance|dailytop10|tntovertime\/Reggies_Mailbag|video\/playoffs\/series|puppets|correspondent|flipvideo|rtc|video\/Inside_the_NBA|video\/top5_of_inside|playsoftheweek/;
	var matchUrl = window.location.pathname.search(urlRegex);

	var matchChannelShort = window.location.pathname.match(/\/video\/channels\/([a-z_]+)(\/index.html){0,1}/);
	var matchChannelFull = window.location.pathname.match(/\/video\/channels\/([a-z_]+)(\/index.html){0,1}\/([0-9]{4})/);
	
	if ((!matchChannelFull && matchChannelShort) || matchUrl != -1) {
		useVideoId = loadThisVideo;
	} else {
		var match = window.location.pathname.match(/([0-9]{4})\/([0-9]{2})\/([0-9]{2})/);
		if (match) {
			useVideoId = loadThisVideo;
		} else {
			var matchTab = window.location.pathname.match(/\/video\/([a-z_]+)(\/index.html){0,1}/);
			if (matchTab && matchTab[1]) {
				tabName = matchTab[1];
				switch (tabName) {
					case 'mostrecent':	useVideoId = latestVideoId; break;
					case 'highlights':	useVideoId = highlightsVideoId; break;
					case 'nbatv':		useVideoId = nbatvVideoId; break;
					case 'tntot':		useVideoId = tntovertimeVideoId; break;
					case 'topplays':	useVideoId = topplaysVideoId; break;
					case 'featured':	useVideoId = featuredVideoId; break;
					case 'playoffs':	useVideoId = playoffsVideoId; break;
					case 'barkleyzone':	useVideoId = barkleyzoneVideoId; break;
					case 'draft':		useVideoId = draftVideoId; break;
					
				}
			}
		}
	}

	playArray[0] = useVideoId;
		
	if (jsonListArray != null) {
		tempArray = jsonListArray;
		var maxLength = (tempArray.length > 7) ? 7 : tempArray.length;
		for (var i = 0; i < tempArray.length; i++) {
			if (playArray.length >= maxLength)
				break;
			if (tempArray[i] != playArray[0]) {
				playArray.push(tempArray[i]);
			}
		}
	} 

	if (loadFirstVideo) {
		loadFirstVideo = false;
		$('nbaVideoPlayer').innerHTML = '';
		NBAVideoPlayerWrapper = new NBAVideoPlayer();
		NBAVideoPlayerWrapper.initialize('game_auto','nbaVideoPlayer','nbaVPAdvertisment',playlistUpdateHandler,playArray,overridePrerollAdTag,overrideSynchAdTag, overrideTopSynchAdTag);
		
	}
}

var prevVideoOverlayId = null;
function playlistUpdateHandler(jsonId) {
	var nowPlayOnClass = 'nbaSpanOverlayNow';
	var nowPlayOffClass = 'nbaSpanOverlay';

	// unset class for prev video overlay
	if (prevVideoOverlayId != null) {
		var prevVideoOverlayElem = document.getElementById(prevVideoOverlayId);
		if (prevVideoOverlayElem != null) { 
			prevVideoOverlayElem.className = nowPlayOffClass; 
		}
	}

	// set class for current video overlay
	var videoIdMatch = jsonId.match(/\/([0-9]{4})\/([0-9]{2})\/([0-9]{2})\/(.*)\.(.*)/);
	if (videoIdMatch) {
		var videoOverlayId = videoIdMatch[4] + '_overlay';
		prevVideoOverlayId = videoOverlayId;
		var videoOverlayElem = document.getElementById(videoOverlayId);
		if (videoOverlayElem != null) {
			videoOverlayElem.className = nowPlayOnClass;
		}
	}
}	

function loadVideo(videoArray){
	jsonListArray = videoArray;
	initializeVideo();
}

function changePlaylist(videoId) {
	NBAVideoPlayerWrapper.log('changePlaylist(' + videoId + ')');
	goto_top();

	var arr_newPlaylist = [];
	var pt = jsonListArray.indexOf(videoId);
	if (pt > -1) {
		var jsonCt = jsonListArray.length;
		var ct = NBAVideoPlayerWrapper.playlistLength;
		for (var i=0; i < ct; i++) {
			var newpt = ((i + pt) % jsonCt);
			arr_newPlaylist[i] = jsonListArray[newpt].replace(/\.json$/i, '');
			NBAVideoPlayerWrapper.log('arr_newPlaylist[' + i + ']: ' + jsonListArray[newpt].replace(/\.json$/i, ''));
		}
	} else {
		arr_newPlaylist[0] = videoId.replace(/\.json$/i, '')
	}
	NBAVideoPlayerWrapper.setPlaylist(arr_newPlaylist);
}

/* Ad Section Config */
var nbaCVPAdConfig = {
	"adSectionMap": {
		"allstar":"nba.com_video_allstar",
		"barkleyzone":"nba.com_video_barkleyzone",
		"draft":"nba.com_video_draft",
		"featured":"nba.com_video_featured",
		"highlights":"nba.com_video_games_home",
		"mostrecent":"nba.com_video_most_recent",
		"nbatv":"nba.com_video_nbatv",
		"playoffs":"nba.com_playoffs",
		// "playoffs.eastround1match1":"nba.com_playoffs_easternconf_round1_matchup1",
		// "playoffs.eastround1match2":"nba.com_playoffs_easternconf_round1_matchup2",
		// "playoffs.eastround1match3":"nba.com_playoffs_easternconf_round1_matchup3",
		// "playoffs.eastround1match4":"nba.com_playoffs_easternconf_round1_matchup4",
		// "playoffs.eastsemifinals1":"nba.com_playoffs_easternconf_semifinals_matchup1",
		// "playoffs.eastsemifinals2":"nba.com_playoffs_easternconf_semifinals_matchup2",
		// "playoffs.westround1match1":"nba.com_playoffs_westernconf_round1_matchup1",
		// "playoffs.westround1match2":"nba.com_playoffs_westernconf_round1_matchup2",
		// "playoffs.westround1match3":"nba.com_playoffs_westernconf_round1_matchup3",
		// "playoffs.westround1match4":"nba.com_playoffs_westernconf_round1_matchup4",
		// "playoffs.westsemifinals1":"nba.com_playoffs_westernconf_semifinals_matchup1",
		// "playoffs.westsemifinals2":"nba.com_playoffs_westernconf_semifinals_matchup2",
		// "playoffs.eastfinals":"nba.com_playoffs_easternconf_finals",
		// "playoffs.westfinals":"nba.com_playoffs_westernconf_finals",
		// "playoffs.finals":"nba.com_playoffs_worldfinals",
		"team":"nba.com_teams_home",
		"tntot":"nba.com_video_tntot",
		"topplay":"nba.com_video_top_plays"
	}
};

