/////////////////////////////////////////////////////////
var MM_contentVersion = 6;
var MM_contentRelease = 40;
var MM_FlashCanPlay = false;
if (MOZILLA)
{
	var plugin = (navigator.mimeTypes && navigator.mimeTypes["application/x-shockwave-flash"]) ? navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin : 0;
	if ( plugin ) 
	{
		var words = navigator.plugins["Shockwave Flash"].description.split(" ");
		var MM_PluginVersion = words[2].charAt(0); 
	
		var MM_PluginRelease = words[4].substr(1,words[4].length);
		MM_FlashCanPlay = (MM_PluginVersion >= MM_contentVersion) && (MM_PluginRelease >= MM_contentRelease);
	}
}
else if ((IE4 || IE5) && (navigator.appVersion.indexOf("Win") != -1))
{
	MM_FlashCanPlay = true;
}
// set constants
var GAME_EVENT = 0;
var GAME_SITE = 1;
var GAME_DATE = 2;
var GAME_ROUND = 3;
var GAME_WHITEPLAYER = 4;
var GAME_BLACKPLAYER = 5;
var GAME_RESULT = 6;
var GAME_NIC_KEY = 7;
var GAME_ECO_KEY = 8;
var GAME_ANNOTATOR = 9;
var GAME_FENPOSTION = 10;
var GAME_MOVES = 11;
var GAME_WHOTOPLAY = 12;
// set vars
var board = null;
var gamefile = "puzzels.pgn";
var gamesArray = null;
var selectedGame = null;
var oldField = null;
var GameType = 1;
// if game is a quiz
var WhitePlayerQuiz;
var BlackPlayerQuiz;
var Place;
var Question;
var Aanwijzing;
var Oplossing;
var InitPositie = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w QK - 0 1";
var fenPositie = "";
// Look for Internet Explorer.
var InternetExplorer = navigator.appName.indexOf("Microsoft") != -1;
//
if (navigator.appName && navigator.appName.indexOf("Microsoft") != -1 && 
	navigator.userAgent.indexOf("Windows") != -1 && navigator.userAgent.indexOf("Windows 3.1") == -1)
{
	document.write('<SCRIPT LANGUAGE=VBScript\> \n');
	document.write('on error resume next \n');
	document.write('Sub Board_FSCommand(ByVal command, ByVal args)\n');
	document.write('  call Board_DoFSCommand(command, args)\n');
	document.write('end sub\n');
	document.write('</script\> \n');
}
// The flash move gives a command to java
function Board_DoFSCommand(command, args)
{
	switch (command)
	{
		case "Load":
			this.Board_Load();
			// Be sure the gamefile has loaded
			this.Board_Gamefile(this.gamefile);
			
			break;
		case "ShowPgnGameList":
    	this.GameList_ShowGames(args);
    	break;
    case "ShowPgnData":
    	this.GameInfo_ShowHeader(args);
	
    	break; 
    case "ShowPGNList":
      this.showGamefileList(args);
      break;
    case "GameInfo_MoveNumberChanged":
      this.MoveList_showMove(args);
      break;     
 		case "Error":
			alert(args);
			break;
    default:
      break;  	  
	}
}	
function Board_Load()
{
	this.board = MOZILLA ? document.Board : this.GetElementByID("Board");
		// Give Server domain to Flash
	this.Board_SetCommandParameter("Server", location.host.toLowerCase() + "/nhsb");

	this.Board_SetCommandParameter("EscapeQuotes", MOZILLA ? "True" : "False");
}
function Board_ExecuteCommand(command)
{
	this.board.SetVariable("Command", command);
}
function Board_SetCommandParameter(paramName, paramValue)
{
	this.board.SetVariable(paramName, paramValue);
}
// load a gamefile
function Board_Gamefile(file)
{
	this.Board_SetCommandParameter("PGNfile", file);
	this.Board_SetCommandParameter("QuizMode", this.GameType);
	this.Board_SetCommandParameter("QuizStart", this.StartQuizAt());
	this.Board_ExecuteCommand("LoadPGNfile");
}
function Board_LoadGame(file,type)
{
  this.gamefile = file;
  this.GameType = type;
 // alert();
}
function GameList_ShowGames(gamesString)
{
    if(this.GetElementByID("GameListContainer") == null) 
    {
      return; 
    }
  	var container = this.GetElementByID("GameListContainer");
    this.gamesArray = gamesString.split("*|");
   	output = "";	
  	if (this.gamesArray == null)
	  {
	   	output += "No games found.";
	  }
	  else
	  {
	  	output += "<table id=\"GameList\" cellpadding=\"0\" cellspacing=\"0\">";
    		// Draw each game.
      output += "<tr class=selektor><td>&nbsp;witspeler</td><td>&nbsp;zwartspeler</td><td>&nbsp;</td></tr>";		
		for (var i = 0; i < this.gamesArray.length; i++)
		{
		     output += this.GameList_DrawItem(i);
		}
	   	output += "</table>";
   	}
    	container.innerHTML = output;
    	this.Game_Click(1);
    	this.GameList_SelectGame(0);
}
function GameList_DrawItem(index)
{
	var output = "";
	var game = this.gamesArray[index].split('|');
	// Watch the length of the strings
	var whitePlayer = game[GAME_WHITEPLAYER];
	var blackPlayer = game[GAME_BLACKPLAYER];
	var result = game[GAME_RESULT];
	var plwidth = 16;
	if(result == "1/2-1/2") result = "-";
	index += 1;
	if (MOZILLA)
	{
		output += "<tr id=\"Game" + index + "\" onclick=\"Game_Click(" + index + ")\" onmouseover=\"Game_MouseOver(this)\" onmouseout=\"Game_MouseOut(this)\">";
		output += "<td>&nbsp;" + this.GameList_CutOffString(whitePlayer,plwidth) + "</td>";
		output += "<td>&nbsp;" + this.GameList_CutOffString(blackPlayer,plwidth) + "</td>";
		output += "<td align=\"center\"><nobr>" + result + "</nobr></td>";
		output += "</tr>";
	}
	else
	{
  	output += "<tr id=\"Game" + index + "\" onclick=\"Game_Click(" + index + ")\" onmouseover=\"Game_MouseOver(this)\" onmouseout=\"Game_MouseOut(this)\">";
  	output += "<td>&nbsp;" + this.GameList_CutOffString(whitePlayer,plwidth) + "</td>";
		output += "<td>&nbsp;" + this.GameList_CutOffString(blackPlayer,plwidth) + "</td>";
		output += "<td align=\"center\"><nobr>" + result + "</nobr></td>";
		output += "</tr>";
	}
	return output;
}
// set de lengte 
function GameList_CutOffString(s, length)
{
	if (s.length > length)
	{
		s = s.substr(0, length - 3);
		return s + "...";
	}
	
	return s;
}
function GameList_SelectGame(gameIndex)
{
	if (this.selectedGame != null)
	{
		this.selectedGame.className = "game";
	}
	if (gameIndex == 0) return;
	this.selectedGame = this.GetElementByID("Game" + (gameIndex));
	this.selectedGame.className = "gameSelected";
}
function Game_Click(index)
{
  this.Game_Clear();
	this.Board_SetCommandParameter("GameIndex", index - 1);
	this.Board_ExecuteCommand("ViewPgnGame");
}
function Game_Clear()
{
    this.oldField = null;
    this.GameInfo_setHeaderInfo("whiteplayer","&nbsp;");  
    this.GameInfo_setHeaderInfo("blackplayer","&nbsp;");  
    this.GameInfo_setHeaderInfo("place","&nbsp;");
    this.GameInfo_setHeaderInfo("keyid","&nbsp;");  
    this.GameInfo_setHeaderInfo("annotator","&nbsp;");  
    this.GameInfo_setHeaderInfo("movebox","...loading");
}
function Game_MouseOver(tableRow)
{
	tableRow.className = "gameRowOver";
}
function Game_MouseOut(tableRow)
{	
	tableRow.className = (tableRow == selectedGame) ? "gameSelected" : "";
}
function GameInfo_ShowHeader(game)
{
  // parse game data
  gameItems = game.split('|');
  this.GameInfo_setHeaderInfo("keyid","<b>" + gameItems[GAME_NIC_KEY] + "</b> (" + gameItems[GAME_ECO_KEY] + ")");
  this.WhitePlayerQuiz = gameItems[GAME_WHITEPLAYER];
  this.BlackPlayerQuiz = gameItems[GAME_BLACKPLAYER];
  if(this.GameType != 1)
  {
    this.GameInfo_setHeaderInfo("whiteplayer",this.WhitePlayerQuiz);  
    this.GameInfo_setHeaderInfo("blackplayer",this.BlackPlayerQuiz);  
  }
  gameplace = gameItems[GAME_SITE];
  if(gameItems[GAME_SITE] == "?" || gameItems[GAME_SITE] == "")
  {
      gameplace = gameItems[GAME_EVENT];
      if(gameplace == "?") gameplace = "";
  }
  datum = gameItems[GAME_DATE].split('.');		
  ronde = "";
  if(gameItems[GAME_ROUND] != "?" && gameItems[GAME_ROUND] != "") ronde = " (" + gameItems[GAME_ROUND] + ")";
  gameplace += " " + datum[0] + ronde;
  this.Place = gameplace;
  if(this.GameType != 1)  this.GameInfo_setHeaderInfo("place",gameplace);
  this.GameInfo_setHeaderInfo("annotator",gameItems[GAME_ANNOTATOR]);
  if(this.GameType == 1)
  {
     this.substractQuiz(gameItems[GAME_MOVES]);
     this.GameInfo_setHeaderInfo("movebox",this.Question + gameItems[GAME_WHOTOPLAY]);
  }
  else
  {
     this.GameInfo_setHeaderInfo("movebox",gameItems[GAME_MOVES]);
  } 
  if(gameItems[GAME_FENPOSTION] == "") fenPositie = InitPositie;
  else  fenPositie = gameItems[GAME_FENPOSTION];
}
function GameInfo_setHeaderInfo(headerID,headerValue)
{
    if(this.GetElementByID(headerID) != null)
    {
        this.GetElementByID(headerID).innerHTML = headerValue;
    }
}
function substractQuiz(a)
{
  this.Question = "<b class=question>" + a.substring(a.indexOf("<Q>")+3,a.indexOf("</Q>"));
  this.Aanwijzing = "<b class=aanwijzing>" + a.substring(a.indexOf("<S>")+3,a.indexOf("</S>")) + "</b>";
  this.Oplossing = "<b class=comment>" + a.substring(a.indexOf("</S>")+4);
}
////////////////////////////////////////////////////////
function MoveList_showMove(num)
{
   var s = num;
   if(this.oldField == null)
   {
      if(num > 1 || num < -1)
      {
          this.oldField = this.GetElementByID("move1");
      }
   } 
   if(this.oldField != null)
   {
      var i = 1;
      s = Math.floor(this.oldField.id.substring(4));
      if(Math.floor(num) > 0)
      {
        while(i <= num)
        {
          if(this.GetElementByID("move" + (Math.floor(s) + 1)) != null)
          {
            s = Math.floor(s) + 1;     
          }
          else
          {
            break;
          } 
          i++; 
        }
      }
      if(Math.floor(num) < 0)
      {
         i = 1;
         var a = Math.floor(num)*-1;
         while(i <= a)
         {
            if(this.GetElementByID("move" + (Math.floor(s) - 1)) != null)
            {
                s = Math.floor(s) - 1;     
            }
            else
            {
              if(Math.floor(s) - 1 == 0)
              {
                  s = 0;
                 	this.Board_SetCommandParameter("FenPosition", this.fenPositie);
      	          this.Board_ExecuteCommand("ViewPosition");
      	          this.oldField.style.background = "#FBFBFB";
              }
              break;
            }   
            i++;
         }
      }
   } 
   var newmove = "move" + s;
   if(this.GetElementByID(newmove) != null) showpgnmove(this.GetElementByID(newmove));
}
function showpgnmove(field)
{
	this.Board_SetCommandParameter("FenPosition", field.name);
	this.Board_ExecuteCommand("ViewPosition");
	field.style.background = "#F2E8D8";
	if(this.oldField != null)
	{
		if(field != this.oldField) this.oldField.style.background = "#FBFBFB";
	}	
	oldField = field;
}
function showsolution(action)
{
  if(action < 3)
  {
      this.GameInfo_setHeaderInfo("whiteplayer","<b>" + this.WhitePlayerQuiz + "</b>");
      this.GameInfo_setHeaderInfo("blackplayer","<b>" + this.BlackPlayerQuiz + "</b>");
      this.GameInfo_setHeaderInfo("place",this.Place);
  }
  if(action == 1)
  {
      this.GameInfo_setHeaderInfo("movebox",this.Aanwijzing);
  }
  if(action == 2)
  {
      this.GameInfo_setHeaderInfo("movebox",this.Oplossing);
  }
  if(action == 3)
  {
    this.Game_Clear();  
  	//this.Board_SetCommandParameter("GameIndex", Math.floor(Math.random() * 5) + 1);
  	this.Board_SetCommandParameter("GameIndex",0);
	this.Board_ExecuteCommand("ViewPgnGame");
  }
}
// all functions for fileselections
function wijzigGamefile(selector)
{
    Board_Gamefile(this.getselectedItem(selector));
}
function wijzigPeriode(periode,selector,base)
{
    this.Game_Clear();
	  this.Board_SetCommandParameter("PeriodeIndex", this.getselectedItem(periode));
	  this.Board_SetCommandParameter("PGNselector",selector);
  	this.Board_ExecuteCommand("GetPgnFiles");
}
function getselectedItem(selector)
{
    var menu = this.GetElementByID(selector);
	  return menu.options[menu.selectedIndex].value;
}
function showGamefileList(argumenten)
{
    var gamesList = argumenten.split("|");
    var menu = this.GetElementByID(gamesList[1]);
    var opties = gamesList[2].split('#');
    var selekted = true;
    var i;
    for(i = 0; i<opties.length-1;i++)
    {
        if(opties[i] == "") break;
        var items = opties[i].split('^');
        menu.options[i].value  = items[1];
        menu.options[i].text   = items[2];
        menu.options[i].selected = selekted;
        selekted = false;
    }
}
