var xmlLoc = "/nugget/12";
var xmlhttp; // create the xml holder
function loadXMLDoc(url){
	
	xmlhttp=null; // reset the xml request holder
	
	if(window.XMLHttpRequest){  // code for all new browsers
  		xmlhttp=new XMLHttpRequest(); // create new xml request
	}else if(window.ActiveXObject){  // code for IE5 and IE6
  		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); // create new xml request
  	}
	
	if (xmlhttp!=null){ // check xml status
		xmlhttp.onreadystatechange=stateChange; // launch stateChange when the file is ready
  		xmlhttp.open("GET",url,true); // get the file
  		xmlhttp.send(null); // lauch
  	}else{ // if the request has not ran
  		alert("Your browser does not support XMLHTTP."); // notify the user
  	}
	return true;
}

function stateChange(){
	if(xmlhttp.readyState == 4 ){  // Make sure the document has been loaded(4 = "loaded") 
  		if (xmlhttp.status==200){  // Make sure the contents are good (200 = "OK")
    			
			setGames(); // set the game information
    	}else{ // if there was a problem
    		//alert("Problem retrieving XML data"); // notify the user
    }
  }
}


var preGames; // game information holder (for previous games when we start checking)
var games;// game information holder (for previous games when we start checking)
function setGames(){	
	games = xmlhttp.responseXML.documentElement.getElementsByTagName('game'); // gather all of the games
	getGames(); // start checking the game changes	
}

/// ** Check The Day's Games States ** ///
function checkGames(){	
	loadXMLDoc(xmlLoc); // launch the first set of data calls
	
	var globalState = ''; // set the global state
	for(var i=0; i<games.length; i++){	// loop through the games
		if(games[i].getAttribute('gamestate') == "In-Progress" || games[i].getAttribute('gamestate') == "Pre-Game"){ // look for all non-final games
			globalState = "gameOn";	// GAME ON!! Keep the ajax running
		}
	}
	if(globalState == ''){	// if there are no games or they are all set to "Final"
		runGames = window.clearInterval(runGames);	// release the ajax and stop running.
	}
	
}
loadXMLDoc(xmlLoc); // launch the first set of data calls


/// ** Alert behavior handler ** ///
var gBehaviorsArray = []; // set the behavior handler for all effects
function CancelBehavior(id){/* checks and sets the behavior ON/OFF (Run/Cancel) */
  if (gBehaviorsArray[id]){
    gBehaviorsArray[id].cancel();
    gBehaviorsArray[id] = null;
  }
}



/// ** Get and Set Game Information ** ///
var thisGame = new Array(); // setup the game holder
var thisPreGame = new Array(); // setup the pregame holder
function getGames(){
		
		if(preGames){ // if the pregame information has been loaded, then check.
			for(i=0; i<games.length; i++){ // loop through the games
				
				getGame(games[i].getAttribute('gameId')); // go get all of the game information for updates				
				
				thisGame.getGameState(); // get the game state
				thisGame.getScores({who:"home"}); // get the home scores
				thisGame.getScores({who:"away"}); // get the away scores
				
				thisGame.getLeaders({who:"home"}); // update the home leaders
				thisGame.getLeaders({who:"away"}); // update the away leaders
				thisGame.addClock();
			}
		}
		preGames = xmlhttp.responseXML.documentElement.getElementsByTagName('game'); // gather all of the games as previous information
}


/// ** Table Manipulation to Add TH's and TD's ** ///
function addData(gameId, key, score, title){
	
	table = document.getElementById('board_'+gameId); // get the correct game table (score board)
	
	if(table){ // make sure the table exists...
		thead = table.getElementsByTagName("THEAD")[0]; // get the headers
		tbody = table.getElementsByTagName("TBODY")[0]; // get the body
		
		theadrow = thead.getElementsByTagName('TR')[0];  // get the TRs in the header
		rowLength = theadrow.getElementsByTagName('TH').length-1;  // get the count of all Table Headers
		
		if(title){ // check for a title
			if(theadrow.getElementsByTagName('TH')[rowLength].innerHTML != title){ // if the title doesn't match the current TH
				theadcell = document.createElement('TH'); // create a new Table Hader
				theadcell.innerHTML = title; // write in the new header data/text
				
				theadrow.insertBefore(theadcell, theadrow.getElementsByClassName('total')[0]); // insert the new Header with the new data 
				thead.appendChild(theadrow); // add the new header in the row
			}
		}
		
		tbodyrow = tbody.getElementsByTagName('TR')[0]; // get the first row in the body
		cell = document.createElement('TD'); // create a new TD
		cell.id = key; // set the id of the TD to the key passed in 
		cell.innerHTML = score; // add in the new data/text
		
		tbodyrow.insertBefore(cell, tbodyrow.getElementsByClassName('total')[0]);  // inserr the new Table Cell with the new data
		tbody.appendChild(tbodyrow); // add the new data in the row.
	}
}

 /// ** Add the game clock to scoreboards ** ///
