/*
	Uses the JSON model to plug the necessary information into the page.
*/

/*******	A. ajax object	*******/
function ajaxer(url, callbackFunction) {
	var that=this;      
	this.updating = false;
	this.abort = function() {
		if (that.updating) {
			that.updating=false;
			that.AJAX.abort();
			that.AJAX=null;
		}
	}
	this.update = function(passData,postMethod) { 
		if (that.updating) { return false; }
		that.AJAX = null;                          
		if (window.XMLHttpRequest) {              
			that.AJAX=new XMLHttpRequest();              
		} else {                                  
			that.AJAX=new ActiveXObject("Microsoft.XMLHTTP");
		}
		if (that.AJAX==null) {  
			return false;                               
		} else {
			that.AJAX.onreadystatechange = function() {  
			if (that.AJAX.readyState==4) {             
				that.updating=false;                
				that.callback(that.AJAX.responseText,that.AJAX.status,that.AJAX.responseXML);        
				that.AJAX=null;                                         
			}                                                      
		}
		that.updating = new Date();                              
		if (/post/i.test(postMethod)) {
			var uri=urlCall+'?'+that.updating.getTime();
			that.AJAX.open("POST", uri, true);
			that.AJAX.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			that.AJAX.setRequestHeader("Content-Length", passData.length);
			that.AJAX.send(passData);
		} else {
			var uri=urlCall;
			var ifModifiedSince = new Date(0);
			that.AJAX.open("GET", uri, true); 
			if(navigator.appName == "Microsoft Internet Explorer"){ /* if IE, then set the header to see if the file has been modified since some time in the past */
				that.AJAX.setRequestHeader("If-Modified-Since", ifModifiedSince);
			}
			that.AJAX.send(null);                                         
		}              
			return true;                                             
		}                                                                           
	}
	var urlCall = url;        
	this.callback = callbackFunction || function () { };
}
/*******	[END] A. ajax object	*******/

/*******	B. team data
 - latest game
 - standings bar
 - si power ranking
 *******/
 
var team_url_name = document.cnnSASDPageType;
var team = {
	ajax:{
		latest_game:new ajaxer('/.element/auto/team/4.1/basketball/nba/'+team_url_name+'/latestgame.json'),
		standings_bar_off_def:new ajaxer('/.element/auto/team/4.1/basketball/nba/'+team_url_name+'/standings_bar_off_def.txt'),
		standings_bar_wlt:new ajaxer('/.element/auto/team/4.1/basketball/nba/'+team_url_name+'/standings_bar_wlt.txt'),
		si_pwr_rank:new ajaxer('/.element/auto/team/4.1/basketball/nba/si_power_ranking.txt')
	},
	data:{
		latest_game:{},
		standings_bar:{},
		si_pwr_rank:{}
	},
	status:{
		latest_game:0,
		standings_bar:0,
		si_pwr_rank:0
	}
};


