init_srand();
     }
     if ($_POST['color'] == 'random') {
         $tmpColor = rand(0, 1) == 1 ? "white" : "black";
     } else {
         $tmpColor = $_POST['color'];
     }
     $tmpQuery = "INSERT INTO games (whitePlayer, blackPlayer, gameMessage, messageFrom, dateCreated, lastMove, ratingWhite, ratingBlack,ratingWhiteM, ratingBlackM,oficial,PVBlack,PVWhite) VALUES (";
     if ($tmpColor == 'white') {
         $white = $_SESSION['playerID'];
         $black = $_POST['opponent'];
     } else {
         $white = $_POST['opponent'];
         $black = $_SESSION['playerID'];
     }
     $tmpQuery .= "{$white}, {$black}, 'playerInvited', '" . $tmpColor . "', NOW(), NOW()," . getRating($white) . "," . getRating($black) . "," . getRatingMonth($white) . "," . getRatingMonth($black) . ",'" . $_POST['oficial'] . "'," . getPV($black) . "," . getPV($white) . ")";
     mysql_query($tmpQuery);
     /* if email notification is activated... */
     if ($CFG_USEEMAILNOTIFICATION) {
         /* if opponent is using email notification... */
         $tmpOpponentEmail = mysql_query("SELECT value FROM preferences WHERE playerID = " . $_POST['opponent'] . " AND preference = 'emailNotification'");
         if (mysql_num_rows($tmpOpponentEmail) > 0) {
             $opponentEmail = mysql_result($tmpOpponentEmail, 0);
             if ($opponentEmail != '') {
                 /* notify opponent of invitation via email */
                 webchessMail('invitation', $opponentEmail, '', $_SESSION['nick']);
             }
         }
     }
 }
 break;
     }
     break;
 case 'responseToInvite':
     if ($_POST['response'] == 'accepted') {
         /* update game data */
         $playb = mysql_query("SELECT * FROM games WHERE gameID='" . $_POST['gameID'] . "'");
         $bl = mysql_fetch_array($playb);
         if ($bl['whitePlayer'] == "0") {
             $white = $_SESSION['playerID'];
             $black = $bl['blackPlayer'];
             $tmpQuery = "UPDATE games SET ratingWhite = " . getRating($white) . ", ratingBlack = " . getRating($black) . ", ratingWhiteM = " . getRatingMonth($white) . ", ratingBlackM = " . getRatingMonth($black) . ", PVWhite = " . getPV($white) . ", PVBlack = " . getPV($black) . ", gameMessage = '', messageFrom = '', whitePlayer = '" . $_SESSION['playerID'] . "' WHERE gameID = " . $_POST['gameID'];
             mysql_query($tmpQuery);
         } elseif ($bl['blackPlayer'] == "0") {
             $white = $bl['whitePlayer'];
             $black = $_SESSION['playerID'];
             $tmpQuery = "UPDATE games SET ratingWhite = " . getRating($white) . ", ratingBlack = " . getRating($black) . ", ratingWhiteM = " . getRatingMonth($white) . ", ratingBlackM = " . getRatingMonth($black) . ", PVWhite = " . getPV($white) . ", PVBlack = " . getPV($black) . ", gameMessage = '', messageFrom = '', blackPlayer = '" . $_SESSION['playerID'] . "' WHERE gameID = " . $_POST['gameID'];
             mysql_query($tmpQuery);
         } else {
         }
         /* setup new board */
         $_SESSION['gameID'] = $_POST['gameID'];
         createNewGame($_POST['gameID']);
         saveGame();
     } else {
         $tmpQuery = "UPDATE games SET gameMessage = 'inviteDeclined', messageFrom = '" . $_POST['messageFrom'] . "' WHERE gameID = " . $_POST['gameID'];
         mysql_query($tmpQuery);
     }
     break;
 case 'WithdrawRequest':
     /* get opponent's player ID */
     $tmpOpponentID = mysql_query("SELECT whitePlayer FROM games WHERE gameID = " . $_POST['gameID']);
