
var activeGameId = null;
var activeTime = null;
var activeT1 = null;
var activeT2 = null;
var activeN1 = null;
var activeN2 = null;
var playersInGame = null;

var ageSumH = 0;
var ageSumV = 0;
var ageCountH = 0;
var ageCountV = 0;

var stars = new Array( null, null, null);
var voteTime = null;

var previousSelectedReportTab = null;

function setReportTabActive( tab)
{
  if ( previousSelectedReportTab)
  {
  	previousSelectedReportTab.style.backgroundImage = "url(common/pics/tabmenu.jpg)";
  }

  tab.style.backgroundImage = "url(common/pics/tabmenuselected.jpg)";
  previousSelectedReportTab = tab;
}

function reportTabClicked( e)
{
	var target = getTargetFromEvent( e);	
  
  setReportTabActive( target.parentNode);
  
	if ( target.parentNode.id == "preGameStatsTab")
	{
		goToSub( "preStat");
	} 

	if ( target.parentNode.id == "preCommentsTab")
	{
		goToSub( "preComment");
	} 

	if ( target.parentNode.id == "commentsTab")
	{
		goToSub( "commentTab");
	} 
}

function cleanRaportTab()
{
	var table = document.getElementById("gameReportTabTableId");
  var container = document.getElementById("contentDiv");
  	
	while ( table.nextSibling)
	{
		container.removeChild( table.nextSibling);
	}
}

function createStatRow( stat )
{
  var pid = stat.attributes.getNamedItem("player").nodeValue;
  var player = stat.attributes.getNamedItem("name").nodeValue;
  var goals = stat.attributes.getNamedItem("goals").nodeValue;
  var assists = stat.attributes.getNamedItem("assists").nodeValue;
  var penalty = stat.attributes.getNamedItem("penalty").nodeValue;
  var info = stat.attributes.getNamedItem("info").nodeValue;
  var str = "<a class=\"blBlack\" onclick=\"goToMenu('players#" + pid +"')\">"+ player +"</a>"
  str += " (" + goals + "+" + assists + ")";
  
  if ( penalty > 0 )
  {
    str += ", " + penalty + "min ";
  }
  
  if ( info.length)
  {
  	str += ", " + info;
  }

  return str;  
}

function makeAgeStr( age)
{
  var sid = 24 * 3600;
  var siy = 365 * sid;
  
  var years = age / siy;
  age = age % siy;
  
  var days = age / sid;
  
  return "Joukkueen ikä " + Math.floor( years) + " vuotta ja " + Math.floor( days) + " päivää";
}