var clockAdded =''; // clock check holder
var tabStuff; // tab html holder
function addClock(options){
	var options = options || {}; // setup the options
	var state = this.state || "Pre-Game";
	var gameId = options.gameId || this.id;
	var startTime = options.startTime || this.countDownStartTime;

	if(state == "Pre-Game" && clockAdded.indexOf(gameId) == -1){ // check to see if the game is in pre-game state and the clock hasn't already been added		
		var clock = new FSFlashTag('/id/8877081', 163, 111); // create a new clock
			clock.setId('counter_'+gameId); // set the clock ID
			clock.setFlashvars("useDaylightSavings=false&amp;countdownTime="+startTime+"&amp;myID=clockHolder_"+gameId); // set the flash variables
			clock.setWmode('transparent'); // set the transparency
			clock.setWmodeFF('transparent'); // set the transparency
		
		var clockHolder = document.createElement('div'); // create the clock holder div
			clockHolder.id = "clockHolder_"+gameId; // set the id for the div
			clockHolder.className = "clock"; // set the class name
			clockHolder.innerHTML = clock; // place the clock inside of this div
		
		var game = document.getElementById("gameData_"+gameId); // get the scoreboard box
			game.insertBefore(clockHolder, document.getElementById('gameLeaders_'+gameId)); // insert the clock
			clockAdded += gameId+","; // add the id of the newly added clock to the holder
			document.getElementById('gameCalls_'+gameId).style.visibility = "hidden"; // hide the game calls tabs
			return; // stop checking
	}
	
}
 /// ** Remove the game clock from the scoreboards ** ///
function removeClock(divId){	
	document.getElementById(divId).style.display='none'; // remove / hide the clock
	gc = divId.split("_"); // get the game ID fom the div ID...
	document.getElementById("gameCalls_"+gc[1]).style.visibility = "visible"; // display the game calls tabs
};

//// ** Ordinal Number Format  ** ////
function ordinal(num, options){		
	var options = options || {}; // setup the options
	var sScript = options.sScript || false; // get subscript if needed
	
	var mod1 = num%100; // get the divided "remainder" of 100
	var mod2 = num%10; // get the divided "remainder" of 10
	var ord; // ste the ordinal variable
	
	if((mod1-mod2) == 10){ // capture 10
		ord = "th"; // set the oridnal to th as in: 10th
	}else{// for everything else
		switch(mod2){  // check the remainder of the 10th place
			case 1: // if 1 as in 1st
				ord = "st"; // set the ordinal
			break;
			case 2: // if 2 as in 2nd
				ord = "nd";// set the ordinal
			break;
			case 3: // if 3 as in 3rd
				ord = "rd";// set the ordinal
			break;
			default: // for everything else
				ord = "th";// set the ordinal
			break;
		}
	}
	switch(sScript){
		case "sub":
			return num+"<sub>"+ord+"<\/sub>";	// put the ordinal in the HTML sub script
		break;
		case "sup":
			return num+"<sup>"+ord+"<\/sup>";	// put the ordinal in the HTML super script
		break;
		default:
			return num+ord;
		break;
	}	
}


/// ** Show Alert Information Data ** ///
function showAlert(options){
	var options = options || {}; // setup options
	var notification  = options.notification || null; // set the notification type
	var gameId = options.id || this.id; // get this games Id
	var boxKey = options.boxKey || null; // get the box ID/Key
	var gameCallsHolder; // game calls innerHTML holder
	
	if(notification == "score"){ // check for score update notification
		document.getElementById("gameAlert_"+gameId).className = document.getElementById("gameAlert_"+gameId).className+ " gameScore"; // add the gameScore Class
		
		if(document.getElementById("gameCalls_"+gameId).className != "gameScore gameCallsScore"){
		
			gameCallsHolder = document.getElementById("gameCalls_"+gameId).innerHTML; // capture the current data in the gameAlert section		
			document.getElementById("gameCalls_"+gameId).className = document.getElementById("gameCalls_"+gameId).className + " gameCallsScore"; // add the gameCallsScore class
			
			document.getElementById("gameAlert_"+gameId).style.opacity = "100";
			
			var GA = function(){gBehaviorsArray["update"] = Spry.Effect.DoFade("gameAlert_"+gameId,{duration:3000,from:100, to:0});}
			setTimeout(GA, 5000);
		}
		 // bring in the BIG IMAGE over the Game 
	}
	
	
	if(boxKey){ // see if a boxKey was passed through 
	
		gBehaviorsArray["update"] = Spry.Effect.DoHighlight(boxKey,{duration:9000,from:'#FB9A00', to:'#fff', restoreColor:'#fff', finish: function(){
									if(notification == "score"){
										document.getElementById("gameAlert_"+gameId).className = "gameAlert"; // reset the game Alerts class
										document.getElementById("gameCalls_"+gameId).className = "gameCalls"; // reset the game Calls class
										document.getElementById("gameCalls_"+gameId).innerHTML = gameCallsHolder; // reset the HTML data in game Calls
									}
								}});// highlight the ones that don't match
	}	
}


