var teamObj = {
	"teams": [
{'teamcode':'t100','clubcode':'chf','old_clubcode':'chf','eliascode':'CHI','teamurl':'http://web.mlsnet.com'},
{'teamcode':'t120','clubcode':'cdc','old_clubcode':'cdc','eliascode':'CHV','teamurl':'http://web.mlsnet.com'},
{'teamcode':'','clubcode':'','old_clubcode':'','eliascode':'COL','teamurl':'http://www.coloradorapids.com','ticketlink':'http://www.coloradorapids.com/Tickets/SingleGameTickets.aspx'},
{'teamcode':'t102','clubcode':'clb','old_clubcode':'coc','eliascode':'CLB','teamurl':'http://web.mlsnet.com'},
{'teamcode':'','clubcode':'dc','old_clubcode':'dcu','eliascode':'DC','teamurl':'http://www.dcunited.com','ticketlink':'http://www.dcunited.com'},
{'teamcode':'t104','clubcode':'dal','old_clubcode':'fcd','eliascode':'DAL','teamurl':'http://web.mlsnet.com'},
{'teamcode':'t200','clubcode':'hou','old_clubcode':'hou','eliascode':'HOU','teamurl':'http://web.mlsnet.com'},
{'teamcode':'t105','clubcode':'kc','old_clubcode':'kcw','eliascode':'KC','teamurl':'http://web.mlsnet.com'},
{'teamcode':'t106','clubcode':'la','old_clubcode':'lag','eliascode':'LA','teamurl':'http://web.mlsnet.com'},
{'teamcode':'','clubcode':'','old_clubcode':'','eliascode':'NE','teamurl':'http://www.revolutionsoccer.net','ticketlink':'http://www.revolutionsoccer.net/ticketpackages'},
{'teamcode':'t107','clubcode':'rbn','old_clubcode':'rbn','eliascode':'NY','teamurl':'http://web.mlsnet.com'},
{'teamcode':'t121','clubcode':'rsl','old_clubcode':'rsl','eliascode':'RSL','teamurl':'http://web.mlsnet.com'},
{'teamcode':'t110','clubcode':'sje','old_clubcode':'sje','eliascode':'SJ','teamurl':'http://web.mlsnet.com'},
{'teamcode':'t280','clubcode':'t280','old_clubcode':'t280','eliascode':'TOR','teamurl':'http://web.mlsnet.com'},
{'teamcode':'','clubcode':'','old_clubcode':'','eliascode':'SEA','teamurl':'http://www.soundersfc.com','ticketlink':'http://www.soundersfc.com/Tickets/Tickets.aspx'},
{'teamcode':'','clubcode':'','old_clubcode':'','eliascode':'PHI','teamurl':'http://www.mlsphilly2010.com'}
]}

function openMTWin(mUrl)
{
	//opens a standard sized matchcentre windo
	var mtWin = window.open(mUrl,'matchcentre','width=1010,height=852,location=no,menubar=no,scrollbars=yes,status=no,toolbar=no,resizable=no');
	mtWin.focus();
}

var month,weekday,previewString,recapString;
function setLanguageVars(lang)
{
	if (lang=='es')
	{
		month = new Array("enero","febrero","marzo","abril","mayo","junio","julio","agosto","septiembre","octubre","noviembre","diciembre");
		weekday = new Array("domingo","lunes","martes","mi&eacute;rcoles","jueves","viernes","s&aacute;bado");
	} else {
		month=new Array("January","February","March","April","May","June","July","August","September","October","November","December");
		weekday = new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
	}
	previewString = (lang=="es"? "Previa":"Preview");
	recapString = (lang=="es"? "Cr&oacute;nica":"Recap");
}