function loadGameReport( id)
{
	activeGameId = id;
	
  var params = "rid=getGames";
  params += "&id=" + id;
  params += "&details=all";
  
  xmlHttpRequest( "common/server/games.php", params, 0);
  var xml = xmlParser( xmlHttp.responseText);  
  //testAlert( xmlHttp.responseText);  
  
  
  var container = document.getElementById("contentDiv");
  
  //open game menu
  openMenu( 3);
  
  game = xml.getElementsByTagName("game")[0];

  //get basic info
  var div = game.attributes.getNamedItem("divi").nodeValue;
  var league = game.attributes.getNamedItem("league").nodeValue;
  
  activeDiv = div;
  activeLeague = league;
  updateTabHeader();
	cleanContainer( container);
	
	var now = new Date();
	now = now.getTime();
  
  activeTime = 1000 * parseInt( game.attributes.getNamedItem("date").nodeValue);
  time = new Date( activeTime);
  activeT1 = game.attributes.getNamedItem("team1").nodeValue;
  activeT2 = game.attributes.getNamedItem("team2").nodeValue;
  var t1n = game.attributes.getNamedItem("t1n").nodeValue;
  activeN1 = t1n;
  var t2n = game.attributes.getNamedItem("t2n").nodeValue;
  activeN2 = t2n;
  var s1 = parseInt( game.attributes.getNamedItem("s1").nodeValue);
  var s2 = parseInt( game.attributes.getNamedItem("s2").nodeValue);
  var info = game.attributes.getNamedItem("info").nodeValue;
  
	//time and info
  var table = document.createElement("table");  
  table.id = "infoTimeTableId";
  table.className = "gameTable";
  
  var row = table.insertRow( 0);
  var cell = row.insertCell(0);
  cell.className = "gameCellTimeHeaderClass fDefaultB";
  var infostr = makeDate( time, 1) + ", " + info;
  cell.innerHTML = infostr;
  container.appendChild( table);  
  
  //result row
  var table = document.createElement("table");  
  table.id = "resultRowTableId";
  table.className = "gameTable";
  row = table.insertRow( 0);
  cell = row.insertCell(0);
  cell.className = "gameCellResult fResult";
  cell.style.textAlign = "right";
  
  var resStr = t1n;
  if ( s1 >= 0 )
  {
  	resStr += " " + s1;
  }
  cell.innerHTML = resStr; 
  cell = row.insertCell(1);
  cell.className = "gameCellResult fResult";
  cell.style.textAlign = "left";

	resStr = ""; 
  if ( s2 >= 0 )
  {
  	resStr += s2 + " ";
  }
 	resStr += t2n;

  cell.innerHTML = resStr;  
  container.appendChild( table);  
  
  //details rows
  var table = document.createElement("table");  
  table.id = "detailsTableId";
  table.className = "gameTable";
  var rowIndex = 0;
  
  var ht = game.getElementsByTagName( activeT1 + "PlayerStat");
  var vt = game.getElementsByTagName( activeT2 + "PlayerStat");
  playersInGame = new Array();
  
  ageSumH = 0;
  ageSumV = 0;
  ageCountH = 0;
  ageCountV = 0;  

  for ( var i = 0; i < ht.length + 1 || i < vt.length + 1; i++)
  {
    row = table.insertRow( rowIndex++);
    
    //star cell
    var starcell = row.insertCell(0);
    var player = "";
    
    //stat cell	
    cell = row.insertCell(1);
    cell.className = "gameCellStat fDefault";
    cell.style.textAlign = "right";
    if ( i < ht.length )
    {
      cell.innerHTML = createStatRow( ht[i]);
      player = ht[i].attributes.getNamedItem("player").nodeValue;
      
      var age = new Number( ht[i].attributes.getNamedItem("age").nodeValue);
      if ( age > 0 ) 
      {
         ageSumH += age;
         ageCountH++; 
      }
     
      playersInGame.push( player);
    } else
    {
    	if ( i == 0)
    	{
    		cell.innerHTML = "Ei tilastoja saatavilla";
    	}
    }

    makeStarCell( starcell, player);

    //stat cell	
    cell = row.insertCell(2);
    cell.className = "gameCellStat fDefault";
    cell.style.textAlign = "left";

    if ( i < vt.length )
    {
      cell.innerHTML = createStatRow( vt[i]);
      player = vt[i].attributes.getNamedItem("player").nodeValue;

      var age = new Number( vt[i].attributes.getNamedItem("age").nodeValue);
      if ( age > 0 ) 
      {
         ageSumV += age;
         ageCountV++; 
      }
      
      playersInGame.push( player);
    } else
    {
    	if ( i == 0)
    	{
    		cell.innerHTML = "Ei tilastoja saatavilla";
    	}
    	player = "";
    }
    
    //star cell
    starcell = row.insertCell(3);
    makeStarCell( starcell, player);
  }
  
  //create avarage age row
  if ( ageCountH || ageCountV && testMode)
  {
    row = table.insertRow( rowIndex++);
    
    //star cell
    var starcell = row.insertCell(0);
    
    //stat cell	
    cell = row.insertCell(1);
    cell.className = "gameCellStat fDefaultB";
    cell.style.textAlign = "right";
    
    if ( ageCountH )
    {
      cell.innerHTML = makeAgeStr( ageSumH / ageCountH);
    }

    //stat cell	
    cell = row.insertCell(2);
    cell.className = "gameCellStat fDefaultB";
    cell.style.textAlign = "left";

    if ( ageCountV )
    {
      cell.innerHTML = makeAgeStr( ageSumV / ageCountV);
    }
    
    starcell = row.insertCell(3);
  }

  container.appendChild( table);  

	//best player results
	var votes = xml.getElementsByTagName("voteinfo");
	bestPlayerResults( votes, vt.length + ht.length);

	//best player voting
	bestPlayerVote();
	registerPageCallback( eventCallbackGameReport);
  
  //report header
  if ( now > (activeTime+3600*1000) )
  {
	  var table = document.createElement("table");  
  	table.className = "gameRaportTable";
	  table.id = "reportTableId";
 
	  var report = game.getElementsByTagName("report");

	  row = table.insertRow( 0);
  	cell = row.insertCell( 0);
  	cell.className = "gameCellReportHeader fDefaultB"

  	if ( report.length > 0)
  	{
    		cell.innerHTML = "Raportti";

	  	//report content
	  	row = table.insertRow( 1);
	  	cell = row.insertCell( 0);
		  cell.className = "gameCellReport fDefault"
		  cell.innerHTML = report[0].childNodes[0].nodeValue;
  	} else
  	{
		  if ( s1 >= 0 )
	  	{
    		cell.innerHTML = "Ei raporttia";
  	  } else
	    {
  	   	cell.innerHTML = "Tulosta ei ole vielä kirjattu tai se ei ole tiedossa. Jätä tulos kommenttina, jos tiedät sen.";
	    }
  	}
	  container.appendChild( table); 
	}
	  
  createReportTab()
}