/// ** Check for Home Scores ** ///
var scoreToggle = "score"; // to keep state with the Scores/shots toggle
function getScores(options){ 
	var options = options || {}; // setup options
	var who = options.who || null; // get WHO should be updated
	var nameAtt = options.what || scoreToggle; // attribute name
	var toggle = options.toggle || scoreToggle;  // generic data swap in scores box
	var total = 0; // tally for scores & shots
	
	switch(who){
		case "away":
			var lineScores = this.awayLineScores;
			var prevLineScores = thisPreGame.awayLineScores;
		break;
		case "home":
			var lineScores = this.homeLineScores;
			var prevLineScores = thisPreGame.homeLineScores;
		break;
	}
	
	for(l=0; l<lineScores.length; l++){ // cycle through the linescores				
		
		//// --- Scores update ---- ////
		period = lineScores[l].getAttribute('period'); // get the current period
		nameKey = who+"Quarter_"+period+"_"+this.id; // set the location key
			
		lastPlay = this.lastPlay; 		
		if(!document.getElementById(nameKey)){ // check for new quarters
			if(who=="home"){ // check for the home first... this will load a new header
				addData(this.id, nameKey, lineScores[l].getAttribute(nameAtt), period);	// add in new quarters AND new headers						
			}else{ // just add a new cell... secondary lists
				addData(this.id, nameKey, lineScores[l].getAttribute(nameAtt));	// add in new quarters		
			}
		}else{  // if no new quarters, update the regular data
			try{
			for(a=1; a<=2; a++){ // loop through the tabs			
				tabKey = document.getElementById("ssToggle"+a+"_"+this.id);	// set the tab key
				if(tabKey){ // if the tab key exist
					if(tabKey.className == "tabScore_on"){ // if it's turned on
						nameAtt = tabKey.innerHTML.toLowerCase(); // get the tabs information (title)
					}
				}
			}
			}catch(e){ /*ignore */ } // alert errors
			
			try{
				if(prevLineScores[l].getAttribute(nameAtt)){
					if(prevLineScores[l].getAttribute(nameAtt) != lineScores[l].getAttribute(nameAtt)){ //check for score changes
						document.getElementById(nameKey).innerHTML = lineScores[l].getAttribute(nameAtt); // show new score	
						showAlert({notification: nameAtt, id: this.id, boxKey: nameKey}); // show alerts
						if(nameAtt == "score"){
							document.getElementById("gameCalls_"+this.id).innerHTML = this.whoScored.getAttribute("alias")+ 
																				" Goal: " +
																				this.whoScored.getAttribute('firstname')+" "+
																				this.whoScored.getAttribute('lastname'); // update the gamecalls data
						}
						
					}
				}
			}catch(e){/*ignore*/}
			if(document.getElementById(nameKey)){ // make sure the table data is there
				document.getElementById(nameKey).innerHTML = lineScores[l].getAttribute(nameAtt); // show new data	
			}
		}		
		total = total + parseFloat(lineScores[l].getAttribute(nameAtt)); // add up all of the scores/shots	
	}
	
	if(this.state == "Final"){ // for finals
		getWinners({id: this.id, sHome: this.homeTotalScore, sAway: this.awayTotalScore}) // pass in final information for page update.
	}
	
	document.getElementById(who+"Quarter_to_"+this.id).innerHTML = total; // update the game totals	
}


 /// ** Add links to the bottom of scoreboards ** ///
function addLinks(l, options){ 
	var options = options || {}; // optiosn setup
	var node = options.node || ''; // get the node name
	var attribute = options.attribute || 'url'; // get the attribute
	var display = options.display || ''; // get the display
	var get = options.get || false;
	
	
	if(links[l].getElementsByTagName(node)[0]){ // check for game trax link	
		if(get == false){ // check to see if this is to return specifics		
			return "<a href='"+links[l].getElementsByTagName(node)[0].getAttribute(attribute)+
						"' title='"+display+"'>"+display+"<\/a> | "; // create new link
		}else{			
			return links[l].getElementsByTagName(node)[0].getAttribute(attribute);
				
		}		
	}else{
		return ''; // return nothing
	}	
}

/// ** Show Winners ** ///
function getWinners(options){
	
	try{
		var options = options || {}; // optiosn setup
		var gameId = options.id; // get the game ID
		var homeTotal = options.sHome || this.homeTotalScore;//  get the home scores
		var awayTotal = options.sAway || this.awayTotalScore; // get the away scores
		var winningTD = document.getElementById("board_"+gameId).getElementsByTagName("TD"); // get a handle to the correct game
		var winning= new Array();
		var w=0;	
		for(var a=0; a<winningTD.length; a++){ // loop through them
			if(winningTD[a].className == "teams"){ // find complete stats
				winning[w] = winningTD[a];
				w++;
			}
		}	
		
		
			// Check who won //
			if(homeTotal < awayTotal && winningTD[0].className != "teams winner"){
				winning[0].className = "teams winner";
				return;
			} 
			if(homeTotal > awayTotal && winningTD[0].className != "teams winner"){
				winning[1].className = "teams winner";	
				return;
			}
			if(homeTotal == awayTotal){
				winning[0].className = "teams winner";	
				winning[1].className = "teams winner";	
				return;
			}
		
		
	}catch(e){/*ignore*/}
}



 /// ** Update the Game States ** ///