function getLocalizedStatus(gamestatus)
{
	if (lang=='es')
	{
		if (gamestatus=='First Half') return "Primera Mitad";
		if (gamestatus=='Second Half') return "Segunda mitad";
		if (gamestatus=='Halftime') return "Entretiempo";
	} else {
		return gamestatus;
	}	
}
function getLocalizedDate(gd)
{
	if (lang=='es') 
		return weekday[gd.getDay()] + ", " + gd.getDate() + " de " + month[gd.getMonth()];
	else
		return weekday[gd.getDay()] + ", " + month[gd.getMonth()] + " " + gd.getDate();
}
function getGameStatus(gamestatus)
{
	var gc = '';
	switch(gamestatus)
	{
	 case "Game Start" : gc = "pregame"; break;
	 case "Game Pending" : gc = "pregame"; break;
	 
	 case "Game Over" : gc = "final"; break;
	 case "Game End" : gc = "final"; break;
	 
	 case "First Half" : gc = "live"; break;
	 case "Halftime" : gc = "live"; break;
	 case "Second Half" : gc = "live"; break;
	 
	case "Overtime": gc = "live";break;
	case "Second Overtime": gc = "live"; break;
	 case "Shootout" : gc = "live"; break;

	 default : "live";
	}
	return gc;
}
function makeGameDateTime(m,d,y,gametime,ampm,tz)
{
	var th = gametime.substr(0,gametime.indexOf(":"));
	var tm = gametime.substr(gametime.indexOf(":")+1, gametime.indexOf(":")+1); 
	if (ampm == "pm") th = parseInt(th) + 12;
	if (tz == "CT") th = th-1;
	if (tz == "MT") th = th-2;
	if (tz == "PT") th = th-3;
	return new Date(y,m,d,th,tm)
}	

function tenMinuteWarning(y,m,d,th,tm)
{
	var gameStart = new Date(y,m,d,th,tm);
	var now = new Date();
	now = now.getTime();
	gameStart = gameStart.getTime();
	if (now - gameStart < 60000)
		return true;
	else
		return false;
}


function getMediaLinks(g,m,c,sbType,homeaway,gs,lang)
{
	var ml = '';
	var a = '';
	var tv = '';
	var mt = '';
	var v = (gs == "live" ? "v_sub" : "v_free");
	var k = (gs == "live" ? "pre" : "f");
	homeaway = (sbType=='team'?homeaway:"home");
	m.find('game').find('media').each(function(){
		// handle audio one time
		if ($(this).attr('pid')=="mls_game_audio") //look to see if state is final and it's an archive
		{
			if ($(this).attr('key').indexOf(homeaway)>-1 && $(this).attr('language')==lang && ((gs == 'final' && $(this).attr('state').indexOf('archive')>-1)|| gs=='live') )
				a = createMediaLink('',$(this).find('url').attr('id'),'mls_game_audio','a_sub',$(this).find('url').attr('gid'),k)
			//if not there, get the appropriate language other team's feed
			if ($(this).attr('language')==lang && a=='' && ((gs == 'final' && $(this).attr('state').indexOf('archive')>-1) || gs=='live'))
				a = createMediaLink('',$(this).find('url').attr('id'),'mls_game_audio','a_sub',$(this).find('url').attr('gid'),k)
			// if nothing for this language, show no audio link
		}
		// do video one time
/*		if (($(this).attr('pid')=="game_packages" && gs == 'final' && $(this).attr('state').indexOf('archive')>-1 && $(this).attr('key').indexOf('free')>-1) || ($(this).attr('pid')=="mls_game_tv" && gs == 'live'))
		{
			$(this).find('url').each(function(){
				var w = ($(this).text() !='' ? $(this).text():'');
				if ($(this).attr('speed') == "400")
					tv = createMediaLink(w,$(this).attr('w_id'),'mls_game_tv',v,$(this).attr('gid'),k);
				if ($(this).attr('speed') != "400" && tv=='')
					tv = createMediaLink(w,$(this).attr('w_id'),'mls_game_tv',v,$(this).attr('gid'),k);
			})
		}
		New code to account for VPP links below
		*/
		if ($(this).attr('pid')=="mls_game_tv" && gs == 'live')
		{
			$(this).find('url').each(function(){
				var w = ($(this).text() !='' ? $(this).text():'');
				if ($(this).attr('speed') == "400")
					tv = createMediaLink(w,$(this).attr('w_id'),'mls_game_tv',v,$(this).attr('gid'),k);
				if ($(this).attr('speed') == "800" && tv=='')
					tv = createMediaLink(w,$(this).attr('w_id'),'mls_game_tv',v,$(this).attr('gid'),k);
			})
		}
		// for game highlights
		if ($(this).attr('pid')=="game_packages" && gs == 'final' && $(this).attr('state').indexOf('archive')>-1 && $(this).attr('key').indexOf('free')>-1)
		{
			// first look for flash video
			$(this).find('url').each(function(){
				if ($(this).attr('type') == 'flash-video')
					tv = createVppLink($(this).text(),sbType,k);
			})
			// if we don't have flash video, then use the old player.  this makes this backward compatible
			if (tv=='')
			{
				$(this).find('url').each(function(){
					var w = ($(this).text() !='' ? $(this).text():'');
					if ($(this).attr('speed') == "400")
						tv = createMediaLink(w,$(this).attr('w_id'),'mls_game_tv',v,$(this).attr('gid'),k);
					if ($(this).attr('speed') == "800" && tv=='')
						tv = createMediaLink(w,$(this).attr('w_id'),'mls_game_tv',v,$(this).attr('gid'),k);
				})
			}
		}
		
	})
	
	ml = '<div class="sb_summary"><a href="/scoreboard/"><img src="/imgs/icons/scoreboard/icon_matchcenter_' + k + '.gif" alt="match center"></a>';

	ml += tv + a
	//ml += '<a href="/scoreboard/game.jsp?match=' + g.attr('id') + '"><img src="/imgs/icons/scoreboard/icon_matchtrack_' + k + '.gif" alt="match tracker"></a></div>';
	c.find("game").each(function(){
		mt = $(this).attr("gameday_url");
	});
	mt = (mt=='' || mt=='undefined' || mt==null) ? 'http://matchcentre.stats.com/stats-football.asp?lg=MLS&domain=mlsnet.stats.com' : mt;
	ml += '<a href="javascript:openMTWin(\'' + mt + '\');"><img src="/imgs/icons/scoreboard/icon_vwgamenav_' + k + '.gif" alt="match tracker"></a></div>';
	return ml;
	
}
function createVppLink(vppLink,sbType,imgS)
{
	var vLink= '<a href="' + vppLink;
	vLink += (sbType == 'mls') ? '' : '&team_id=' + team_code;
	vLink += '"><img src="http://www.mlsnet.com/imgs/icons/scoreboard/icon_video_' + imgS + '.gif" alt="video"></a>'
	return vLink;
}