function createReportTab()
{
  var container = document.getElementById("contentDiv");;
  
  var table = document.createElement("table");
  table.id = "gameReportTabTableId";
  table.className = "tabTable";
  table.style.marginTop = "40px";
  tabRow = table.insertRow(0);

  tabCreationIndex = 0;
  
  var now = new Date().getTime();
  

  if ( (activeTime + 3600000) > now )
  {
  	createTab("Ennakko tilastot", "preGameStatsTab", "reportTabClicked");
  	
  	if ( (activeTime - 40 * 24 * 3600000) < now )
  	{
  		createTab("Kommentit", "preCommentsTab", "reportTabClicked");
  	}
  } else
  {
  	createTab("Ennakko tilastot", "preGameStatsTab", "reportTabClicked");
  	createTab("Ennakko kommentit", "preCommentsTab", "reportTabClicked");
  	createTab("Kommentit", "commentsTab", "reportTabClicked");
  }

  cell = tabRow.insertCell( tabCreationIndex);
  
  row = table.insertRow(1);
  cell = row.insertCell(0);
  cell.colSpan = "4";
  cell.id = "reportTabHeaderId";
  cell.className = "tabMenuBase fDefault";
  cell.innerHTML = "";  

  container.appendChild( table);	
  
//  setReportTabActive( document.getElementById("preGameStatsTab"));
//  preGameStat();
	
  if ( (activeTime + 3600*1000) > now )
  {
  	if ( (activeTime - 40 * 24 * 3600000) < now )
  	{
  		createPreCommentTab();
  	} else
  	{
  		preGameStat();
  	}
  } else
  {
  	createCommentTab();
  }

  
  scrollTo( 0,0);
}

