//var storage = "";


var League = "WC";

var leagueOvertimeColumn = [0,5,5,0,0,10,4,3,0,5 ];
var leagueTimePeriod =     [0,15,15,0,0,0,0,20,0,12 ];
var leagueNumPeriods =     [0,4,4,0,0,9,3,2,0,4 ];
var leagueTimePeriodOverTime =     [0,15,15,0,0,0,0,5,0,5 ];

var currentSeason = getCurrentSeason(League);
var LocationNames = [ "","","","" ];
var secondRoundAbbr = [ "","","","","","","","" ];
var secondRoundName = [ "","","","","","","","" ];
var secondRoundCode = [ "","","","","","","","" ];
var secondRoundPrevDate = [ "","","","","","","","" ];
var secondRoundRank = [ "","","","","","","","" ];
var secondRoundIndex = [ 0,0,0,0,0,0,0,0 ];
var secondRoundEvent_Key = [ "","","","","","","","" ];

var sweet16Abbr = [ "","","","" ];
var sweet16Name = [ "","","","" ];
var sweet16Code = [ "","","","" ];
var sweet16PrevDate = [ "","","","" ];
var sweet16Rank = [ "","","","" ];
var sweet16Index = [ 0,0,0,0 ];
var sweet16Event_Key = [ "","","","" ];

var elite8Abbr = [ "","","","" ];
var elite8Name = [ "","","","" ];
var elite8Code = [ "","","","" ];
var elite8PrevDate = [ "","","","" ];
var elite8Rank = [ "","","","" ];
var elite8Index = [ 0,0,0,0 ];
var elite8Event_Key = [ "","","","" ];

var final4Abbr = [ "","","","" ];
var final4Name = [ "","","","" ];
var final4Code = [ "","","","" ];
var final4PrevDate = [ "","","","" ];
var final4Rank = [ "","","","" ];
var final4Index = [ 0,0,0,0 ];
var final4Event_Key = [ "","","","" ];

var championshipAbbr = [ "","" ];
var championshipName = [ "","" ];
var championshipCode = [ "","" ];
var championshipPrevDate = [ "","" ];
var championshipRank = [ "","" ];
var championshipIndex = [ 0,0 ];

var startDate = "2006-05-30";
var scoreFlashIds = "";
var lastViewDate;
var bufferedDivs = "";

var bracketHome = [ 16,9,12,13, 11,14,10,15 ];
var bracketVisit = [ 1,8,5,4, 6,3,7,2 ];

var baseDate = startDate.substring(0,4)+startDate.substring(5,7)+startDate.substring(8,10); //20060217

var tDate = new Date();
var tDateString = ( tDate.getFullYear() + "" + ( (tDate.getMonth()+1) < 10 ? "0"+ (tDate.getMonth()+1) : tDate.getMonth()+1 ) + "" + (tDate.getDate() < 10 ? "0" + tDate.getDate() : tDate.getDate() ) );
var updateIndex = getDateDif( baseDate, tDateString );