function createMediaLink(w,w_id,catCode,type,gid,imgS)
{
	var mLink = '';
	var alt = (catCode=="mls_game_audio" ? 'audio':'video');
	if (w_id=='') return '';
	mLink = "<a href=\"javascript:mediaPlayer.play({";
	if (w!='' && w.indexOf('reflector')<0) mLink += "w:'" + w + "',";
	mLink += "w_id:'" + w_id + "',catCode:'" + catCode +"',type:'"+ type + "',gid:'" + gid + "'})\">";
	mLink += '<img src="/imgs/icons/scoreboard/icon_' + alt + '_' + imgS + '.gif" alt="' + alt + '"></a>';
	return mLink;	
}

function getMediaList(b,type,club_code)
{
	var list = '';
	b.find('source').each(function(i){
		if (type=="TV")
		{
			if ((($(this).attr('source_comment') == 'National' && club_code=='mls' && list.indexOf($(this).attr('source_desc'))<0) || $(this).attr('team_code')==club_code) && $(this).attr('source_type')=="TV")
				list +=  $(this).attr('source_desc') + ", ";
		} else {	
			if (($(this).attr('team_code')==club_code || club_code == 'mls') && ($(this).attr('source_type')=="AM" || $(this).attr('source_type')=="FM"))
				list += $(this).attr('source_desc') + ", ";
		}
	})
	list = (list !=''? type + ": " + list.substr(0,list.length-2): ''); //get rid of the last comma;
	return list;
}
function getTicketLink(eCode,sbType)
{
	var tUrl = '';
	if (sbType=='team')
	{
		tUrl = "/" + team_code + "/tickets";
	} else {
		for (var i=0;i<teamObj.teams.length;i++)
		{
			if (teamObj.teams[i].eliascode == eCode)
			{
				if (teamObj.teams[i].teamcode == '')
					tUrl = teamObj.teams[i].ticketlink;
				else
					tUrl = teamObj.teams[i].teamurl + "/" + teamObj.teams[i].teamcode + "/tickets/";
			}
		}
	}
	if (tUrl == '') tUrl = '/mls/tickets/';
	return tUrl;
}
function initScoreboardTabs()
{
	$("#mlsTabImg").click(function () { 
      	showSB('mls'); 
    });
	$("#globalTabImg").click(function () { 
      	showSB('global'); 
    });
}
function showSB(sb)
{
	if (activeTab != sb)
	{
		if (sb=='mls')
			initScoreboard()
		else
			initGlobalScoreboard()
		$(".sbTabImg").each(function(){
			if ($(this).attr('id').indexOf(sb)>-1)
				document.getElementById($(this).attr("id")).src= document.getElementById($(this).attr("id")).src.replace("_sm","_lg");
			else
				document.getElementById($(this).attr("id")).src= document.getElementById($(this).attr("id")).src.replace("_lg","_sm");
		})
		activeTab = sb;
	}
	
}
function drawGlobalScoreboard()
{
	$("#team_scoreboards").load(globalDataFile);
}

