var tabCreationIndex = null;
var tabRow = null;

var activeDiv = null;
var activeLeague = null;
var previousSelected = null;

var confTable = null;
var confLineBetweenDates = null;
var confRowPrefix = null;
var confGameDay = null;
var confRealRed = null;
var lastDate = null;

var rowColor = null;

function cleanContainer( container)
{
	var startIndex = 0;
	if ( container.childNodes.length && container.childNodes[0].id == "tabTableId" )
	{
		startIndex = 1;
	}

  while ( container.childNodes.length > startIndex )
  {
    container.removeChild( container.childNodes[ startIndex]); 
  } 		
  
 
  if ( startIndex == 0 )
  {
  	//get league info and draw menus
	  drawGameMenus( activeLeague, activeDiv);
  }

	updateTabHeader();
}

function drawGameMenus( league, div)
{
  var container = document.getElementById("contentDiv");;
  container.innerHTML = "<table id=\"tabTableId\" cellspacing=\"0\"></table>";

  var table = document.getElementById("tabTableId");
  table.className = "tabTable";
  tabRow = table.insertRow(0);

  tabCreationIndex = 0;
  createTab("Pelejä", "gameResultsTab", "tabClicked");
  createTab("Sarjataulukko", "standingsTab", "tabClicked");
  createTab("Pistepörssi", "invStatTab", "tabClicked");
  createTab("Otteluohjelma", "gamesTab", "tabClicked");

  cell = tabRow.insertCell( tabCreationIndex);

//  var table = document.createElement("table");  
  row = table.insertRow(1);
  cell = row.insertCell(0);
  cell.id = "gameTabHeaderCellId";
  cell.colSpan = "5";
  cell.className = "tabMenuBase fDefault";


  
  //container.appendChild( table);
}

function updateTabHeader()
{
	var header = document.getElementById("gameTabHeaderCellId");
	
	if ( header)
	{
	  var str = getLeagueName( activeLeague);
  	var divname = getDivName( activeDiv);

	  if ( divname.length )
  	{
	    str += ", " + divname;
  	}
  
		header.innerHTML = str;	
	}
}

function createTab( str, id, tabClickedFunc  )
{
  var cell = tabRow.insertCell( tabCreationIndex++);
  cell.className = "fDefault tabMenu";
  cell.id = id;
  cell.innerHTML = "<a class=\"blBlack\" onclick=\"" + tabClickedFunc + "(event);\">" + str + "</a>";
}

function setTabActive( tabName)
{
	var tab = document.getElementById(tabName);
	
  if ( previousSelected)
  {
  	previousSelected.style.backgroundImage = "url(common/pics/tabmenu.jpg)";
  }

  tab.style.backgroundImage = "url(common/pics/tabmenuselected.jpg)";
  previousSelected = tab;
}

function tabClicked( e)
{
	var target = getTargetFromEvent( e);	
  
	if ( target.parentNode.id == "gamesTab")
	{
		goToMenuP( "games", activeLeague, activeDiv, null);
	} 
	
	if ( target.parentNode.id == "gameResultsTab")
	{
		goToMenuP( "results", activeLeague, activeDiv, null);
	}
	
	if ( target.parentNode.id == "standingsTab")
	{
		goToMenuP( "league", activeLeague, activeDiv, null);
	}
	
	if ( target.parentNode.id == "invStatTab")
	{
		goToMenuP( "invStatTab", activeLeague, activeDiv, null);
	}
}

function games( league, div)
{
	activeLeague = div;
	activeDiv = league;
	
  var container = document.getElementById("contentDiv");
	cleanContainer( container);
	setTabActive("gamesTab");

  params = "rid=getGames";
  params += "&order=asc";	
  params += "&league=" + activeLeague;
  params += "&div=" + activeDiv;

  xmlHttpRequest( "common/server/games.php", params, 0);
  var xml = xmlParser( xmlHttp.responseText);  
	//alert( xmlHttp.responseText);

	//create table
	var table = document.createElement("table");
	table.style.marginTop = "10px";
	gameTableConf( table, 1, true);
	
	var games = xml.getElementsByTagName("game");
	var rowIndex = 0;
	
	for ( var i = 0; i < games.length; i++)
	{
		addGameToTable( games[i]);
	}
		
	container.appendChild( table);
}