function getGameState(){
	
	try{
	
		gameState = this.state; // get last play information
		gameStatus=''; // game status holder
		gameSeriesStanding = this.seriesStanding;
		gameTimeKey = "gameStateInfo_"+this.id; // setup the gameplays key
		gameLeaderStatus  ='gameLeaderStats_'+this.id; // leader status box key
		gameCalls = "gameCalls_"+this.id;	
		gameCallsHolder = document.getElementById(gameCalls);
		gameLinksHolder = document.getElementById("gameLinks_"+this.id); // Game Links Holder box key
		holder = document.getElementById('holder_'+this.id); // main game holder box key
		links = this.links; // get all game related links		
		linkTags = ''; // link tag holders			
		
		var completeStatsLink = document.getElementById("gameLeaders_"+this.id).getElementsByTagName("A"); // get anchors		
		if(completeStatsLink){
			for(var a=0; a<completeStatsLink.length; a++){ // loop through them
				if(completeStatsLink[a].className == "completeStats"){ // find complete stats
					completeStatsLink = completeStatsLink[a]; // set the variable.
				}
			}	
		}
		
		switch(gameState){ // check for the game state
			case "Final": // the state is final
				
				gameStatus = this.state;  // get the game state			
				document.getElementById(gameLeaderStatus).innerHTML = "Game Stats";// update game status header
				
				document.getElementById('tab1leaders_'+this.id).innerHTML = "Points"; // update the points tab
				document.getElementById('tab2leaders_'+this.id).innerHTML = "SOG"; // update the Shot on Goal tab
				document.getElementById('tab3leaders_'+this.id).innerHTML = "Saves"; // update the Saves tab
				
				for(l=0; l<links.length; l++){ // loop through all of the links 				
					linkTags += addLinks(l, {node:"recap", display:"Recap"}); // add link to links box 
					linkTags += addLinks(l, {node:"gametracker", display:"Gametrax"}); // add link to links box 
					linkTags += addLinks(l, {node:"boxscore", display:"Box Score"});  // add link to links box
					linkTags += addLinks(l, {node:"playbyplay", display:"Play-By-Play"});  // add link to links box
					linkTags += addLinks(l, {node:"depthchart", display:"Depth Chart"});  // add link to links box
					linkTags += addLinks(l, {node:"statMatchup", display:"Head-to-Head"});  // add link to links box
					completeStatsLink.href = addLinks(l, {get: true, node:"boxscore", attribute:"url"}); // update the complete stats link back
				}				
			break;
			case "In-Progress": // the state is inprogress		
				gameStatus = this.segmentTime+" - "+ordinal(this.segmentNumber)+" Period"; // set the game status			
				document.getElementById(gameLeaderStatus).innerHTML = "Game Stats"; // update game status jheader
				document.getElementById('tab1leaders_'+this.id).innerHTML = "Points";
				document.getElementById('tab2leaders_'+this.id).innerHTML = "SOG";
				document.getElementById('tab3leaders_'+this.id).innerHTML = "Saves";
				
				
				for(l=0; l<links.length; l++){ // loop through all of the links 				
					linkTags += addLinks(l, {node:"gametracker", display:"Gametrax"}); // add link to links box 
					linkTags += addLinks(l, {node:"boxscore", display:"Box Score"});  // add link to links box
					linkTags += addLinks(l, {node:"playbyplay", display:"Play-By-Play"});  // add link to links box
					linkTags += addLinks(l, {node:"depthchart", display:"Depth Chart"});  // add link to links box
					linkTags += addLinks(l, {node:"statMatchup", display:"Head-to-Head"});  // add link to links box
					completeStatsLink.href = addLinks(l, {get: true, node:"boxscore", attribute:"url"}); // update the complete stats link
				}		
			break;	
			case "Pre-Game": // the state is pre-game			
				gameStatus = this.startTime; // set the game state
				document.getElementById(gameLeaderStatus).innerHTML = "Team Leaders"; // update game status header
				document.getElementById('tab1leaders_'+this.id).innerHTML = "Goals";
				document.getElementById('tab2leaders_'+this.id).innerHTML = "Points";
				document.getElementById('tab3leaders_'+this.id).innerHTML = "GAA";
				for(l=0; l<links.length; l++){ // loop through all of the links 				
					linkTags += addLinks(l, {node:"preview", display:"Preview"}); // add link to links box 
					linkTags += addLinks(l, {node:"gametracker", display:"Gametrax"}); // add link to links box 
					linkTags += addLinks(l, {node:"depthchart", display:"Depth Chart"});  // add link to links box
					linkTags += addLinks(l, {node:"statMatchup", display:"Head-to-Head"});  // add link to links box
					linkTags += addLinks(l, {node:"buytickets", display:"Buy Tickets", attribute:"homeUrl"});  // add link to links box
					completeStatsLink.href = "/nhl/stats"; // remove the complete stats link
				}				
			break;
		}
		
		
		if(gameState == "Halftime"){ // check to see if the game STate is HAlftime	
				if(gameCallsHolder.innerHTML != gameState){ // make sure the gamestate isn't set inside of the games holder
					gameCallsData = gameCallsHolder.innerHTML; // update the gamcalls data (get the current html)
					gameCallsHolder.innerHTML = gameState; // set the new html				
				}
		}else{ // if the game state isn't halftime	
			if(thisPreGame.state == "Halftime" && gameState != "Halftime"){ // if it's coming out of halftime
				gameCallsHolder.innerHTML = gameCallsData;	// put the old html back in the game calls holder
				gameCallsData = ''; // clear the game calls data holder
			}		
		}
			
		holder.className = "games "+gameState; // set the new game state class
		
		if(gameStatus){ // check for game status
			var statusLoc = document.getElementById(gameTimeKey); // get the timekeylocation
			var statusLight = function(){statusLoc.className = "left";}// function to turn off
			var segTime = this.segmentTime;
      var gameSeriesStandingString = "&nbsp;&nbsp;-&nbsp;&nbsp;"+gameSeriesStanding;  // display the series standing string with hyphen
      if(gameSeriesStanding == "") { // if the series standing value is empty
        gameSeriesStandingString = "";  // don't display the series standing string with hyphen
      }
			if(segTime != thisPreGame.segmentTime){ // if the current is different from the last
				statusLoc.className = "left on"; // turn on the light
				statusLoc.innerHTML = gameStatus+gameSeriesStandingString; // update the time key anyway
				setTimeout(statusLight, 2000); // wait 2 seconds then turn it off
			}else{ // if there's no change
				statusLoc.innerHTML = gameStatus+gameSeriesStandingString; // update the time key anyway
			}
		}
		
		
		
		var lastPlayKey = "gamePlays_"+this.id; // setup the gameplays key
		var lastPlayResults = this.lastPlay;
		var lastPlayLoc = document.getElementById(lastPlayKey); // get a handle to the last play section
		if(lastPlayLoc && lastPlayResults){ // make sure there IS a key to update
			lastPlayLoc.className=""; // remove it's class
			if(lastPlayResults != thisPreGame.lastPlay){ // if the current is different from the past
				try{
				gBehaviorsArray["lp"] = Spry.Effect.DoFade(lastPlayKey ,{duration:500,from:100, to:0, finish:function(){ // fade out
												lastPlayLoc.innerHTML = lastPlayResults; // update the content for last play
												gBehaviorsArray["lp"] =  Spry.Effect.DoFade(lastPlayKey ,{duration:500,from:0, to:100}); // fade back in
											}})	
				}catch(e){}
			}else{
				lastPlayLoc.innerHTML = lastPlayResults; // update last play anyway
			}
			
		}
		
		
		if(linkTags != ''){ // make sure there are links to add
			gameLinksHolder.innerHTML = linkTags.substr(0,linkTags.length-2);	 // update links on the game & remove the last pipe (|)
		}
	}catch(e){ /*ignore */ }
	
}

 /// ** Update the Leaders Toggle ** ///