function preGameStat()
{
	setReportTabActive( document.getElementById("preGameStatsTab"));
	var container = document.getElementById("contentDiv");
	cleanRaportTab();
	
	
	//for games between
  var now = new Date();
  now = phpTime( now);
	var toTime = activeTime - 3600 * 1000;
  params = "rid=getGames";
  params += "&order=desc";	
  params += "&type=r";
  params += "&to=" + phpTime( toTime);
  params += "&team1=" + activeT1;
  params += "&team2=" + activeT2;
  params += "&makeStanding=1";
	
	var games = getDataForParams( params, null);
	if ( games > 0)
	{
		if ( games == 1)
		{
			document.getElementById("reportTabHeaderId").innerHTML = "1 keskinäinen ottelu ennen tätä";
		} else
		{
			document.getElementById("reportTabHeaderId").innerHTML = games + " keskinäistä ottelua ennen tätä";
		}		
	} else
	{
		document.getElementById("reportTabHeaderId").innerHTML = "Ei keskinäisiä otteluita ennen tätä";	
	}
	
	//create sub header, last games home
	var table = document.createElement("table");  
  table.className = "gameRaportTable";
  table.id = "lastGamesHomeTableId";
 
  row = table.insertRow( 0);
  cell = row.insertCell( 0);
  cell.className = "gameCellReportHeader fDefaultB"
 	cell.innerHTML = activeN1 + ", viimeisimmät pelit";
  container.appendChild( table); 
  
  //for last games home 
  params = "rid=getGames";
  params += "&order=desc";	
  params += "&type=r";
  params += "&to=" + phpTime( toTime);
  params += "&team1=" + activeT1;
  params += "&count=5";
  params += "&makeStanding=1";
	getDataForParams( params, activeT1);  
	
	//create sub header, last games visitor
	var table = document.createElement("table");  
  table.className = "gameRaportTable";
  table.id = "lastGamesHomeTableId";
 
  row = table.insertRow( 0);
  cell = row.insertCell( 0);
  cell.className = "gameCellReportHeader fDefaultB"
 	cell.innerHTML = activeN2 + ", viimeisimmät pelit";
  container.appendChild( table); 
  
  //for last games home 
  params = "rid=getGames";
  params += "&order=desc";	
  params += "&type=r";
  params += "&to=" + phpTime( toTime);
  params += "&team1=" + activeT2;
  params += "&count=5";
  params += "&makeStanding=1";
	getDataForParams( params, activeT2);  	
}

function getDataForParams( params, standingFor)
{
	var container = document.getElementById("contentDiv");

  xmlHttpRequest( "common/server/games.php", params, 0);
  var xml = xmlParser( xmlHttp.responseText);  
  //testAlert( xmlHttp.responseText);   

	var games = xml.getElementsByTagName("game");

	if ( games.length > 0)
	{
		//create result table
		var table = document.createElement("table");
		table.style.marginTop = "10px";
		gameTableConf( table, 0, false);
	
	
		for ( var i = 0; i < games.length; i++)
		{
			addGameToTable( games[i]);
		}

		container.appendChild( table);
	} 
	
	//create standing table
	var table = document.createElement("table");
	table.style.marginTop = "15px";
	standingTableConf( table, 1);
	
	var teams = xml.getElementsByTagName("teamdata");

	if ( teams.length > 0)
	{
		createStandingHeader();
	}

	var rowIndex = 0;
	for ( var i = 0; i < teams.length; i++)
	{
		if ( standingFor != null)
		{
			if ( teams[i].attributes.getNamedItem("teamid").nodeValue != standingFor)
			{
				continue;
			}
		}
		
		addTeamToStandingTable( teams[i]);
	}
		
	container.appendChild( table);		
	
	return games.length;
}

function commentsTab()
{
	var container = document.getElementById("contentDiv");
	cleanRaportTab();
	
}

function eventCallbackGameReport( eventType)
{
	if ( eventType == eventTypeLogin )
	{
		bestPlayerVote();
	}
}