function gameResults( league, div)
{
	activeLeague = div;
	activeDiv = league;

  var container = document.getElementById("contentDiv");
	cleanContainer( container);
	setTabActive("gameResultsTab");

  var now = new Date();
  now = phpTime( now);

  params = "rid=getGames";
  params += "&order=desc";	
  params += "&league=" + activeLeague;
  params += "&type=r";

  xmlHttpRequest( "common/server/games.php", params, 0);
  var xml = xmlParser( xmlHttp.responseText);  

	//create header table
	var table = document.createElement("table");
	table.className = "gamesSubHeaderTable";
	table.style.marginTop = "10px";
	var row = table.insertRow(0);
	var cell = row.insertCell(0);
	cell.id = "lastResultHeaderCellId";
	cell.className = "gamesSubHeaderCell fDefault";
	cell.innerHTML = "Viimeiset";
	container.appendChild( table);	

	//create result table
	var table = document.createElement("table");
	table.style.marginTop = "10px";
	gameTableConf( table, 1, true);
	gameRowPrefix( "rRow");
	
	var games = xml.getElementsByTagName("game");
	
	for ( var i = 0; i < games.length; i++)
	{
		addGameToTable( games[i]);
	}

	container.appendChild( table);

	//create header table
	var table = document.createElement("table");
	table.className = "gamesSubHeaderTable";
	table.style.marginTop = "10px";
	var row = table.insertRow(0);
	var cell = row.insertCell(0);
	cell.id = "lastGamesHeaderCellId";
	cell.className = "gamesSubHeaderCell fDefault";
	cell.innerHTML = "Tulevat";
	container.appendChild( table);	


	//create game table
	var table = document.createElement("table");
	table.style.marginTop = "10px";
	gameTableConf( table, 1, true);
	gameRowPrefix( "nrRow");

  params = "rid=getGames";
  params += "&order=asc";	
  params += "&league=" + activeLeague;
  params += "&type=nr";


  xmlHttpRequest( "common/server/games.php", params, 0);
  var xml = xmlParser( xmlHttp.responseText);  

	//create table
	var games = xml.getElementsByTagName("game");
	
	for ( var i = 0; i < games.length; i++)
	{
		addGameToTable( games[i]);
	}
		

	params += "&nextGameDays=2";
		
	container.appendChild( table);

//	visibleResultDays( 2);
//	visibleGameDays( 2);
}

function visibleResultDays( days)
{
	var index = 0;
	

	do 
	{
		trace( rows.length);
		
		if ( index <= day )
		{
			for ( var i = 0; i < rows.length; i++)
			{
				rows[i].style.visibility = "visible";
			}
		} else
		{
			for ( var i = 0; i < rows.length; i++)
			{
				rows[i].style.visibility = "hidden";
			}
		}
		
		index++;
	} while ( rows.length);	
}

function visibleGameDays( days)
{
	var table = document.getElementById("nrTable");
	var row = document.getElementById("nrRow" + days);

	for ( var i = 0; i < table.rows.length; i++)
	{
		if ( i < row.rowIndex )
		{
			table.rows[i].style.visibility = "visible";			
		} else
		{
			table.rows[i].style.visibility = "collapse";
		}
	}
}