function getLeaders(options){					
	
	try{
		var options = options || {}; //options setup
		var who = options.who || null; // get who data				
		var toggle = options.toggle || false; // get the toggle option
		var what = options.what || thisPreGame.leadersToggle; // what to show
		var theLastName; // last name holder
		if(!what){ // make sure something is passed to toggle
			switch(this.state){ // check the game states for correct informatino
				case  "Final": // if final
					this.leadersToggle = "points"; // set the toggle
					thisPreGame.leadersToggle = "points"; // preset the previous toggle
				break; // stop checking
				case  "Pre-Game": // if pregame
					this.leadersToggle = "goals"; // set the toggle
					thisPreGame.leadersToggle = "goals"; // preset the previous toggle
				break; // stop checking
				case  "In-Progress": // if in-progress		
					this.leadersToggle = "points"; // set the toggle
					thisPreGame.leadersToggle = "points"; // preset the previous toggle				
				break; // stop checking
			}	
		}else{  // if nothing was requested or set
			 this.leadersToggle = thisPreGame.leadersToggle;  // use the previously selected toggle to update
			 thisPreGame.leadersToggle = what; // preset the previous toggle
		}
	
		if(who){ // if "who" exists
			switch(who){  // check to see "who's" being up dated (home or away)
				case "away": // if away 
					var leaders = this.awayLeaders; // set the away leaders
					var alias = this.awayAlias; // set the away alias
				break; // stop checking 
				case "home": // if home
					var leaders = this.homeLeaders; // ste the home leaders
					var alias = this.homeAlias; // set the home alias
				break; // stop checking
			}
		}
		
		
		for(var l=0; l<leaders.length; l++){ // cycle through the leaders
			switch(leaders[l].getAttribute('type')){
				case "points":
					 lPoints = leaders[l].getAttribute('stat'); // capture points data
				break;
				case "assists":
					 lAssists = leaders[l].getAttribute('stat'); // capture assist data
				break;
				case "goals":
					 lGoals = leaders[l].getAttribute('stat'); // capture goals data
				break;
				case "saves":
					 lSaves = leaders[l].getAttribute('stat'); // capture saves data
				break;
				case "GAA":
					 lGaa = leaders[l].getAttribute('stat'); // capture GAA data
				break;
				case "SV%":
					 lSV = leaders[l].getAttribute('stat'); // capture Saves percentage data
					 lSVSaves = leaders[l].getAttribute('saves');
				break;
				case "SOG":
					 lSog = leaders[l].getAttribute('stat'); // capture shots on goal data
				break;
			}
		}
		
		for(l=0; l<leaders.length; l++){ // cycle through the leaders
			
			//// --- Leading Player ---- ////
			nameKey = who+"PlayerName_"+this.id; // set the location key		
			nameAtt = thisPreGame.leadersToggle; // attribute name
						
			for(a=1; a<4; a++){ // loop through the tabs
				tabKey = document.getElementById("tab"+a+"leaders_"+this.id); // if set the tabkey or tab ID
				 
				if(tabKey){
					if(tabKey.className == "tlTabs_on"){ // if the tab is currently on, update its data
						if(leaders[l].getAttribute('type').toLowerCase() == tabKey.innerHTML.toLowerCase()){ // get the right leader 
													
							if(document.getElementById(nameKey)){
								
								if(leaders[l].getAttribute('lastname').indexOf('Tied') != -1 || leaders[l].getAttribute('lastname') == ''){
									theLastName = '';
								}else{									
									theLastName = ". "+leaders[l].getAttribute('lastname');
								}							
								document.getElementById(nameKey).innerHTML = leaders[l].getAttribute('firstname').substring(0,1)+theLastName; // show new player name		
							}
						
							if(document.getElementById(who+'Alias_'+this.id)){
								document.getElementById(who+'Alias_'+this.id).innerHTML = alias;  // update the players team alias
								type = tabKey.innerHTML.substring(0,1).toUpperCase()+tabKey.innerHTML.substr(1); // Title Case the type of data
							}
							
							switch(tabKey.innerHTML.toLowerCase()){
								case "points":
									if(this.state == "Pre-Game"){
										document.getElementById(who+"Goals_"+this.id).innerHTML = lPoints+" "+type; // show new saves points
									}else{
										//document.getElementById(who+"Goals_"+this.id).innerHTML = lGoals+" G, "+lAssists+" A"; // show new player points
										document.getElementById(who+"Goals_"+this.id).innerHTML = lPoints+" "+type; // show new saves points
									}
									
									if(leaders[l].getAttribute('playerId') == '' && lPoints != ''){
										document.getElementById(who+"Goals_"+this.id).innerHTML = leaders[l].getAttribute('lastname')+" "+lPoints;									
									}
									if(lPoints == ''){
										document.getElementById(who+"Goals_"+this.id).innerHTML = "No Points Scored";										
									}
									if(leaders[l].getAttribute('lastname').indexOf('Tied') != -1 && lPoints == 0){
										document.getElementById(nameKey).innerHTML = '';
										document.getElementById(who+"Goals_"+this.id).innerHTML = "No Points Scored";
									}
									
								break;						
								case "goals":
									if(lGoals == ''){
										document.getElementById(who+"Goals_"+this.id).innerHTML = "No Goals Scored";
									}else{
										 document.getElementById(who+"Goals_"+this.id).innerHTML = lGoals+" "+type; // show new goals points
									}
									if(leaders[l].getAttribute('lastname').indexOf('Tied') != -1 && lGoals == 0){
										document.getElementById(nameKey).innerHTML = '';
										document.getElementById(who+"Goals_"+this.id).innerHTML = "No Goals Scored";
									}
								break;
								case "saves":
									if(lSaves == ''){
										document.getElementById(who+"Goals_"+this.id).innerHTML = "0 SV, 1.000 SV%"; // show new saves points
									}else{
										//document.getElementById(who+"Goals_"+this.id).innerHTML = lSaves+" SV, "+lSV+" SV%"; // show new saves points
										document.getElementById(who+"Goals_"+this.id).innerHTML = lSVSaves+" SV, "+lSV+" SV%";
									}
									
								
								break;	
								case "gaa":
									document.getElementById(who+"Goals_"+this.id).innerHTML = lGaa+" GAA"; // show new GAA
								break;
								case "sog":
									if(lSog == ''){
										document.getElementById(who+"Goals_"+this.id).innerHTML = "No Shots on Goal";
									}else{
										document.getElementById(who+"Goals_"+this.id).innerHTML = lSog+" SOG"; // show new SOG
									}
									if(leaders[l].getAttribute('lastname').indexOf('Tied') != -1 && lSog == 0){
										document.getElementById(nameKey).innerHTML = '';
										document.getElementById(who+"Goals_"+this.id).innerHTML = "No Shots on Goal";
									}
								break;
							}
						}
						
					}
						
					
				}
			}
			
		}		
	}catch(e){ /*ignore */ }
}

 /// ** Get the Pre-Game information ** ///