function bestPlayerVote()
{
	//best player vote
  var now = new Date();
  
	if ( now > (activeTime + 24*3600000 * 5) && playersInGame)
	{
		//no time to vote
		return;
	}
	
	var playerIn = false;
	for ( var i = 0; i < playersInGame.length; i++)
	{
		if ( playersInGame[i] == playerid )
		{
			playerIn = true;
			break;
		}
	}
	
	if ( !playerIn)
	{
		//player was not in the game
		return;
	}	
	
	//todo check time
	var container = document.getElementById("contentDiv");
	var statTable = document.getElementById("detailsTableId");
	if ( !statTable )
	{
		//no detail return
		return;
	}

  now = phpTime( now);	
  
  voteTime = 0;
  stars[0] = stars[1] = stars[2] = null;
		
	if ( userid )
	{
		var params = "rid=getVoteStatus";
		params += "&gameid=" + activeGameId;
		params += "&player=" + playerid;
		
  	xmlHttpRequest( "common/server/voting.php", params, 0);
  	var xml = xmlParser( xmlHttp.responseText);  
  	//testAlert( xmlHttp.responseText);  		
  	
  	var voteInfo = xml.getElementsByTagName("voteInfo");
  	
  	if ( voteInfo.length == 1)
  	{
  		updateVoteinfo( voteInfo[0]);
  	}
  		
  	if ( voteTime == 0 || (voteTime + 1800) > now )
  	{
 			//create table
 			var table = document.createElement("table");  
 			table.id = "playerVoteTableId";
 			table.className = "playerVoteTableClass";
 				
 			var row = table.insertRow(0);
 			var cell = row.insertCell(0);
 			cell.innerHTML = "Anna äänesi ottelun kolmelle parhaalle 1-3 tähteä. Valintasi jälkeen paina Lähetä.";
 			cell.className = "playerVoteCellLeft fDefault";

 			var cell = row.insertCell(1)
 			cell.className = "playerVoteCellRight fDefault";
 			var button = document.createElement("input");
 			button.type = "button";
 			button.id = "voteOkButtonId";
 			button.className = "voteOkButtonClass";
 			button.value = "Lähetä";
 			button.onclick = sendVotesClicked;
 			button.disabled = true;
 			cell.appendChild( button);
			setVoteVisibility( true);
 			
 			if ( statTable.nextSibling )
 			{
 				container.insertBefore( table, statTable.nextSibling);
 			}else
 			{
	 			container.appendChild( table);
	 		}
 		}
  } else
  {
  		
  }
}

function setVoteVisibility( visible)
{
	var table = document.getElementById("detailsTableId");
	
 	for ( var i = 0; i < table.rows.length; i++)
 	{
 		
 		var cell = table.rows[i].cells[0];
 		if ( cell.id.substr(0, 8) == "starCell" && cell.id.substr( 8) != playerid)
 		{
 			chIndex = -1;
 			if ( stars[0] && cell.id == stars[0].id ) chIndex = 0;
 			if ( stars[1] && cell.id == stars[1].id ) chIndex = 1;
 			if ( stars[2] && cell.id == stars[2].id ) chIndex = 2;
 			
			for ( var x = 0; x < 3; x++)
			{
				var img = document.createElement( "img");
				if ( x <= chIndex  )
				{
					img.src = "common/pics/starselected.png";
				} else
				{
					img.src = "common/pics/star.png";
				}
				img.id = "star" + x;
				img.onclick = starClicked;
				cell.appendChild( img);
			}			
 		} 				
 		
 		cell = table.rows[i].cells[3];
 		if ( cell.id.substr(0, 8) == "starCell"  && cell.id.substr( 8) != playerid)
 		{
 			chIndex = -1;
 			if ( stars[0] && cell.id == stars[0].id ) chIndex = 0;
 			if ( stars[1] && cell.id == stars[1].id ) chIndex = 1;
 			if ( stars[2] && cell.id == stars[2].id ) chIndex = 2;

			for ( var x = 0; x < 3; x++)
			{
				var img = document.createElement( "img");
				if ( x <= chIndex  )
				{
					img.src = "common/pics/starselected.png";
				} else
				{
					img.src = "common/pics/star.png";
				}
				img.id = "star" + x;
				img.onclick = starClicked;
				cell.appendChild( img);
			}			
 		} 				
 	}	
}

function makeStarCell( cell, player)
{
	
	cell.className = "gameCellStatStar";
	cell.style.margin = "2px";

	if ( player.length)
	{
		cell.id = "starCell" + player;
	}
}

