var elemList = new Hash();
var elemStateList = new Hash();

var getNextUrl = function(elemId) {
	var temp = elemList.get(elemId);
	var tempArray = temp.split("|");
	var url = tempArray[1];
	return url;
};

var setNextUrl = function(elemId, nextUrl, tabId) {
	if (elemId != null) {
		elemList.set(elemId, tabId + "|" + nextUrl);
	}
};

var getTabId = function(elemId) {
	var temp = elemList.get(elemId);
	var tempArray = temp.split("|");
	var tabId = tempArray[0];
	return tabId;
};

var tabState = null;
var setTabState = function(oSituation){
	tabState = oSituation;
}
var getTabState = function(){
	return tabState;
}

// no callback function for this asynchronous call because we are evaluating the JavaScript
function getGameUpdates() {
		elemList.each(
			function(obj) {
				//console.log(getTabId(obj.key) + ' == ' + window.nbaSelectedTab.href.match(/#(\w.+)/)[1] + '?');
				if (getTabId(obj.key)==window.nbaSelectedTab.href.match(/#(\w.+)/)[1] || getTabId(obj.key)=='nbaGIline' || getTabId(obj.key)=='nbaGItab') {
					var myUpdater = AjaxUpdater(obj.key, getNextUrl(obj.key), {method: 'get', evalScripts: true, asynchronous:true});
				} 
			}
		);
		setTabStateEX(getTabState());
}

function getGameUpdatesOnClick() {
	elemList.each(
		function(obj) {
			if (getTabId(obj.key)==window.nbaSelectedTab.href.match(/#(\w.+)/)[1] || getTabId(obj.key)=='nbaGIline' || getTabId(obj.key)=='nbaGItab') {
				var myUpdater = AjaxUpdater(obj.key, getNextUrl(obj.key), {method: 'get', evalScripts: true, asynchronous:true});
			} 
		}
	);
}

function openPopupOrSignupPage() {    
	if ($chrome.isUserAuthenticated()) {        
		open_window_ex ($chrome.getNBABaseUrl() + '/broadband/alp_schedule.html?name='+encodeURIComponent($chrome.getUserDisplayName()), 'AudioLeaguePass', 660,550);    
	} else {        
		window.location = $chrome.getMSIB() + '/flow/registerOrLogin?url='+ encodeURIComponent($chrome.getNBABaseUrl() + '/allaccess/watchListen.html');
	} 
}

//Generic Open-Window function
function open_window_ex(url, title, height, width, options) {
	var path = url;
	if( url.search(/^http:/) == -1 ) {
		path = "/popups/" + url;
	} else {
		var nbaDomain = new RegExp("/^http:\/\/www.nba.com\/([.*]*)/");
		var result = url.match(nbaDomain);
		if( result != null ) {
			path = "/popups/" + result[1];
		} else {
			path = url;
		}
	}
	var opts = '';
	if(options == null || options == 'null') {
		opts = 'toolbar=0, location=0, directories=0, status=0, menubar=0, scrollbars=yes, resizable=yes';
	} else {
		opts = options;
	}
	
	opts += ',width=' + width;
	opts += ',height=' + height;
	mywin=window.open(path,title,opts);
}



AjaxUpdater = function(container, url, options) {
	url = url.replace(/\.js$/, '.html');

	if (url.search(/masterController/) != -1) {
		logger('---------------');
		logger('callObject(' + container + ', ' + url + '[, ' + options + ']) - JSON return');
		CSIManager.getInstance().callObject({url: url, domId: container, funcObj: renderCSI});
	} else {
		logger('callObject(' + container + ', ' + url + '[, ' + options + '])');
 		CSIManager.getInstance().callObject({url:url, domId: container});
	}
}

var outputDebug = false;
if (CVP.swfobject.getQueryParamValue('nbaDebug')) {
	outputDebug = true;
}
function logger(msg) {
	if ((outputDebug) && (typeof(console) != 'undefined')) {
		console.log('[CSI] ' + msg)
	}
}

function renderCSI(obj) {
	if (typeof(obj.defaultState) != 'undefined') {
		defaultState = obj.defaultState; 		
		logger('setTabState(' + obj.defaultState + ')');
		setTabState(obj.defaultState);
	}
	if (typeof(obj.nextURL) != 'undefined') {
		for (var i=obj.nextURL.length; i--;) {
			var entry = obj.nextURL[i];
			//logger('setNextUrl(' + entry['elemID'] + ', ' + entry['nextURL'] + ', ' + entry['tabId'] + ')');
			setNextUrl(entry['elemID'], entry['nextURL'], entry['tabId']);
		}
		defaultState = obj.defaultState; 		
		setTabState(obj.defaultState);
	}

	return '';
}

function toggleVideo() {
	$('Rnd1pick1').toggle();
	if($('Rnd1pick1').visible()){
		$('Rnd1pick1-listen').update('<img src="http://i.cdn.turner.com/nba/nba/.element/img/2.0/sect/gameinfo/nbaGIVideoHide.gif" alt="Close the feature box" />');
	} else {
		$('Rnd1pick1-listen').update('<img src="http://i.cdn.turner.com/nba/nba/.element/img/2.0/sect/gameinfo/nbaGIVideoShow.gif" alt="Open the feature box" />');
	}
	return false;
}



// by the time window loads, we should have the elemList populated, if any games are in ready-to-update, or progress state.
Event.observe(document, 'dom:loaded', pageOnLoaded);
Event.observe (window, 'load', onWindowLoad);


function onWindowLoad() {
	var internalPollingInterval = 10;
	if (typeof(csiPollingInterval) != 'undefined') {
		internalPollingInterval = csiPollingInterval;
	}
	if ((defaultState != 5) && (internalPollingInterval > 0)) {
		logger('setting poll interval to: ' + internalPollingInterval);
		var myexecuter = new PeriodicalExecuter(getGameUpdates, internalPollingInterval);
	}
}


function pageOnLoaded() {
	startVideo();
	if (CVP.swfobject.getQueryParamValue('nbaDebug')) {
		outputDebug = true;
	}
}

function startVideo() {
	if (typeof(videoIDArray) != 'undefined') {
		var vidPlayerDiv = 'nbaGIVideo';
		var vidPlaylist = videoIDArray;
		var height = 354;
		var width = 576;
		var context = 'nba_gameinfo_player';
		NBAStandalonePlayer = new NBAVideoPlayer();
		NBAStandalonePlayer.initialize(vidPlayerDiv, vidPlaylist, height, width, context);
		if ($('Rnd1pick1').style.display == 'none') {
			Event.observe(window, 'load', function() {$('Rnd1pick1-listen').update('<img src="http://i.cdn.turner.com/nba/nba/.element/img/2.0/sect/gameinfo/nbaGIVideoHide.gif" alt="Close the feature box" />');});
			$('Rnd1pick1').show();
		}
	}
};