function getPreGame(sbGId){	

	try{

		for(i=0; i<preGames.length; i++){ // loop through the games
			if(preGames[i].getAttribute('gameId') == sbGId){ // if the game ID in the XML matches the one passed to it		
				thisPreGame[preGames[i].getAttribute("gameId")] = new Object(); // create a new hash
				thisPreGame.id = preGames[i].getAttribute("gameId"); // get the pregame game ID
				thisPreGame.state = preGames[i].getAttribute("gamestate"); // get the game state
				thisPreGame.seriesStanding = preGames[i].getAttribute("seriesStanding"); // get the game state
				thisPreGame.segmentTime = preGames[i].getAttribute("segment-time");
				thisPreGame.lastPlay = preGames[i].getElementsByTagName('lastPlay')[0].getAttribute("description"); // get/set last play
				thisPreGame.homeLineScores = preGames[i].getElementsByTagName('gamestats')[0].getElementsByTagName("home")[0].getElementsByTagName('linescores')[0].getElementsByTagName('linescore'); // get the home lines scores
				thisPreGame.awayLineScores = preGames[i].getElementsByTagName('gamestats')[0].getElementsByTagName("away")[0].getElementsByTagName('linescores')[0].getElementsByTagName('linescore'); // get the away line scores
				
				return thisPreGame; // return the previous game
				
			}
		}
		return //alert('Error - returned data: '+sbGId);	// if there's an error getting the data, aler the user
	}catch(e){ /*ignore */ }
}

 /// ** Get the Game information ** ///