var cache = ["","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""];
var cacheCount = cache.length;

var customScoreboardDiv = null;
var AllEvents = "";
//var Week;
//var Period;
var Year;
var refreshCounter = 0;
var localCache = "";

	function getDateDif( startDate, endDate ) {
		//alert(startDate+" "+ endDate);
		var mendDate = new Date( parseInt( endDate.substring(0,4), 10 ), parseInt( endDate.substring(4,6), 10 ) - 1, parseInt( endDate.substring(6,8), 10 ), 00, 00, 00);  //Next millennium start date
		var mstartDate = new Date( parseInt( startDate.substring(0,4), 10 ), parseInt( startDate.substring(4,6), 10 ) - 1, parseInt( startDate.substring(6,8), 10 ), 00, 00, 00);  //Next millennium start date
		var diff = mendDate - mstartDate;    //difference in milliseconds
		var mtg = new String(diff/86400000);    //calculate days and convert to string
		var point = mtg.indexOf(".");    //find the decimal point
		if ( point == -1 ) {
			return mtg;
		} else {
			var days = mtg.substring(0,point);    //get just the whole days
			return days;
		}
	}

	function updateBracket() {

		//storage = "";
		//alert("updateBraket");
		//populateBrackett( false, true );
		//alert( AllEvents.indexOf("||"));
		if ( AllEvents.indexOf("||") != -1 ) {

			//alert("100: "+ AllEvents);

			var bracketArray = AllEvents.split("||");
			for ( var i=0; i<bracketArray.length; i++ ) {
				//alert(bracketArray[i]);

				var bracketElement = replacestring( bracketArray[i], "|", "", true );
				var element = bracketElement.split(",");
				var visitEventDiv = document.getElementById("VisitEvent-"+element[1]);
				var homeEventDiv = document.getElementById("HomeEvent-"+element[1]);
				var Year = element[2].substring(0,4);
				var timePeriod = element[2].substring(5,7) + element[2].substring(8,10);
				var TeamOnTop = element[3];
				var gameXml = cInclude( null, "data\\"+League+"ScoresAndMatchup\\Xml\\"+Year+"\\"+timePeriod+"\\"+element[0]+".xml?code="+getRandom( League ) );

				//alert(element[0])
				//alert(gameXml)
				//alert("data\\"+League+"ScoresAndMatchup\\Xml\\"+Year+"\\"+timePeriod+"\\"+element[0]+".xml?code="+getRandom( League ) )
				//hack wrong ids 31638, 31634, 31636

				var GameDateTime = getFieldContents( "GameDateTime", gameXml );
				var ViewDate = Year + "-" + element[2].substring(5,7) + "-" + element[2].substring(8,10);
				var ScoreStatus = getFieldContents( "ScoreStatus", gameXml );
				var Total2 = getFieldContents( "Total2", gameXml );
				var Spread2 = getFieldContents( "Spread2", gameXml );
				var VisitTeamABR = getFieldContents( "VisitTeamABR", gameXml );
				var HomeTeamABR = getFieldContents( "HomeTeamABR", gameXml );
				var nowDate = new Date();
				
				//alert("120 GameDateTime: " + GameDateTime);

				nowDate.setFullYear( parseInt( GameDateTime.substring(0,4), 10 ), parseInt( GameDateTime.substring(5,7), 10 ) - 1, parseInt( GameDateTime.substring(8,10), 10 ) );
				nowDate.setHours( parseInt( GameDateTime.substring(11,13), 10 ), parseInt( GameDateTime.substring(14,16), 10 ) );

				var Event_Key = getFieldContents( "Event_Key", gameXml );

				//alert("130ScoreStatus: " + ScoreStatus + " " + VisitTeamABR);

				var scoreStatusDiv = document.getElementById("ScoreStatus-"+element[1]);
				//alert(element[1]);
				//alert(scoreStatusDiv.innerHTML);

				if ( scoreStatusDiv != null ) {
					//alert("143: ScoreStatus: " + ScoreStatus); //hack empty score status
				
					if ( ScoreStatus.indexOf("Final") != -1 || ScoreStatus != "" ) {
						//alert("setting score status")
						scoreStatusDiv.innerHTML = ScoreStatus;
						//scoreStatusDiv.innerHTML = "&nbsp;&nbsp;" + ScoreStatus;
						//scoreStatusDiv.innerHTML = "&nbsp;&nbsp;<font color='000000'>" + ScoreStatus + "</font>";
					} else {
						//alert("setting score time")
						//alert("3")
						scoreStatusDiv.innerHTML = formatDate( nowDate , "HH:mm" ) +" BST";
						//scoreStatusDiv.innerHTML = formatDate( nowDate , "NNN dd, HH:mm" ) +" BST";
						//scoreStatusDiv.innerHTML = formatDate( GameDateTime , "NNN dd, h:mma" ) +" ET";
					}
				}else{
					//alert("151 score status div null"); //hack
				}
				var VisitScore = "";
				var HomeScore = "";
				if ( VisitTeamABR != TeamOnTop ) {
					VisitScore = getFieldContents( "VisitScore", gameXml );
					HomeScore = getFieldContents( "HomeScore", gameXml );
				} else {
					VisitScore = getFieldContents( "HomeScore", gameXml );
					HomeScore = getFieldContents( "VisitScore", gameXml );
				}
				var visitScoreDiv = document.getElementById("VisitScore-"+element[1]);
				var homeScoreDiv = document.getElementById("HomeScore-"+element[1]);
				
				
//alert("homeScoreDiv: " + homeScoreDiv);
				if ( visitScoreDiv != null ) {
					var divContents = " ";
					if ( ScoreStatus.indexOf("Final") != -1 || ScoreStatus != "" ) {
						//divContents = "<center><a href='javascript:void(0);' onClick='addScoreBox( event, "+element[0]+", \""+ViewDate+"\" );'>"+HomeScore+"</a></center>";
						//divContents = HomeScore;
						divContents = VisitScore;
					} else {
						//if ( Total2 == "" ) {
							divContents = "&nbsp;0";
						//} else {
						//	divContents = "<center><a href='/sports/common/lineHistory.aspx?eventId="+element[0]+"&sport=wc'>"+(( VisitTeamABR != TeamOnTop )?Spread2:Total2)+"</a></center>";
						//}
					}
					visitScoreDiv.innerHTML = divContents;
				}

				if ( homeScoreDiv != null ) {

					var divContents = " ";
					//alert(ScoreStatus);
					if ( ScoreStatus.indexOf("Final") != -1 || ScoreStatus != "" ) {
						//divContents = "<center><a href='javascript:void(0);' onClick='addScoreBox( event, "+element[0]+", \""+ViewDate+"\" );'>"+VisitScore+"</a></center>";
						//divContents = VisitScore;
						divContents = HomeScore;
					} else {
						//if ( Spread2 == "" ) {
							divContents = "&nbsp;0";
						//} else {
						//	divContents = "<center><a href='/sports/common/lineHistory.aspx?eventId="+element[0]+"&sport=wc'>"+(( VisitTeamABR != TeamOnTop )?Total2:Spread2)+"</a></center>";
						//}
					}
					homeScoreDiv.innerHTML = divContents;
				}
			}
		}
		window.setTimeout("updateBracket();", 10000 ); //hack 10000

		refreshCounter++;
		if ( refreshCounter > 5) { //hack 5
			refreshCounter = 0;
			populateBrackett( false );
		}
	}

	//called from body onload(true for init)
	function populateBrackett( init, refresh ) {


//alert("215 " + "/sports-scores/data/"+League+"ScoresAndMatchup/Xml/WorldCupBracket"+currentSeason+".xml");

		AllEvents = "";
		//load the xml from the file WorldCupBracket2005-2006
		var contentXml = cInclude( null, "/sports-scores/data/"+League+"ScoresAndMatchup/Xml/WorldCupBracket"+currentSeason+".xml");
		cacheScores( startDate, init );

//alert(contentXml);

		for ( var location=0; location<1; location++ ) { //LocationArray.length-1
		//for ( var location=0; location<LocationArray.length-1; location++ ) { //LocationArray.length-1
		//	var locationXnl = replacestring( LocationArray[location], "<Location>", "", true );

			//set Location Data
			//var Name = getFieldContents( "Name", locationXnl );
			//LocationNames[location] = Name;
			//var splitNameString = "";
			//for ( var i=0; i<Name.length; i++ ) {
			//	splitNameString += ( Name.substring(i, i+1) + "<br>" );
			//}
			//var nameDiv = document.getElementById("name"+location);
			//nameDiv.innerHTML = splitNameString;

			//var secondRound = [ 0,0,0,0 ];

			//get Event Data for this location ( there are 4 each )
			//var EventArray = LocationArray[location].split("</Event>");
			var EventArray =  contentXml.split("</Event>"); //s

			for ( var events=0; events<EventArray.length-1; events++ ) {

				var round = Math.floor(events / 2);

				var eventXml = replacestring( EventArray[events], "<Event>", "", true );

				var EventID = getFieldContents( "EventID", eventXml );
				
				//alert("eventID " + EventID);
				var GameDateTime = getFieldContents( "GameDateTime", eventXml );

				//alert(GameDateTime);
				var Year = GameDateTime.substring(0,4);
				var timePeriod = GameDateTime.substring(5,7) + GameDateTime.substring(8,10);

				//get game Xml
				var gameXml = cInclude( null, "data\\"+League+"ScoresAndMatchup\\Xml\\"+Year+"\\"+timePeriod+"\\"+EventID+".xml?code="+getRandom( League ) );
				//var gameXml = cInclude( null, "data\\"+ "NCAABScoresAndMatchup\\Xml\\"+Year+"\\"+timePeriod+"\\"+EventID+".xml?code="+getRandom( League ) );

				//alert(gameXml)
				//alert("254 setting HomeTeamName: " + HomeTeamName);

				var HomeTeamName = getFieldContents( "HomeTeamName", gameXml );//.substring(0,11);
				var VisitTeamName = getFieldContents( "VisitTeamName", gameXml );//.substring(0,11);
				
				VisitTeamName = replacestring( VisitTeamName, "Serbia and Montenegro", "Serbia & Mont", true );
				HomeTeamName = replacestring( HomeTeamName, "Serbia and Montenegro", "Serbia & Mont", true );
				VisitTeamName = replacestring( VisitTeamName, "Trinidad &amp; Tobago", "Trinidad & Tob", true );
				HomeTeamName = replacestring( HomeTeamName, "Trinidad &amp; Tobago", "Trinidad & Tob", true );
				HomeTeamName = replacestring( HomeTeamName, "Czech Republic", "Czech", true );

				
//alert("HomeTeamName:259 " + HomeTeamName);

				var TeamOnTop = VisitTeamABR;

				var HomeTeamABR = getFieldContents( "HomeTeamABR", gameXml )
				var VisitTeamABR = getFieldContents( "VisitTeamABR", gameXml );
				var HomeScore = getFieldContents( "HomeScore", gameXml );
				var VisitScore = getFieldContents( "VisitScore", gameXml );
				var GameDateTime = getFieldContents( "GameDateTime", gameXml );
				var startingDate = GameDateTime.substring(0,4)+GameDateTime.substring(5,7)+GameDateTime.substring(8,10);
				var ScoreStatus = getFieldContents( "ScoreStatus", gameXml );
				var VisitTeamCode = getFieldContents( "VisitTeamCode", gameXml );
				var HomeTeamCode = getFieldContents( "HomeTeamCode", gameXml );
				var Total2 = getFieldContents( "Total2", gameXml );
				var Spread2 = getFieldContents( "Spread2", gameXml );
				var Event_Key = getFieldContents( "Event_Key", gameXml );
				//alert("var Event_Key: " + Event_Key);
				//alert(gameXml);

				var VisitRank = bracketVisit[events];
				var HomeRank = bracketHome[events];

				//alert("location-0-events: " + location+"-0-"+events);

				var MatchUpLink = getFieldContents( "MatchUpLink", gameXml );
				if (MatchUpLink == 'true'){
					//var Event_Key =  1 //getFieldContents( "Event_Key", gameXml );
					var fixtureDiv = document.getElementById("fixture-"+location+"-0-"+events);
					if ( fixtureDiv != null ) {
						var strFixture = fixtureDiv.innerHTML;
						//alert("setting fixture");
						fixtureDiv.innerHTML = "<a href='http:/pageLoader/pageLoader.aspx?page=/data/worldcup/matchups/g1_summary_"+Event_Key+".html'>"+strFixture+"</a>";
					}
				}

				var visitEventDiv = document.getElementById("VisitEvent-"+location+"-0-"+events);
				//alert("here comes the name")
				if ( visitEventDiv != null ) {
					visitEventDiv.innerHTML = ( VisitTeamName == "" ? "" : "&#160;" ) + " <a href='http://www.covers.co.uk/pageLoader/pageLoader.aspx?page=/data/worldcup/teams/team"+VisitTeamCode+".html'>"+VisitTeamName+"</a>";
				}
				//alert(ScoreStatus + " " + VisitScore + " " + HomeScore);
				var visitScoreDiv = document.getElementById("VisitScore-"+location+"-0-"+events);
				if ( visitScoreDiv != null ) {
					var divContents = "";
					if ( ScoreStatus != "" ) {				 // && parseInt( VisitScore ) > parseInt( HomeScore )

						//divContents = "<a href='/sports/worldcup/lineHistory.aspx?eventId="+EventID+"'>"+VisitScore+"</a>";
						divContents = VisitScore;

						if ( ScoreStatus.indexOf("Final") != -1 && parseInt( VisitScore ) > parseInt( HomeScore ) ) {
							//alert( getDateDif( startingDate, baseDate ) + " " + startingDate + " " + baseDate );
							//alert("313about to set team data " + VisitTeamName);
							setTeamData( "secondRound", events, VisitRank, VisitTeamName, VisitTeamABR, VisitTeamCode, GameDateTime, null, getDateDif( baseDate, startingDate ), EventID, location+"-0-"+events );
						}

					} else {
						//divContents = "&nbsp;&nbsp;<a href='/sports/common/lineHistory.aspx?eventId="+EventID+"&sport=wc'>"+(( VisitTeamABR != TeamOnTop )?Spread2:Total2)+"</a>";

					}
					visitScoreDiv.innerHTML = divContents;
				}

				//alert("events: " + events);
				var homeEventDiv = document.getElementById("HomeEvent-"+location+"-0-"+events);
//alert("location, 0, events: " + location + "-0-"+ events);
				if ( homeEventDiv != null ) {
					//n alert("327 setting home team name");
					homeEventDiv.innerHTML = ( HomeTeamName == "" ? "" : "&#160;" ) + " <a href='http://www.covers.co.uk/pageloader/pageloader.aspx?page=/data/worldcup/teams/team"+HomeTeamCode+".html'>"+HomeTeamName+"</a>";
				}
				var homeScoreDiv = document.getElementById("HomeScore-"+location+"-0-"+events);
				if ( homeScoreDiv != null ) {
					var divContents = "";
					if ( ScoreStatus != "" ) { //&& parseInt( HomeScore ) > parseInt( VisitScore )

						//divContents = "<a href='/sports/worldcup/lineHistory.aspx?eventId="+EventID+"'>"+HomeScore+"</a>";
						divContents = HomeScore;

						if ( ScoreStatus.indexOf("Final") != -1 && parseInt( HomeScore ) > parseInt( VisitScore ) ) {
							//setTeamData( "secondRound", events, HomeRank, HomeTeamName, HomeTeamABR, HomeTeamCode, GameDateTime, null, getDateDif( baseDate, startingDate ), EventID, location+"-0-"+events );
							//alert("341 set team data " + HomeTeamName);
							setTeamData( "secondRound", events, HomeRank, HomeTeamName, HomeTeamABR, HomeTeamCode, GameDateTime, null, getDateDif( baseDate, startingDate ), EventID, location+"-0-"+events );
						}

					} else {
						//divContents = "&nbsp;<a href='/sports/common/lineHistory.aspx?eventId="+EventID+"&sport=wc'>"+(( VisitTeamABR != TeamOnTop )?Total2:Spread2)+"</a>";
					}
					homeScoreDiv.innerHTML = divContents;
				}
				//----------------------------------------------

				//update the score status
				var scoreStatusDiv = document.getElementById("ScoreStatus-"+location+"-0-"+events);

//				alert("354scorestatus: " + ScoreStatus);

				if ( scoreStatusDiv != null ) {
					var nowDate = new Date();

					if (GameDateTime != ""){
						//alert(GameDateTime.length)
						nowDate.setFullYear( parseInt( GameDateTime.substring(0,4), 10 ), parseInt( GameDateTime.substring(5,7), 10 ) - 1, parseInt( GameDateTime.substring(8,10), 10 ) );
						nowDate.setHours( parseInt( GameDateTime.substring(11,13), 10 ), parseInt( GameDateTime.substring(14,16), 10 ) );


						if ( ScoreStatus.indexOf("Final") != -1 || ScoreStatus != "" ) {
							scoreStatusDiv.innerHTML = ScoreStatus;
							//scoreStatusDiv.innerHTML = "&nbsp;&nbsp;<font color='000000'>" + ScoreStatus + "</font>";
						} else {

							scoreStatusDiv.innerHTML = formatDate( nowDate , "HH:mm" ) +" BST";
						}
					}
				}
				//alert("allevents 367 " + AllEvents)
					//alert( parseInt(getDateDif( baseDate, startingDate ),10) +" " + parseInt(updateIndex,10) );
				if ( AllEvents.indexOf("|"+EventID+",") == -1 && parseInt(getDateDif( baseDate, startingDate ),10) >= parseInt(updateIndex,10) ) {
					AllEvents += ( "|"+EventID+","+location+"-0-"+events+","+GameDateTime.substring(0,10)+","+TeamOnTop+"|" );
					
					//alert("383 AllEvents: " + AllEvents);
					//alert("setting allevents")
				}
				//alert("whose round? " + round)
			}


			//round 2
			if ( refresh == null ) {

	 //function populateColumn( numEvents, thisRound, thisRoundNum, nextRound, location, division ) {
				//alert("here")
				populateColumn( 8, "secondRound", "1", "sweet16", location, null );
				populateColumn( 4, "sweet16", "2", "elite8", location, null );
				populateColumn( 4, "elite8", "3", null, location, null );

				//secondRoundfixture = [ "","","","","","","","" ];
				secondRoundAbbr = [ "","","","","","","","" ];
				secondRoundName = [ "","","","","","","","" ];
				secondRoundCode = [ "","","","","","","","" ];
				secondRoundPrevDate = [ "","","","","","","","" ];
				secondRoundRank = [ "","","","","","","","" ];
				secondRoundIndex = [ 0,0,0,0,0,0,0,0 ];
				secondRoundEvent_Key = [ "","","","","","","","" ];

				sweet16Abbr = [ "","","","" ];
				sweet16Name = [ "","","","" ];
				sweet16Code = [ "","","","" ];
				sweet16PrevDate = [ "","","","" ];
				sweet16Rank = [ "","","","" ];
				sweet16Index = [ 0,0,0,0 ];
				sweet16Event_Key = [ "","","","" ];

				elite8Abbr = [ "","","","" ];
				elite8Name = [ "","","","" ];
				elite8Code = [ "","","","" ];
				elite8PrevDate = [ "","","","" ];
				elite8Rank = [ "","","","" ];
				elite8Index = [ 0,0,0,0 ];
				elite8Event_Key = [ "","","","" ];
			}

		}

		if (round == 2){
//			alert("round 2");
		}
		//alert("roundww: " + round);

		//alert("about to call pop")
		//populateColumn( 4, "final4", "0", "championship", 4, null );
		//s populateColumn( 2, "championship", "0", null, 5, null );
		if ( refresh == null ) {

			if ( init == true ) {
				window.setTimeout("updateBracket();", 100 );
			}
		}
//alert(storage);
	}

	function setTeamData( round, events, rank, teamName, teamABR, teamCode, gameDateTime, division, index, eventId, coord, Event_Key ) {
		//alert("setTeamData");

//storage += (("round: " + round)+ "\r\n");

		if ( round != null ) {
			if ( division != null ) {
				events = division;
			}

			//if (round == "sweet16"){
//				alert("teamName: 447" + teamName)
			//}

			//populate the arrays!
			eval( round+"Abbr[ "+events+" ] = '"+teamABR+"';" );
			eval( round+"Name[ "+events+" ] = '"+replacestring(teamName, "'", "\\'", true )+"';" );
			eval( round+"Code[ "+events+" ] = '"+teamCode+"';" );
			eval( round+"PrevDate[ "+events+" ] = '"+gameDateTime+"';" );
			eval( round+"Rank[ "+events+" ] = '"+rank+"';" );
			eval( round+"Index[ "+events+" ] = "+index+";" );
			eval( round+"Event_Key [ "+events+" ] = "+Event_Key+";" );

		//alert("Event_Key: " + Event_Key);

		}
	}


	function populateColumn( numEvents, thisRound, thisRoundNum, nextRound, location, division ) {

		//alert("populateColumn: " + numEvents)
		//populateColumn( 8, "secondRound", "1", "sweet16", location, null ); //broke

		var VisitTeamAbbr;
		var VisitTeamName;
		var VisitTeamCode;
		var VisitPrevIndex;
		var EventID;
		var HomeScore;
		var VisitScore;
		var GameDateTime;
		var GameTime;
		var ScoreStatus;
		var Index;
		var Total2;
		var Spread2;
		var ViewDate;

		var thisR = null;

		for ( var events=0; events<numEvents; events++ ) {

			var round = Math.floor(events / 2);

			//pull the values out of the arrays
			eval( "var TeamAbbr = "+thisRound+"Abbr[ events ];" );
			eval( "var TeamName = "+thisRound+"Name[ events ];" );
			eval( "var TeamCode = "+thisRound+"Code[ events ];" );
			eval( "var PrevDate = "+thisRound+"PrevDate[ events ];" );
			eval( "var Rank = "+thisRound+"Rank[ events ];" );
			eval( "var PrevIndex = "+thisRound+"Index[ events ];" );
			eval( "var PrevIndex = "+thisRound+"Index[ events ];" );
			eval( "var Event_Key = "+thisRound+"Index[ events ];" );


			if ( events == round * 2 ) {

				visitEventDiv = document.getElementById("VisitEvent-"+location+"-"+thisRoundNum+"-"+round);
				fixtureDiv = document.getElementById("fixture-"+location+"-"+thisRoundNum+"-"+round);

				if ( visitEventDiv != null ) {

					visitEventDiv.innerHTML = ( TeamName == "" ? "" : "&#160;" ) + " " + TeamName;
					VisitTeamAbbr = TeamAbbr;
					VisitTeamName = TeamName;
					VisitTeamCode = TeamCode;
					VisitPrevIndex = PrevIndex;
					VisitRank = Rank;

					EventID = null;
					HomeScore = null;
					VisitScore = null;
					GameDateTime = null;
					GameTime = null;
					ScoreStatus = null;
					Index = null;
					Total2 = null;
					Spread2 = null;

					//alert("548 about to getScores: " + VisitTeamAbbr + " " + VisitPrevIndex);
					thisR = getScores( VisitTeamAbbr, VisitPrevIndex );

					var scoreStatusDiv = document.getElementById("ScoreStatus-"+location+"-"+thisRoundNum+"-"+round);

					//alert("550: " +thisR); //hack here should have values
					if ( thisR != null ) {

						var thisRoundArray = thisR.split("|"); // EventID+"|"+HomeScore+"|"+VisitScore+"|"+thisViewDate+"|"+GameTime+"|"+ScoreStatus;

						EventID = thisRoundArray[0];
						VisitScore = ( thisRoundArray[1] == "" ? "0" : thisRoundArray[1] );
						HomeScore = ( thisRoundArray[2] == "" ? "0" : thisRoundArray[2] );
						GameDateTime = thisRoundArray[3];
						GameTime = thisRoundArray[4];
						ScoreStatus = thisRoundArray[5];
						Index = thisRoundArray[6];
						Total2 = thisRoundArray[7];
						Spread2 = thisRoundArray[8];
						TeamOnTop = thisRoundArray[9];
						Event_Key = thisRoundArray[10]




						if (Event_Key != ""){
							if ( fixtureDiv != null ) {
								var strFixture = fixtureDiv.innerHTML;
								//alert("setting fixture " + Event_Key);
								fixtureDiv.innerHTML = "<a href='http:/pageLoader/pageLoader.aspx?page=/data/worldcup/matchups/g1_summary_"+Event_Key+".html'>"+strFixture+"</a>";
							}
						}

						ViewDate = GameDateTime.substring(6,10) + "-" + GameDateTime.substring(3,5) + "-" + GameDateTime.substring(0,2);

						if ( TeamName == "" ) {
							visitEventDiv.innerHTML = "";
						} else if ( EventID == null ) {
							visitEventDiv.innerHTML = ( TeamName == "" ? "" : "&#160;" ) + " " + TeamName;
						} else {
							visitEventDiv.innerHTML = ( TeamName == "" ? "" : "&#160;" ) + " <a href='http://www.covers.co.uk/pageloader/pageloader.aspx?page=/data/worldcup/teams/team"+TeamCode+".html'>"+TeamName+"</a>";
						}

						if ( scoreStatusDiv != null ) {
							var nowDate = new Date();
							nowDate.setFullYear( parseInt( GameDateTime.substring(6,10), 10 ), parseInt( GameDateTime.substring(3,5), 10 ) - 1, parseInt( GameDateTime.substring(0,2), 10 ) );
							nowDate.setHours( parseInt( GameTime.substring(0,2), 10 ), parseInt( GameTime.substring(3,5), 10 ) );

							if ( ScoreStatus.indexOf("Final") != -1 || ScoreStatus != "" ) {
								scoreStatusDiv.innerHTML = ScoreStatus;
							} else {
								scoreStatusDiv.innerHTML = formatDate( nowDate , "HH:mm" ) +" BST";
							}
						}

					//thisR is null!
					} else {
						if ( scoreStatusDiv != null ) {
							//scoreStatusDiv.innerHTML = "<font color='#FFFFFF'>TBA</font>";
							//visitEventDiv.innerHTML = ( TeamName == "" ? "" : "&#160;("+Rank+")" ) + " " + TeamName;
							visitEventDiv.innerHTML = ( TeamName == "" ? "" : "&#160;" ) + " " + TeamName;
						
						}
					}
				}
			//if ( events == round * 2 ) {
			} else {
				homeEventDiv = document.getElementById("HomeEvent-"+location+"-"+thisRoundNum+"-"+round);
				//alert(thisR);
				if ( thisR != null ) {
					if ( homeEventDiv != null ) {
					//	alert(thisR + " " + TeamName);
						if ( TeamName == "" || thisR == null ) {
							homeEventDiv.innerHTML = "";
						} else if ( EventID == null || thisR == null ) {
							homeEventDiv.innerHTML = ( TeamName == "" ? "" : "&#160;" ) + " " + TeamName;
						} else {
							homeEventDiv.innerHTML = ( TeamName == "" ? "" : "&#160;" ) + " <a href='http://www.covers.co.uk/pageloader/pageloader.aspx?page=/data/worldcup/teams/team"+TeamCode+".html'>"+TeamName+"</a>";
						}
					}

					visitScoreDiv = document.getElementById("VisitScore-"+location+"-"+thisRoundNum+"-"+round);
					homeScoreDiv = document.getElementById("HomeScore-"+location+"-"+thisRoundNum+"-"+round);
					if (  visitScoreDiv != null && homeScoreDiv != null && thisR != null ) {
						//alert(ScoreStatus);
						if ( ScoreStatus != "" ) {

							if ( ScoreStatus.indexOf("Final") != -1	&& ScoreStatus != "" ) {
								if ( parseInt( VisitScore ) > parseInt( HomeScore )  ) {
									setTeamData( nextRound, round, Rank, TeamName, TeamAbbr, TeamCode, GameDateTime, division, Index, EventID, location+"-"+thisRoundNum+"-"+round,Event_Key );
									if ( thisRound == "sweet16" ) {
										setTeamData( nextRound, round + 2, VisitRank, VisitTeamName, VisitTeamAbbr, VisitTeamCode, GameDateTime, division, Index, EventID, location+"-"+thisRoundNum+"-"+round,Event_Key );
									}
								} else {

									setTeamData( nextRound, round, VisitRank, VisitTeamName, VisitTeamAbbr, VisitTeamCode, GameDateTime, division, Index, EventID, location+"-"+thisRoundNum+"-"+round,Event_Key );
									if ( thisRound == "sweet16" ) {
										setTeamData( nextRound, round + 2, Rank, TeamName, TeamAbbr, TeamCode, GameDateTime, division, Index, EventID, location+"-"+thisRoundNum+"-"+round,Event_Key );
									}
								}
							}
							//visitScoreDiv.innerHTML = "&nbsp;&nbsp;&nbsp;&nbsp;<a href='javascript:void(0);' onClick='addScoreBox( event, "+EventID+", \""+ViewDate+"\" );'>"+HomeScore+"</a>";
							//homeScoreDiv.innerHTML = "&nbsp;&nbsp;&nbsp;&nbsp;<a href='javascript:void(0);' onClick='addScoreBox( event, "+EventID+", \""+ViewDate+"\" );'>"+VisitScore+"</a>";
							visitScoreDiv.innerHTML = HomeScore;
							homeScoreDiv.innerHTML = VisitScore;

						} else {
							visitScoreDiv.innerHTML ="&nbsp;0"; //&nbsp;&nbsp;<a href='/sports/common/lineHistory.aspx?eventId="+EventID+"&sport=ncb'>"+(( TeamAbbr != TeamOnTop )?Spread2:Total2)+"</a>";
							homeScoreDiv.innerHTML = "&nbsp;0"; //&nbsp;&nbsp;<a href='/sports/common/lineHistory.aspx?eventId="+EventID+"&sport=ncb'>"+(( TeamAbbr != TeamOnTop )?Total2:Spread2)+"</a>";
						}
					}

					if ( thisR != null ) {
						if ( AllEvents.indexOf("|"+EventID+",") == -1 && ScoreStatus.indexOf("Final") == -1	 ) { // parseInt(Index,10) >= parseInt(updateIndex,10)
						
							//alert("653 allevents " + EventID);
							AllEvents += ( "|"+EventID+","+location+"-"+thisRoundNum+"-"+round+","+ViewDate+","+TeamOnTop+"|" );
						}
					}
					thisR = null;
				} else {
					//homeEventDiv.innerHTML = ( TeamName == "" ? "" : "&#160;("+Rank+")" ) + " " + TeamName;
					homeEventDiv.innerHTML = ( TeamName == "" ? "" : "&#160;" ) + " " + TeamName;
					//scoreStatusDiv.innerHTML = "<font color='#FFFFFF'>TBA2</font>";
					thisR = null;
				}
			}
		}
	}

	function cacheScores( gameDate, init ) {

	//alert("cacheScores: " + cacheScores);
		//alert(tDateString); yyyymmdd
		var nextDate = new Date();
		var numTimesToLook = 0;
		nextDate.setFullYear( parseInt( gameDate.substring(0,4), 10 ), parseInt( gameDate.substring(5,7), 10 ) - 1, parseInt( gameDate.substring(8,10), 10 ) );
		//alert(cacheCount);
		for ( var t=0; t<cacheCount; t++ ) {
			with (nextDate) setDate(getDate()+1); //hack good!
			//with (nextDate) setDate(getDate()); //hack remove
			thisViewDate = nextDate.getFullYear() + "" + ( (nextDate.getMonth()+1) < 10 ? "0"+ (nextDate.getMonth()+1) : nextDate.getMonth()+1 ) + "" + (nextDate.getDate() < 10 ? "0" + nextDate.getDate() : nextDate.getDate() );

			//alert(thisViewDate + " " + tDateString);
			if ( ( thisViewDate >= tDateString && numTimesToLook < 3 ) || init == true ) {
				
				//alert( "690: /sports-scores/data/"+League+"ScoresAndMatchup/Xml/"+thisViewDate.substring(0,4) + "/" + thisViewDate.substring(4,8)+"/"+League+"ScoresAndMatchupsAllIds_"+thisViewDate.substring(4,8)+".xml");
				//alert("689: " + thisViewDate);
				cache[t] = cInclude( null, "/sports-scores/data/"+League+"ScoresAndMatchup/Xml/"+thisViewDate.substring(0,4) + "/" + thisViewDate.substring(4,8)+"/"+League+"ScoresAndMatchupsAllIds_"+thisViewDate.substring(4,8)+".xml");
				//cache[t] = cInclude( null, "/sports-scores/data/NCAABScoresAndMatchup/Xml/"+thisViewDate.substring(0,4) + "/" + thisViewDate.substring(4,8)+"/NCAABScoresAndMatchupsAllIds_"+thisViewDate.substring(4,8)+".xml");
				///alert("670: " + cache[t] );
				
				
				if ( cache[t].indexOf("no games") == -1 && cache[t].indexOf("cannot access") == -1 ) {
					numTimesToLook++;
					//alert(t);
					//alert("thisViewDate: " + thisViewDate);
				}
			}
		}
	}

	function getScores( teamCode, Index ) {

		//alert("814getScores" + teamCode + " " + Index);
//		try{
		for ( var t=Index; t<cacheCount; t++ ) {
			var contents = cache[t];

			 //alert(cache[t]);

			if ( contents.indexOf( "<br>" ) != -1 && contents.indexOf( "<EventID>" ) != -1 ) {

				var events = contents.split("<br>");
				for ( var eventArray=0; eventArray<events.length-1; eventArray++ ) {
				//alert(events[eventArray]);
					var EventID = getFieldContents( "EventID", events[eventArray] );
					var HomeTeamABR = getFieldContents( "HomeTeamABR", events[eventArray] );
					var VisitTeamABR = getFieldContents( "VisitTeamABR", events[eventArray] );
					var ScoreStatus = getFieldContents( "ScoreStatus", events[eventArray] );

					if ( ( HomeTeamABR == teamCode || VisitTeamABR == teamCode ) ) {

						var TeamOnTop = "";
						if ( VisitTeamABR == teamCode ) {
							var HomeScore = getFieldContents( "HomeScore", events[eventArray] );
							var VisitScore = getFieldContents( "VisitScore", events[eventArray] );
							TeamOnTop = VisitTeamABR;
						} else if ( HomeTeamABR == teamCode ) {
							var HomeScore = getFieldContents( "VisitScore", events[eventArray] );
							var VisitScore = getFieldContents( "HomeScore", events[eventArray] );
							TeamOnTop = HomeTeamABR;
						}
						var GameTime = getFieldContents( "GameTime", events[eventArray] );
						var GameDateTime = getFieldContents( "GameDateTime", events[eventArray] );
						var ScoreStatus = getFieldContents( "ScoreStatus", events[eventArray] );
						var Total2 = getFieldContents( "Total2", events[eventArray] );
						var Spread2 = getFieldContents( "Spread2", events[eventArray] );

						var Event_Key = getFieldContents( "Event_Key", events[eventArray] );

						//alert("Event_Key in getscores: " + Event_Key);
						return EventID+"|"+HomeScore+"|"+VisitScore+"|"+GameDateTime+"|"+GameTime+"|"+ScoreStatus+"|"+(t+1)+"|"+Total2+"|"+Spread2+"|"+TeamOnTop+"|"+Event_Key;
					}
				} //for ( var eventArray=0; eventArray<events.length-1; eventArray++ ) {
			}
		}
//		}catch( err ) {
//		}

		return null;
	}





	var dragobj = null
	endDragStart = false;
	var elex = 0;
	var eley = 0;
	var grabx = 0;
	var graby = 0;
	var orix = 0;
	var oriy = 0;


	function getRandom( thisLeague ) {
		var currentTime = new Date();
		var randomnumber = thisLeague +":"+ currentTime.getDay() +":"+ currentTime.getMonth() +":"+ currentTime.getFullYear() +":"+ currentTime.getHours() +":"+ currentTime.getMinutes() +":"+ currentTime.getSeconds();
		return randomnumber
	}


	function getFieldContents( field, xml ) {
		if ( xml.indexOf( "<"+field+">" ) != -1 ) {
			return xml.substring( xml.indexOf( "<"+field+">" ) + ( "<"+field+">" ).length, xml.indexOf( "</"+field+">" ) );
		} else {
			return "";
		}
	}

	function cInclude(id, url) {

	//alert(url)
	var req = false;
	// For Safari, Firefox, and other non-MS browsers
	if (window.XMLHttpRequest) {
		try {
		req = new XMLHttpRequest();
		} catch (e) {
		req = false;
		}
	} else if (window.ActiveXObject) {
		// For Internet Explorer on Windows
		try {
		req = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
		try {
			req = new ActiveXObject("Microsoft.XMLHTTP");
		} catch (e) {
			req = false;
		}
		}
	}


	var element = document.getElementById(id);

	if (req) {
		// Synchronous request, wait till we have it all
		var randomnumber = Math.floor(Math.random()*1000001);
		req.open('GET', url + '?' + randomnumber, false);
		req.send(null);
		if ( req.responseText.indexOf('Error 404') == -1 ) {
			if ( element == null ) {
				return req.responseText;
			}
			element.innerHTML = req.responseText;
		} else {
			if ( element == null ) {
				return 'There were no games scheduled or played this month.';
			}
			element.innerHTML = 'There were no games scheduled or played this month.';
		}

	} else {
		element.innerHTML =
	"Sorry, your browser does not support " +
		"XMLHTTPRequest objects. This page requires " +
		"Internet Explorer 5 or better for Windows, " +
		"or Firefox for any system, or Safari. Other " +
		"compatible browsers may also exist.";
	}
	}

	function replacestring(str_normal,str_find,str_replace,int_case_insensitive)
	{
		if (arguments.length<3 || str_find=="" || str_normal=="" || typeof("".split)!="function")
			return(str_normal);

		//no parm means default, "case SENSITIVE"...
		if(!(int_case_insensitive))
			return(str_normal.split(str_find)).join(str_replace);

		str_find=str_find.toLowerCase();

		var rv="";
		var ix=str_normal.toLowerCase().indexOf(str_find);
		while(ix>-1)
		{
			rv+=str_normal.substring(0,ix)+str_replace;
			str_normal=str_normal.substring(ix+str_find.length);
			ix=str_normal.toLowerCase().indexOf(str_find);
		}
		return(rv+str_normal);
	}

	function getCurrentSeason( sport ) {
		var a = cInclude( null, "/sports-scores/data/"+sport+"ScoresAndMatchup/CurrentSeason.html");
		if ( a.indexOf("The page cannot be found") == -1 ) {
			return a;
		} else {
			alert("season not found");
			return "2005-2006";
		}
	}

	var MONTH_NAMES = new Array('January','February','March','April','May','June','July','August','September','October','November','December','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
	var DAY_NAMES=new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sun','Mon','Tue','Wed','Thu','Fri','Sat');
	function LZ(x) {return(x<0||x>9?"":"0")+x}

	function formatDate(date,format) {

		format=format+"";
		var result="";
		var i_format=0;
		var c="";
		var token="";
		var y=date.getYear()+"";
		var M=date.getMonth()+1;
		var d=date.getDate();
		var E=date.getDay();
		var H=date.getHours();
		var m=date.getMinutes();
		var s=date.getSeconds();
		var yyyy,yy,MMM,MM,dd,hh,h,mm,ss,ampm,HH,H,KK,K,kk,k;
		// Convert real date parts into formatted versions
		var value=new Object();
		if (y.length < 4) {y=""+(y-0+1900);}
		value["y"]=""+y;
		value["yyyy"]=y;
		value["yy"]=y.substring(2,4);
		value["M"]=M;
		value["MM"]=LZ(M);
		value["MMM"]=MONTH_NAMES[M-1];
		value["NNN"]=MONTH_NAMES[M+11];
		value["d"]=d;
		value["dd"]=LZ(d);
		value["E"]=DAY_NAMES[E+7];
		value["EE"]=DAY_NAMES[E];
		value["H"]=H;
		value["HH"]=LZ(H);
		if (H==0){value["h"]=12;}
		else if (H>12){value["h"]=H-12;}
		else {value["h"]=H;}
		value["hh"]=LZ(value["h"]);
		if (H>11){value["K"]=H-12;} else {value["K"]=H;}
		value["k"]=H+1;
		value["KK"]=LZ(value["K"]);
		value["kk"]=LZ(value["k"]);
		if (H > 11) { value["a"]="pm"; }
		else { value["a"]="am"; }
		value["m"]=m;
		value["mm"]=LZ(m);
		value["s"]=s;
		value["ss"]=LZ(s);
		while (i_format < format.length) {
			c=format.charAt(i_format);
			token="";
			while ((format.charAt(i_format)==c) && (i_format < format.length)) {
				token += format.charAt(i_format++);
				}
			if (value[token] != null) { result=result + value[token]; }
			else { result=result + token; }
			}
		return result;
		}