function addGameToTable( game)
{
   var row = confTable.insertRow( rowIndex++);
      
   if ( lastDate == null)
   {
   		row.id = confRowPrefix + confGameDay;
   }   
      
   //date
   var timestamp = parseInt( game.attributes.getNamedItem("date").nodeValue) * 1000;      
   var time = new Date( timestamp);
   
   var t1 = game.attributes.getNamedItem("team1").nodeValue;
   var t2 = game.attributes.getNamedItem("team2").nodeValue;
   
   var realMatch = false;
   if ( (t1 == "real" || t2 == "real") && confRealRed)
   {
   	realMatch = true;
   }

     
   var newDate = !confLineBetweenDates || lastDate == null || lastDate.getDate() != time.getDate() || lastDate.getMonth() != time.getMonth();
     
   if ( confLineBetweenDates && newDate && lastDate != null)
   {
   	 var extraCell = row.insertCell(0);
   	 row.style.height = "10px";
   	 extraCell.colSpan = "5";
   	 row = confTable.insertRow( rowIndex++);	
	   row.id = confRowPrefix + confGameDay;
	   counter = 0;
   	 confGameDay++;
   } 
   row.className = "gameRowClass";
      
   //create time cell
   var cell = row.insertCell(0);
   cell.className = "gameCellClass fDefault";
   if ( rowColor ) cell.style.color = rowColor;
   	
   cell.style.width = "20%";
     
   if ( newDate )
   {
		 cell.innerHTML = makeDate( time, 0); 
		 lastDate = time;
	 }
      
   //create teams cell
   var cell = row.insertCell(1);
   cell.className = "gameCellClass fDefault";
   cell.style.width = "auto";
   
   if ( realMatch) cell.style.color = "#FF9900";
   if ( rowColor ) cell.style.color = rowColor;
   
   cell.innerHTML = game.attributes.getNamedItem("t1n").nodeValue + " - " + game.attributes.getNamedItem("t2n").nodeValue;
      
   //create result cell
   var cell = row.insertCell(2);
   cell.className = "gameCellClass fDefault";
   if ( realMatch) cell.style.color = "#FF9900";
   if ( rowColor ) cell.style.color = rowColor;
   cell.style.width = "5%";
   var s1 = parseInt( game.attributes.getNamedItem("s1").nodeValue);
   if ( s1 >= 0 )
   {
     var s2 = parseInt( game.attributes.getNamedItem("s2").nodeValue);
     cell.innerHTML = s1 + "-" + s2;        
   } else
   {
     cell.innerHTML = "x-x";
   }  


   //create info cell
   var cell = row.insertCell(3);
   cell.className = "gameCellClass fDefault";
   cell.style.width = "auto";
   if ( realMatch) cell.style.color = "#FF9900";
   if ( rowColor ) cell.style.color = rowColor;
   var infostr = game.attributes.getNamedItem("info").nodeValue;
     
   var hours = time.getHours();
   
   if ( infostr.length > 1 && hours != 0) infostr += ", ";
   
	 if ( hours != 0)
	 {
	   infostr += "klo " + hours;
  	 if ( time.getMinutes() != 0)
	   {
  	 		 infostr += ":" + time.getMinutes();
	   } 
     
  	 cell.innerHTML = infostr;
   }

     
   //create report cell
   var reportStr = "Raportti";
   var now = new Date();
     
   if ( (time.getTime() + 60*60*1000  )  > now.getTime())
   {
   	reportStr = "Ennakko";
   }
     
   var cell = row.insertCell( 4);
   cell.className = "gameCellClass fDefault";
   cell.style.width = "7%";
   if ( realMatch) cell.style.color = "#FF9900";
   if ( rowColor ) cell.style.color = rowColor;
   var gameid = game.attributes.getNamedItem("id").nodeValue;
   cell.innerHTML = "<a class=\"blBlack\" onclick=\"goToMenu('report#" + gameid +"')\">"+ reportStr +"</a>";

}

function gameTableConf( table, lineBetweenDates, realRed)
{
	confTable = table;
	confLineBetweenDates = lineBetweenDates;
	lastDate = null;
	rowIndex = 0;
	confRealRed = realRed;
}

function gameRowColor( textColor)
{
	rowColor = textColor;
}

function gameRowPrefix( rowPrefix)
{
	confRowPrefix = rowPrefix;
	confGameDay = 0;
}

function leagueStandings( league, div)
{
	activeLeague = league;
	activeDiv = div;

  var container = document.getElementById("contentDiv");
	cleanContainer( container);
	setTabActive( "standingsTab");	

  params = "rid=getStanding";
  params += "&league=" + activeLeague;
  params += "&div=" + activeDiv;

  xmlHttpRequest( "common/server/leagues.php", params, 0);
	//alert(  xmlHttp.responseText);  
  var xml = xmlParser( xmlHttp.responseText);  
	

	//create table
	var table = document.createElement("table");
	table.style.marginTop = "10px";
	table.className = "standTable";
	standingTableConf( table, 1);
	createStandingHeader();
	
	var teams = xml.getElementsByTagName("teamdata");
	var rowIndex = 0;
	for ( var i = 0; i < teams.length; i++)
	{
		addTeamToStandingTable( teams[i]);
	}
		
	container.appendChild( table);	
}