function getGame(sbGId){
	thisPreGame = getPreGame(sbGId); // get the Previous Game information
	
	for(i=0; i<games.length; i++){ // loop through the games
		if(games[i].getAttribute('gameId') == sbGId){  // if the XML game id matches the one being passed in
			thisGame[games[i].getAttribute("gameId")] = new Object(); // setup a new hash			
			thisGame.id = games[i].getAttribute('gameId');	// get/set the game Id	
			thisGame.state = games[i].getAttribute('gamestate'); // get/set the game state
			thisGame.status = games[i].getAttribute('status');   // get/set the status	
			thisGame.seriesStanding = games[i].getAttribute('seriesStanding');   // get/set the status	
			thisGame.countDownStartTime = games[i].getAttribute('countdownStartTime'); // get/set count down time
			thisGame.date = games[i].getAttribute('date'); // get/set the date
			thisGame.gameDate = games[i].getAttribute('YYYYMMDD');  // get/set the game date
			thisGame.startTime = games[i].getAttribute('startTime'); // get/set the start time
			thisGame.segmentTime = games[i].getAttribute('segment-time'); // get/set the segment time
			thisGame.segmentNumber = games[i].getAttribute('segment-number'); // get/set the 
			thisGame.lastPlay = games[i].getElementsByTagName('lastPlay')[0].getAttribute("description"); // get/set last play
			thisGame.whoScored = games[i].getElementsByTagName('gamestats')[0].getElementsByTagName('lastgoal')[0]; // get/set who scored the last goal
			thisGame.links = games[i].getElementsByTagName('links'); // get/set game links
			thisGame.homeAlias = games[i].getElementsByTagName('home')[1].getAttribute('alias'); // get/set home alias
			thisGame.homeLeaders = games[i].getElementsByTagName('home')[1].getElementsByTagName('leader'); // get/set game leaders			
			thisGame.homeLineScores = games[i].getElementsByTagName('gamestats')[0].getElementsByTagName("home")[0].getElementsByTagName('linescores')[0].getElementsByTagName('linescore'); // get/set home line scores
			thisGame.homeTotalScore = games[i].getElementsByTagName('gamestats')[0].getElementsByTagName("home")[0].getElementsByTagName('linescores')[0].getAttribute('totalscore'); // get/set home total scores
			thisGame.homeTotalShots = games[i].getElementsByTagName('gamestats')[0].getElementsByTagName("home")[0].getElementsByTagName('linescores')[0].getAttribute('shots'); // get/set home total scores
			thisGame.awayLineScores = games[i].getElementsByTagName('gamestats')[0].getElementsByTagName("away")[0].getElementsByTagName('linescores')[0].getElementsByTagName('linescore'); // get/set  away line scores	
			thisGame.awayTotalScore = games[i].getElementsByTagName('gamestats')[0].getElementsByTagName("away")[0].getElementsByTagName('linescores')[0].getAttribute('totalscore'); // get/set home total scores
			thisGame.awayTotalShots = games[i].getElementsByTagName('gamestats')[0].getElementsByTagName("away")[0].getElementsByTagName('linescores')[0].getAttribute('shots'); // get/set home total scores
			thisGame.awayLeaders = games[i].getElementsByTagName('away')[1].getElementsByTagName('leader'); // get/set away leaders
			thisGame.awayAlias = games[i].getElementsByTagName('away')[1].getAttribute('alias'); // get/set away alias
			
			
			/// ** Check for Home Game Leaders ** ///			
			thisGame.getLeaders = getLeaders;
						
			/// ** Get all Score Data update function ** ///
			thisGame.getScores = getScores;
			
			/// ** Add clocks for pre-games function ** ///			
			thisGame.addClock = addClock;
			
			thisGame.getWinners = getWinners;
			
			//// ** Check the Game State ** ////
			thisGame.getGameState = getGameState;
			
			return thisGame;  // return specific game information
		}
	}
	
	return false;	/// return nothing
}

 /// ** Information Tab Toggle ** ///