function getTeamData(){
	
	//STANDINGS BAR DEF+OFF
	team.ajax.standings_bar_off_def.update();
	team.ajax.standings_bar_off_def.callback = function(text,status){	
		window.STANDINGS_BAR_OFF_DEF = new Array();
		team.status.standings_bar_off_def  = status;
		if (status == 200) {	
			team.data.standings_bar_off_def = eval('('+text+')');	
			STANDINGS_BAR_OFF_DEF = [
				{	id:"STANDINGS_OFF_RANK", value: parseInt(team.data.standings_bar_off_def.OFF_RANK)},
				{	id:"STANDINGS_DEF_RANK", value: parseInt(team.data.standings_bar_off_def.DEF_RANK)}
			];
		} else {
			STANDINGS_BAR_OFF_DEF = [
				{	id:"STANDINGS_OFF_RANK", value: "--"},
				{	id:"STANDINGS_DEF_RANK", value: "--"}
			];
		}
		Controller(STANDINGS_BAR_OFF_DEF);
		setTimeout("checkData('standings_bar_off_def')",2000);
		setTimeout("checkData('standings_bar_off_def')",5000);
	};

	//STANDINGS BAR WLT
	team.ajax.standings_bar_wlt.update();
	team.ajax.standings_bar_wlt.callback = function(text,status){	
		window.STANDINGS_BAR_WLT = new Array();
		team.status.standings_bar_wlt  = status;
		if (status == 200) {	
			team.data.standings_bar_wlt = eval('('+text+')');	
			STANDINGS_BAR_WLT = [
				{	id:"STANDINGS_WLT", value:team.data.standings_bar_wlt.TEAM_RECORD}
			];
		} else {
			STANDINGS_BAR_WLT = [
				{	id:"STANDINGS_WLT", value:"--"}
			];
		}
		Controller(STANDINGS_BAR_WLT);
		setTimeout("checkData('standings_bar_wlt')",2000);
		setTimeout("checkData('standings_bar_wlt')",5000);
	};
	
	//SI POWER RANKING
	team.ajax.si_pwr_rank.update();
	team.ajax.si_pwr_rank.callback = function(text,status){	
		window.SI_PWR_RANK = new Array();
		team.status.si_pwr_rank = status;
		if (status == 200) {	
			team.data.si_pwr_rank = eval('('+text+')');	
			SI_PWR_RANK = [{	id:"SI_PWR_RANK", value:team.data.si_pwr_rank[ document.cnnSASDPageType ]}];
		} else {
			SI_PWR_RANK = [{	id:"SI_PWR_RANK", value:'--'}];
		}		
		Controller(SI_PWR_RANK);
		setTimeout("checkData('si_pwr_rank')",2000);
		setTimeout("checkData('si_pwr_rank')",5000);
	};
	
	//LATEST GAME
	team.ajax.latest_game.update();
	team.ajax.latest_game.callback = function(text,status){	
		window.LATEST_GAME = new Array();
		team.status.latest_game = status;
		if (status == 200) {	
			team.data.latest_game = eval('('+text+')');	
			var the_game_status = team.data.latest_game.CNTST_STATUS;
						
			LATEST_GAME = [
				{	id:"GAME_STATUS", value:the_game_status},
				{	id:"SCORES_V_SCORE", value:team.data.latest_game.VSTR.SCORE},
				{	id:"SCORES_H_SCORE", value: team.data.latest_game.HOME.SCORE},
				{	id:"BOX_SCORE", attribute:"href", value: team.data.latest_game.BOXSCORE_URL}
				
			];

			if(the_game_status != "FINAL"){
				setTimeout("team.ajax.latest_game.update()",60000);				
				Controller(LATEST_GAME);
			} 
			else {
				return false;
			}
		} 
	};
}

getTeamData(); //fetches json and sets up callbacks

function capitalize(string){
	var strArr = string.split(' ');
	var newstring = "";
	for (var i=0;i<strArr.length;i++){
		strArr[i] = strArr[i].substring(0,1).toUpperCase() + strArr[i].substring(1,strArr[i].length).toLowerCase();
		newstring += strArr[i];
		if(i < strArr.length-1) newstring += " ";
	}
	return newstring;
}



function Controller (directive){	//parses the directive object and plugs in the appropriate directive values
	for(var i=0; i < directive.length; i++){
		var id = directive[i].id;
		var attribute = directive[i].attribute;
		var value 	  = directive[i].value; 
		var node = $e(id);
		if(id != null || value != null){
			if(node != null){
				if (attribute != null){
					node.setAttribute(attribute, value);
				} else {
					if ( node.firstChild != null){
						node.firstChild.nodeValue = value;
					} else {
						node.innerHTML = value;
					}
				}
			}
		}		
	}
}

function checkData(id){
	var directive = new Array();
	
	if (team.status[id] == 200){
		switch(id){
			case 'latest_game':
			directive = LATEST_GAME;
			break;
			case 'standings_bar_off_def':
			directive = STANDINGS_BAR_OFF_DEF;
			break;
			case 'standings_bar_wlt':
			directive = STANDINGS_BAR_WLT;
			break;
			case 'si_pwr_rank':
			directive = SI_PWR_RANK;
			break;
			default:
			break;
		}
		
		if( directive[0].attribute != null){
			if( $e(directive[0].id)[directive[0].attribute] != directive[0].attribute ){
				Controller(directive);
				try{
					console.log(id+'\'s second attempt to convert json to html');
				} catch (e) {}
			} else {
				return false;
			}		
		} else if ( $e(directive[0].id).innerHTML.indexOf(directive[0].value) < 0){
			Controller(directive);
			try{
				console.log(id+'\'s second attempt to convert json to html');
			} catch (e) {}
		} else{
			try{
			console.log(id+'\'s content already loaded!');
			} catch (e) {}
			return false;
		}
		
	} else if(team.status[id] == 404){
		return false;
	}
}
/*******	[END] B. team data	*******/