function standingTableConf( table)
{
	confTable = table;
	rowIndex = 0;
}

function createStandingHeader()
{
  var row = confTable.insertRow( rowIndex++);
      
  //team name
  row.className = "standRowClass";
      
  var cell = row.insertCell(0);
  cell.className = "standHeaderCellClass fDefault";
  cell.style.textAlign = "Left";
  cell.style.width = "30%";
     
  //create game count cell
  var cell = row.insertCell(1);
  cell.className = "standHeaderCellClass fDefault";
  cell.style.width = "10%";
  cell.innerHTML = "Pelit";

  //create wins cell
  var cell = row.insertCell(2);
  cell.className = "standHeaderCellClass fDefault";
  cell.style.width = "10%";
  cell.innerHTML = "Voitot";

  //create draws cell
  var cell = row.insertCell(3);
  cell.className = "standHeaderCellClass fDefault";
  cell.style.width = "10%";
  cell.innerHTML = "Tasapelit";

  //create loses cell
  var cell = row.insertCell(4);
  cell.className = "standHeaderCellClass fDefault";
  cell.style.width = "10%";
  cell.innerHTML = "Häviöt";

  //create goals cell
  var cell = row.insertCell(5);
  cell.className = "standHeaderCellClass fDefault";
  cell.style.width = "10%";
  cell.innerHTML = "Maalit";

  //create goalsa cell
  var cell = row.insertCell(6);
  cell.className = "standHeaderCellClass fDefault";
  cell.style.width = "10%";
  cell.innerHTML = "Päästetyt";

  //create plusminus
  var cell = row.insertCell(7);
  cell.className = "standHeaderCellClass fDefault";
  cell.style.width = "10%";
  cell.innerHTML = "+/-";

  //create points
  var cell = row.insertCell(8);
  cell.className = "standHeaderCellClass fDefault";
  cell.style.width = "auto";
  cell.innerHTML = "Pisteet";	
}

function addTeamToStandingTable( team )
{
  var row = confTable.insertRow( rowIndex++);
      
  //team name
  row.className = "standRowClass";
      
  var cell = row.insertCell(0);
  cell.className = "standCellClass fDefault";
  cell.style.textAlign = "Left";
  cell.innerHTML = team.attributes.getNamedItem("teamname").nodeValue;  
     
  //create game count cell
  var cell = row.insertCell(1);
  cell.className = "standCellClass fDefault";
  
  var games = parseInt(team.attributes.getNamedItem("games").nodeValue);
  var gnr = parseInt(team.attributes.getNamedItem("gamesnoresult").nodeValue);
  
//  if ( gnr == 0 )
  {
  	cell.innerHTML = games;
  }// else
  {
//  	cell.innerHTML = games + "(" + gnr + ")";
	}

  //create wins cell
  var cell = row.insertCell(2);
  cell.className = "standCellClass fDefault";
  cell.innerHTML = team.attributes.getNamedItem("wins").nodeValue;

  //create draws cell
  var cell = row.insertCell(3);
  cell.className = "standCellClass fDefault";
  cell.innerHTML = team.attributes.getNamedItem("draws").nodeValue;

  //create loses cell
  var cell = row.insertCell(4);
  cell.className = "standCellClass fDefault";
  cell.innerHTML = team.attributes.getNamedItem("loses").nodeValue;

  //create goals cell
  var cell = row.insertCell(5);
  cell.className = "standCellClass fDefault";
  cell.innerHTML = team.attributes.getNamedItem("goals").nodeValue;

  //create goalsa cell
  var cell = row.insertCell(6);
  cell.className = "standCellClass fDefault";
  cell.innerHTML = team.attributes.getNamedItem("goalsa").nodeValue;

  //create plusminus cell
  var cell = row.insertCell(7);
  cell.className = "standCellClass fDefault";
  cell.innerHTML = team.attributes.getNamedItem("plusminus").nodeValue;

  //create points cell
  var cell = row.insertCell(8);
  cell.className = "standCellClass fDefault";
  cell.innerHTML = team.attributes.getNamedItem("points").nodeValue;

}