function infoToggle(ele, options){
	var options = options || {}; // setup options
	var what = options.what || ele.innerHTML.toLowerCase(); // get the tab name
	var other = options.other || false;	
	
	var tabsParent = ele.parentNode.getElementsByTagName("A"); // grab the parent element to the "selecting element"
	var thisClass = ele.className.split("_"); // break out the initial class name
	
	for(var i=0; i<tabsParent.length; i++){ //  loop through all fo the child nodes of the parent
		if(tabsParent[i].className == thisClass[0]+"_on"){ // find the "on" tab
			tabsParent[i].className = thisClass[0]+"_off"; // set the "on" tab off
		}
	}
	ele.className = thisClass[0]+"_on"; // turn THIS elements tab "on"
	elemId = ele.id.split("_"); // split out the game id
	
	
	if(other == false){
			var myGame = getGame(elemId[1]); // get the games information
			
			if(what){ // make sure there is a "what"					
				if(what == "score" || what == "shots"){
					scoreToggle = what; // set the score toggle
					thisGame.getScores({who:"home", what: what, toggle:what}); // update home scores	
					thisGame.getScores({who:"away", what: what, toggle:what}); // update away scores	
				}else{	
					myGame.getLeaders({who:"home", what: what}); // update home leaders	
					myGame.getLeaders({who:"away", what: what}); // update away leaders	
				}		
			}	
	
	}else{		
	
		var tbodyHolder = document.getElementById("board_"+elemId[1]).getElementsByTagName("TBODY"); // get the tbodies	
		switch(what){ // check what to turn off or on
			case "score":				
				tbodyHolder[1].className = 'off'; // turn shots off
				tbodyHolder[0].className = ''; // turn scores on
			break;
			case "shots":
				tbodyHolder[1].className = ''; // turn shots on
				tbodyHolder[0].className = 'off'; // turn scores off
			break;
		}
				
		if(thisClass[0] == "tlTabs"){
			
			var tabHolder = ele.parentNode.getElementsByTagName("DIV"); // Get the top UL
			for(var i=0; i<tabHolder.length; i++){
				if(tabHolder[i].className.indexOf('teamGameLeaders on') != -1){
					tabHolder[i].className = tabHolder[i].className.replace(' on','');
				}
				
				if(tabHolder[i].id == "team"+ele.innerHTML.replace(' ','')+"Leaders_"+elemId[1]){
					tabHolder[i].className = tabHolder[i].className+" on";
				}
			}		
		}
	}

}

function showTab(me, info){ // show tabs
	var tabHolder = me.parentNode.parentNode.childNodes; // Get the top UL
	var leaderHolder = me.parentNode.parentNode.parentNode.childNodes; // Get the top UL
	var tabInfo = document.getElementById(info);
	var t;
	for(var i=0; i<leaderHolder.length; i++){
		if(leaderHolder[i].className == "info on"){
			leaderHolder[i].className = "info";	
			tabInfo.className = "info on";
			
		}
		if(leaderHolder[i].className == "teamGameLeaders on"){
			leaderHolder[i].className = "teamGameLeaders";	
			tabInfo.className = "teamGameLeaders on";
			
		}
	}
	
	
	for(var i=0; i<tabHolder.length; i++){ // cycle through the li's
		if(tabHolder[i].className == "on"){ // if they li's class is "on"		
			tabHolder[i].className = "";	 // turn it off			
			me.parentNode.className = "on" // turn the selected tab on			
			return; // kill the script
		}			
	}	
}

function loadAds(){ /* Load Adds */	
	dapMgr.enableACB('ad300x250box',false); // enable advertisement
	dapMgr.renderAd('ad300x250box', adCode300x250, 300, 250); // render advertisement
	dapMgr.enableACB('ad728x90box',false); // enable advertisement
	dapMgr.renderAd('ad728x90box', adCode728x90, 728, 90);	 // render advertisement	
}


function sendHBXKeepAlive(desc) { /* Hitbox keepalive */
	_hbDownload('keep alive - ' + desc);
}

function serveAdRefreshViaMSFT() {/* server Ad refresh */
	try{
	dapMgr.trackEvent(eventType.click);
	sendHBXKeepAlive("NHL AJAX Scoreboard");
	}catch(e){/*ignore*/}
}
function pageRefresh(){
	window.location.reload();
}

var adTimer =setInterval("serveAdRefreshViaMSFT()", 60000); // 1 min. - launch add refresh
var pageTimer = setTimeout("pageRefresh()", 600000); // 10 min. - reload the page 