function drawScoreboard()
{
	setLanguageVars(lang);
	var sb = '';
	var g, b, lk, m, c;
	var gamestatus;
	var gametime;
	var hometeam;
	var homescore;
	var awayteam;
	var awayscore;
	var gameinfo1, gameinfo2;
	var gamesummary;
	var ticketlink;
	var gl;
	var nd = new Date('January 1, 2009');
	var gd =''; //gamedate
	var gc; //game class
	var gs;
	var gId;
	$.ajax({
	  type: "GET",
	  url: datafile,
	  dataType: "xml",
	  success: function(xml){
	  	$(xml).find('game_complete').each(function(){
			g = $(this).find('data').find('game');
			b = $(this).find('content').find('broadcasting');
			lk = $(this).find('content').find('game_links');
			m = $(this).find('media');
			c = $(this).find('content');
			
			//new variables for each game!
			homeaway = 'home'; // default to home. 
			hometeam = '';
			homescore = '';
			awayteam = '';
			awayscore = '';
			gameinfo1 = '';
			gameinfo2 = '';
			ticketlink = '';
			gamesummary = '';
			gmc = '';
			tvL = '';
			audL = '';
			gl = '';
			gc = ''; 
			gId = '';
			//the date for the game
			gd = makeGameDateTime((g.attr('id').substr(0,2)-1),g.attr('id').substr(2,2),g.attr('id').substr(4,4),g.attr('game_time'),g.attr("am_pm"), tz);						
			//gametime = g.attr('game_time') + g.attr('am_pm') + " " +  g.attr('timezone');
			// correct for local time
			gametime = (gd.getHours() ==0 ? "12":gd.getHours()) + ":" + (gd.getMinutes() >0 ? gd.getMinutes(): "00") + g.attr('am_pm');
			
			// get the game's current status
			gamestatus = g.attr('status');
			gs = getGameStatus(gamestatus);
			
			//get home and away teams
			g.find('event').find('team').each(function(){
				if ($(this).attr('vishom')=="away")
					awayteam = $(this).attr('abbr');
				else
					hometeam = $(this).attr('abbr');
			});
			homescore = g.attr('homeScore');
			awayscore = g.attr('awayScore');
			if (sbType=='mls')
				homeaway == 'mls';
			else
				homeaway = (awayteam==e_code ? "away" : "home");

			// get the game ID
			gId = g.attr('id');
			
			if (gs == "live")
			{	
				if (gamestatus=='Shootout')
					gameinfo1 = "";
				else
					gameinfo1 = (parseInt(g.find('event:last').find('eventtext_pxp').attr('mmss').substr(0,2)) + 1) + "'";
				gameinfo2 = getLocalizedStatus(gamestatus); 
				gl = getMediaLinks(g,m,c,sbType,homeaway,gs,lang)
				tvL = getMediaList(b,'TV',old_team_code);
				audL = (sbType== 'team' ? getMediaList(b,'Radio',old_team_code) : "");
			}
			if (gs == "pregame")
			{	 
				homescore="";
				awayscore="";
				ticketlink = '<a href="' + getTicketLink(hometeam) + '"><img src="http://web.mlsnet.com/imgs/icons/tickets.gif" border="0" align="absmiddle" style="position:relative;left:-4px;margin-right:4px;"/></a>';
				gameinfo1 = ticketlink + gametime;
				lk.find('link').each(function(){
					//find the link for this team that is a preview
					if ($(this).attr('owner')==team_code && $(this).attr('type').indexOf('preview')>-1 && $(this).attr('language')==lang)	
						gameinfo2 ='<a href="' + $(this).find('url').text() + '">' + previewString + '</a>';
				})
				tvL = getMediaList(b,'TV',old_team_code);
				audL = (sbType=='team' ? getMediaList(b,'Radio',old_team_code) : "");
			}
			if (gs == "final")
			{
				// final score, recap link
				var winner;
				var wingoalindex;
				var player;
				var pID; //playerID
				var gtd; //goalstodate
				var wintime;
				var winhalf;

				gameinfo1 = 'F';
				lk.find('link').each(function(){
					//find the link for this team that is a recap
					if ($(this).attr('owner')==team_code && $(this).attr('type').indexOf('recap')>-1 && $(this).attr('language')==lang)	
						gameinfo2 = '<a href="' + $(this).find('url').text() + '">' + recapString + '</a>';
				})
				// game winning/tying goal
				if (homescore != awayscore) //find the gamewinner
				{
					if (homescore>awayscore) 
					{
						winner = hometeam;
						wingoalindex = (parseInt(awayscore) + 1);
					}
					else
					{
						winner = awayteam;
						wingoalindex = (parseInt(homescore) + 1);
					}
					// find that goal for that team
					var cGoals = 0; //cumulative goals scored by the winning team
					g.find('event').each(function(){
						if ($(this).attr('type')=="Goal" && $(this).find('eventtext_pxp').attr('tgttm') == winner)
						{
							cGoals = cGoals + 1;
							if (cGoals == wingoalindex)
							{
								pID = $(this).find('eventtext_pxp').attr('player');
								gtd = $(this).find('eventtext_pxp').attr('player_ytd_goals');
								wintime = (parseInt($(this).find('eventtext_pxp').attr('mmss').substr(0,$(this).find('eventtext_pxp').attr('mmss').indexOf(":"))) + 1) + "'"
								winhalf = $(this).find('eventtext_pxp').attr('half');
								// go find the player name from the first event
								g.find('event:first').find('team').each(function(){
									if ($(this).attr('abbr') == winner)
									{
										$(this).find('player').each(function(){
											if ($(this).attr('id') == pID)
											{
												player = $(this).attr('lastName');
												return false;
											}
										})
									return false;
									}
								})
								return false;
							} 
						}
					})
					gamesummary = "GWG: " + player + " (" + gtd  + ") - " + wintime;
					if ((parseInt(wintime)>45 && winhalf == "1") || (parseInt(wintime)>90)) gamesummary += "+";
				}
				else  //tie!
				{
					if (homescore>0)
					{
						//find the game tying goal, which is the last one. 
						g.find('event').each(function(){
							//just set the variables.  the last goal will be set when it completes
							if ($(this).attr('type')=="Goal")
							{
								pID = $(this).find('eventtext_pxp').attr('player');
								gtd = $(this).find('eventtext_pxp').attr('player_ytd_goals');
								wintime = (parseInt($(this).find('eventtext_pxp').attr('mmss').substr(0,$(this).find('eventtext_pxp').attr('mmss').indexOf(":"))) + 1) + "'";
								tt = $(this).find('eventtext_pxp').attr('tgttm');									
							}
						})
						g.find('event:first').find('team').each(function(){
							if ($(this).attr('abbr') == tt)
							{
								$(this).find('player').each(function(){
									if ($(this).attr('id') == pID)
									{
										player = $(this).attr('lastName');
										return false;
									}
								})
							return false;
							}
						})
						gamesummary = "GTG: " + player + " (" + gtd  + ") - " + wintime;
					}
					else //scoreless tie.  shots only
					{
						var hshots = 0;
						var ashots = 0;
						g.find('event').each(function(){
							// count shots
							if ($(this).attr('type') == "Shot")
							{
								if ($(this).find('eventtext_pxp').attr('tgttm')==hometeam)
									hshots = hshots +1;
								if ($(this).find('eventtext_pxp').attr('tgttm')==awayteam)
									ashots = ashots +1;
							}	
						})
						gamesummary = "Shots: " + hometeam + " - " + hshots + ", " + awayteam + ' - ' + ashots;
					}
					//check to see if there were, infact, penalty kicks.
					if (g.attr("homeShootoutScore") !="0" && g.attr("awayShootoutScore") != "0") //shootout!
					{
						if (parseInt(g.attr("homeShootoutScore")) > parseInt(g.attr("awayShootoutScore")))
							gamesummary = hometeam + " wins in PKs " + g.attr("homeShootoutScore") + "-" + g.attr("awayShootoutScore");
						else
							gamesummary = awayteam + " wins in PKs " + g.attr("awayShootoutScore") + "-" + g.attr("homeShootoutScore");
					}
				}	
				gl =  getMediaLinks(g,m,c,sbType,homeaway,gs,lang)
			}
			
			if (nd.getMonth() != gd.getMonth() || nd.getDate() != gd.getDate()) sb += '<div class="day"><h3>' + getLocalizedDate(gd) + '</h3></div>';
			//single game items
			if (hometeam == "MLS") sb+= (lang=='es' ? '<a href="/mls/es/events/all_star/2009/index.jsp">' : '<a href="/mls/events/all_star/2009/index.jsp">') + '<img src="/imgs/icons/scoreboard/mls_asg_scoreboard_180.jpg" border="0" /></a>';
			if (gId == "08052009_TIGCHI") sb += (lang=='es' ? '<a href="http://www.superliga2009.com/es">' : '<a href="http://www.superliga2009.com">') + '<img src="/imgs/icons/scoreboard/superliga_180x22.jpg" border="0" /></a>';
			//create the games
			sb += '<div class="game">\n';
			sb += '<div class="' + gs 
			if (lang=='es' && gs =='live') sb += "_es";
			sb +='"><img src="/imgs/icons/scoreboard/' + gs + '_header';
			if (lang=='es') sb += "_es";
			sb += '.gif" border="0" />\n';
			sb += '<table cellspacing="0"><tr><td class="team1">' + awayteam + '&nbsp;' + awayscore + '</td>';
			sb += '<td class="team2">' + hometeam + '&nbsp;' + homescore + '</td>';
			sb += '<td class="info1">' + gameinfo1 + '</td>';
			sb += '<td class="info2">' + gameinfo2 + '</td></tr>';
			if (gamesummary !='') sb += '<tr><td colspan="4" class="gsummary">' +  gamesummary + '</td></tr>';
			if (gl!='') sb += '<tr><td colspan="4" class="gamelinks">' + gl + '</td></tr>';
			if (tvL!='') sb += '<tr><td colspan="4" class="media">' + tvL + '</td></tr>';
			if (audL!='') sb += '<tr><td colspan="4" class="media">' + audL + '</td></tr>';
			sb += '</table>\n';
			sb += '</div>\n</div>\n';
			nd = gd;
		});
	  $("#team_scoreboards").html(sb);
		if (sbType =='team')
			trackClick("Club Mini Scoreboard Refresh");
		else
			trackClick("MLS Mini Scoreboard Refresh");
	  },
	  error: function(){
	  	$("#team_scoreboards").html('<p style="font-size:.9em;margin-bottom:8px;">MatchCenter data is currently unavailable</p>');
		}
	});
}
var sbInterval = 0;
function initScoreboard()
{
	clearInterval(sbInterval);
	drawScoreboard();
	sbInterval = setInterval(drawScoreboard, 60000);
}	
function initGlobalScoreboard()
{
	clearInterval(sbInterval);
	drawGlobalScoreboard()
	sbInterval = setInterval(drawGlobalScoreboard, 60000);
}