function invStat( league, div)
{
	activeDiv = div;
	activeLeague = league;
	
  var container = document.getElementById("contentDiv");
	cleanContainer( container);
	setTabActive("invStatTab");


  var now = new Date();
  now = phpTime( now);

  params = "rid=getInvStanding";
  params += "&order=asc";	
  params += "&league=" + activeLeague;
  params += "&div=" + activeDiv;

  xmlHttpRequest( "common/server/leagues.php", params, 0);
  var xml = xmlParser( xmlHttp.responseText);  

	//create table
	var table = document.createElement("table");
	table.style.marginTop = "10px";
	table.className = "standTable";
	
	invStandingTableConf( table, 1);
	createInvStandingHeader();
	
	var player = xml.getElementsByTagName("invdata");
	var rowIndex = 0;
	for ( var i = 0; i < player.length; i++)
	{
		addPlayerToStandingTable( player[i]);
	}
		
	container.appendChild( table);	
}

function createInvStandingHeader()
{
	var row = confTable.insertRow( rowIndex++);
      
  //inv name
  row.className = "standRowClass";
      
  var cell = row.insertCell(0);
  cell.className = "standCellClass fDefault";
  cell.style.textAlign = "Left";
  cell.innerHTML = "";  
  cell.style.width = "40%";
     
  //create game count cell
  var cell = row.insertCell(1);
  cell.className = "standCellClass fDefault";
  cell.style.width = "12%";
  cell.innerHTML = "Pelit";
  
  //create goals cell
  var cell = row.insertCell(2);
  cell.className = "standCellClass fDefault";
  cell.innerHTML = "Maalit";
  cell.style.width = "12%";

  //create assits cell
  var cell = row.insertCell(3);
  cell.className = "standCellClass fDefault";
  cell.innerHTML = "Syötöt";
  cell.style.width = "12%";

	 //create penalties cell
  var cell = row.insertCell(4);
  cell.className = "standCellClass fDefault";
  cell.innerHTML = "Jäähyt";
  cell.style.width = "12%";
 
  //create total cell
  var cell = row.insertCell(5);
  cell.className = "standCellClass fDefault";
  cell.innerHTML = "Pisteet";
  cell.style.width = "12%";

}

function addPlayerToStandingTable( invData)
{
  var row = confTable.insertRow( rowIndex++);
      
  //inv name
  row.className = "standRowClass";
      
  var cell = row.insertCell(0);
  cell.className = "standCellClass fDefault";
  cell.style.textAlign = "Left";
  
  player = invData.attributes.getNamedItem("name").nodeValue;  
  pid = invData.attributes.getNamedItem("id").nodeValue;  
  cell.innerHTML = "<a class=\"blBlack\" onclick=\"goToMenu('players#" + pid +"')\">"+ player +"</a>";  
     
  //create game count cell
  var cell = row.insertCell(1);
  cell.className = "standCellClass fDefault";
  
  var games = parseInt(invData.attributes.getNamedItem("games").nodeValue);
 	cell.innerHTML = games;

  //create goals cell
  var cell = row.insertCell(2);
  cell.className = "standCellClass fDefault";
  cell.innerHTML = invData.attributes.getNamedItem("goals").nodeValue;

  //create assits cell
  var cell = row.insertCell(3);
  cell.className = "standCellClass fDefault";
  cell.innerHTML = invData.attributes.getNamedItem("assits").nodeValue;

  //create penalties cell
  var cell = row.insertCell(4);
  cell.className = "standCellClass fDefault";
  cell.innerHTML = invData.attributes.getNamedItem("penalty").nodeValue;

  //create total cell
  var cell = row.insertCell(5);
  cell.className = "standCellClass fDefault";
  cell.innerHTML = invData.attributes.getNamedItem("total").nodeValue;


}

function invStandingTableConf( table)
{
	confTable = table;
	rowIndex = 0;
}