function create_match_games($match_id){
   //load up all signed up players and arrange in order
   $tmp_teams = mysql_query("SELECT * FROM matches WHERE match_id = '$match_id'");
   $teams = db_result_to_array($tmp_teams);
   $team1 = $teams[0][1];
   $team2 = $teams[0][2];
   $boards = $teams[0][6];
   //load up player IDs for team 1
   $tmp_players = mysql_query("SELECT playerID FROM match_players WHERE match_id = '$match_id' AND teamID = '$team1'");
   $team1_players = db_result_to_array($tmp_players);
   for ($i=0;$i<$boards;$i++){
      $tmp_player_info = mysql_query("SELECT rating FROM {$db_prefix}players WHERE playerID = ".$team1_players[$i][0]);
      $tmp_rating = mysql_fetch_array($tmp_player_info);
      $rating=$tmp_rating[0];
      $team1_players[$i][1] = $rating;
#      echo "Player team 1, player $i: ".$team1_players[$i][0]." rating = ".$team1_players[$i][1]."<br>";
   }
   usort ($team1_players, 'compare');//sort in rank order

   //load up player IDs for team 2
   $tmp_players = mysql_query("SELECT playerID FROM match_players WHERE match_id = '$match_id' AND teamID = '$team2'");
   $team2_players = db_result_to_array($tmp_players);
   for ($i=0;$i<$boards;$i++){
      $tmp_player_info = mysql_query("SELECT rating FROM {$db_prefix}players WHERE playerID = ".$team2_players[$i][0]);
      $tmp_rating = mysql_fetch_array($tmp_player_info);
      $rating=$tmp_rating[0];
      $team2_players[$i][1] = $rating;
#      echo "Player team 2, player $i: ".$team2_players[$i][0]." rating = ".$team2_players[$i][1]."<br>";
   }
   usort ($team2_players, 'compare');//sort in rank order

   //debug line
#   echo "<br>".$team1_players[0][0]." : ".$team1_players[0][1]."<br>".$team1_players[1][0]." : ".$team1_players[1][1]."<br>".$team2_players[0][0]." : ".$team2_players[0][1]."<br>".$team2_players[1][0]." : ".$team2_players[1][1];


//for each pair, create first game
$tmpColor = 'white';//set first team 1 player to white
for ($i=0;$i<$boards;$i++){
   $tmpQuery = "INSERT INTO {$db_prefix}games (white_player, black_player, status, message_from, dateCreated, lastMove, ratingWhite, ratingBlack, ratingWhiteM, ratingBlackM, oficial, PVBlack, PVWhite, timelimit, teamMatch, team) VALUES (";
   if ($tmpColor == 'white'){
      $white = $team1_players[$i][0];
      $black = $team2_players[$i][0];
      $tmpColor = 'black';
   }else{
      $white = $team2_players[$i][0];
        $black = $team1_players[$i][0];
        $tmpColor = 'white';
    }
   $tmpQuery .= "$white, $black, '', '', NOW(), NOW(),".getRating($white).",".getRating($black).",".getRatingMonth($white).",".getRatingMonth($black).",'1',".getPV($black).",".getPV($white).",".getMatchTimeLimit($match_id).",'1',$match_id)";
   mysql_query($tmpQuery);

   /* if email notification is activated... */
#   if ($CFG_USEEMAILNOTIFICATION){
#      /* if opponent is using email notification... */
#      $tmpOpponentEmail = mysql_query("SELECT value FROM ch_preferences WHERE playerID = ".$_POST['opponent']." AND preference = 'emailNotification'");
#      if (mysql_num_rows($tmpOpponentEmail) > 0){
#         $opponentEmail = mysql_result($tmpOpponentEmail, 0);
#         if ($opponentEmail != ''){
#            /* notify opponent of invitation via email */
#            webchessMail('invitation', $opponentEmail, '', $_SESSION['nick']);
#         }
#      }
#   }

   // setup new board
   $game_id = mysql_insert_id();//   get ID of new game
   $_SESSION['game_id'] = $game_id;
   createNewGame($game_id);
   saveGame();
}
//for each pair, create second game
$tmpColor = 'black';//set first team 1 player to white
for ($i=0;$i<$boards;$i++){
   $tmpQuery = "INSERT INTO {$db_prefix}games (white_player, black_player, status, message_from, dateCreated, lastMove, ratingWhite, ratingBlack, ratingWhiteM, ratingBlackM, oficial, PVBlack, PVWhite, timelimit, teamMatch, team) VALUES (";
   if ($tmpColor == 'black'){
      $black = $team1_players[$i][0];
      $white = $team2_players[$i][0];
      $tmpColor = 'white';
   }else{
      $black = $team2_players[$i][0];
        $white = $team1_players[$i][0];
        $tmpColor = 'black';
    }
    $tmpQuery .= "$white, $black, '', '', NOW(), NOW(),".getRating($white).",".getRating($black).",".getRatingMonth($white).",".getRatingMonth($black).",'1',".getPV($black).",".getPV($white).",".getMatchTimeLimit($match_id).",'1',$match_id)";
   mysql_query($tmpQuery);

   /* if email notification is activated... */
#   if ($CFG_USEEMAILNOTIFICATION){
#      /* if opponent is using email notification... */
#      $tmpOpponentEmail = mysql_query("SELECT value FROM ch_preferences WHERE playerID = ".$_POST['opponent']." AND preference = 'emailNotification'");
#      if (mysql_num_rows($tmpOpponentEmail) > 0){
#         $opponentEmail = mysql_result($tmpOpponentEmail, 0);
#         if ($opponentEmail != ''){
#            /* notify opponent of invitation via email */
#            webchessMail('invitation', $opponentEmail, '', $_SESSION['nick']);
#         }
#      }
#   }

   // setup new board
   $game_id = mysql_insert_id();//   get ID of new game
   $_SESSION['game_id'] = $game_id;
   createNewGame($game_id);
   saveGame();
}
  //update match table
   mysql_query("UPDATE matches SET status = '' WHERE match_id = '$match_id'");
}
function create_games($id) {

global $_SESSION;

$t = mysql_query("SELECT * FROM tournaments WHERE id = '$id'");
$t = mysql_fetch_array($t);

if ($t['players'] == 4)
{

$games = array(
          1 => array('whitePlayer' => $t['player1'], 'blackPlayer' => $t['player2']),
          2 => array('whitePlayer' => $t['player1'], 'blackPlayer' => $t['player3']),
          3 => array('whitePlayer' => $t['player1'], 'blackPlayer' => $t['player4']),

          4 => array('whitePlayer' => $t['player2'], 'blackPlayer' => $t['player1']),
          5 => array('whitePlayer' => $t['player2'], 'blackPlayer' => $t['player3']),
          6 => array('whitePlayer' => $t['player2'], 'blackPlayer' => $t['player4']),

          7 => array('whitePlayer' => $t['player3'], 'blackPlayer' => $t['player1']),
          8 => array('whitePlayer' => $t['player3'], 'blackPlayer' => $t['player2']),
          9 => array('whitePlayer' => $t['player3'], 'blackPlayer' => $t['player4']),

         10 => array('whitePlayer' => $t['player4'], 'blackPlayer' => $t['player1']),
         11 => array('whitePlayer' => $t['player4'], 'blackPlayer' => $t['player2']),
         12 => array('whitePlayer' => $t['player4'], 'blackPlayer' => $t['player3']));

         while (list($key, $val) = each($games))
         {

                 $query = "INSERT INTO {$db_prefix}games (timelimit, gameMessage,messageFrom, whitePlayer, blackPlayer, dateCreated,
                 lastMove, ratingWhite, ratingBlack,ratingWhiteM,ratingBlackM,PVBlack,PVWhite,tournament,oficial,thematic)
                 VALUES (";

                 $white = $games[$key]['whitePlayer'];
        $black = $games[$key]['blackPlayer'];

                 $query .= "".$t['days'].", '', '', $white, $black, NOW(), NOW(),".getRating($white).",".getRating($black).",".getRatingMonth($white).",".getRatingMonth($black).",".getPV($black).",".getPV($white).", '$id', '".$t['official']."','".$t['thematic']."')";

                 mysql_query($query);

                 echo mysql_error();

         } // while

         $query = mysql_query("SELECT game_id FROM {$db_prefix}games WHERE tournament = '$id'");

    while ($g = mysql_fetch_array($query))
    {
                 if (!function_exists('createNewGame'))
                 {
                    include 'newgame.php';
                 }

                 $_SESSION['gameID'] = $g['gameID'];
        createNewGame($_SESSION['gameID']);
        saveGame();

         } // while

} // 4 players

}
                    init_srand();

                if ($_POST['color'] == 'random')
                    $tmpColor = (rand(0,1) == 1) ? "white" : "black";
                else
                    $tmpColor = $_POST['color'];

                $tmpQuery = "INSERT INTO games (timelimit, whitePlayer, blackPlayer, gameMessage, messageFrom, dateCreated, lastMove, ratingWhite, ratingBlack,ratingWhiteM, ratingBlackM,oficial,PVBlack,PVWhite,thematic) VALUES (";
                if ($tmpColor == 'white'){
                    $white = $_SESSION['playerID'];
                    $black = $_POST['opponent'];
                }else{
                    $white = $_POST['opponent'];
                    $black = $_SESSION['playerID'];
                }
                $tmpQuery .= "$_POST[timelimit], $white, $black, 'playerInvited', '".$tmpColor."', NOW(), NOW(),".getRating($white).",".getRating($black).",".getRatingMonth($white).",".getRatingMonth($black).",'".$_POST['oficial']."',".getPV($black).",".getPV($white).",'".$_POST['thematic']."')";
                mysql_query($tmpQuery);

                /* if email notification is activated... */
                if ($CFG_USEEMAILNOTIFICATION)
                {
                    /* if opponent is using email notification... */
                    $tmpOpponentEmail = mysql_query("SELECT value FROM preferences WHERE playerID = ".$_POST['opponent']." AND preference = 'emailNotification'");
                    if (mysql_num_rows($tmpOpponentEmail) > 0)
                    {
                        $opponentEmail = mysql_result($tmpOpponentEmail, 0);
                        if ($opponentEmail != '')
                        {
                            /* notify opponent of invitation via email */
                            webchessMail('invitation', $opponentEmail, '', $_SESSION['firstName']);
                        }