function starClicked( event)
{
	var targ = getTargetFromEvent( event);
	var index = parseInt( targ.id.substr( 4, 1));

	for ( var i = 0; i < 3; i++)
	{
		//remove old selections
		if ( stars[index])
		{
			stars[index].childNodes[i].src = "common/pics/star.png";
		}
		//mark new selections
		if ( i <= index)
		{
			targ.parentNode.childNodes[i].src = "common/pics/starselected.png";
		}
	}

	//save selection
	stars[index] = targ.parentNode;
	
	//remove overlapping selections
	for ( var i = 0; i < 3; i++)
	{
		if ( i != index && stars[i] == targ.parentNode ) 
		{
			stars[i] = null;
		}
	}
	
	//check is all selected
	var button = document.getElementById("voteOkButtonId");
	if ( stars[0] && stars[1] && stars[2])
	{
		button.disabled = false;
	} else
	{
		button.disabled = true;
	}
}

function sendVotesClicked()
{
	var params = "rid=votePlayers";
	params += "&sid=" + sessionid;
	params += "&star1=" + stars[0].id.substr( 8);
	params += "&star2=" + stars[1].id.substr( 8);
	params += "&star3=" + stars[2].id.substr( 8);
	params += "&gameid=" + activeGameId;
	params += "&player=" + playerid;
	
  xmlHttpRequest( "common/server/voting.php", params, 0);
  var xml = xmlParser( xmlHttp.responseText);  	
  //testAlert( xmlHttp.responseText);  	
  
  var fail = xml.getElementsByTagName("fail");
  if ( fail.length)
  {
  	var reason = fail[0].attributes.getNamedItem("reason").nodeValue;
		alert("Äänestys epäonnistui.");
  } else
  {
		alert("Äänesi rekistöröity. Sinulla on 30 minuuttia aikaa muuttaa ääniäsi jos tarvetta.");
  }
}

function updateVoteinfo( voteInfo)
{
	voteTime = parseInt( voteInfo.attributes.getNamedItem("votetime").nodeValue);
	stars[0] = document.getElementById("starCell" + voteInfo.attributes.getNamedItem("star1").nodeValue);
	stars[1] = document.getElementById("starCell" + voteInfo.attributes.getNamedItem("star2").nodeValue);
	stars[2] = document.getElementById("starCell" + voteInfo.attributes.getNamedItem("star3").nodeValue);  		
} 

function bestPlayerResults( votes, playerCount)
{
	if ( !votes.length)
	{
		//no votes for this game
		return;
	} 

	var now = new Date();
	now = now.getTime();
	var headerstr = "";

	if ( now < (activeTime + 3600000 * 25 * 5))
	{
		headerstr = "Polartek-tähdet. Äänestys käynnissä 5 vuorokautta pelin jälkeen.";// " + votes.length + "/" + playerCount + " ääntä annettu.";
		headerstr += " Äänet ovat pelissä olleiden pelaajien antamia.";
	} else
	{
		headerstr = "Polartek-tähdet. Äänet ovat pelissä olleiden pelaajien antamia.";
	}

	var container = document.getElementById("contentDiv");	

	//create headertable
	var table = document.createElement("table");
	table.className = "gameRaportTable";
	
	var row = table.insertRow( 0);
	var cell = row.insertCell(0);
	cell.className = "fDefault";
	cell.innerHTML = headerstr;
	container.appendChild( table);
	
	//create headertable
	var table = document.createElement("table");
	table.className = "playerVoteResultTableClass";
	var rowIndex = 0;
	
	for ( var i = 0; i < 3 && i < votes.length; i++)
	{
		var player = votes[i].attributes.getNamedItem("player").nodeValue;
		var playername = votes[i].attributes.getNamedItem("name").nodeValue;
		var votecount = parseInt( votes[i].attributes.getNamedItem("votes").nodeValue);
		
		//star row
		row = table.insertRow( rowIndex++);
		cell = row.insertCell(0);
		cell.className = "fDefault starResultLeftClass";
		cell.innerHTML = playername + " ( " + votecount + " pistettä)";
	
		cell = row.insertCell(0);
		cell.className = "starResultRightClass";
		
		for ( var j = 0; j < (3-i); j++)
		{
				var img = document.createElement( "img");
				img.src = "common/pics/stargold.png";
				cell.appendChild( img);			
		}		

	}

	container.appendChild( table);

}
