function OnPrePageLoad()
 {
     /* @var $match Match */
     # set page title
     if ($this->tournament instanceof Match) {
         $action = $this->adding ? "Add " : "Edit ";
         $this->SetPageTitle($action . $this->tournament->GetTitle() . ', ' . Date::BritishDate($this->tournament->GetStartTime()));
     } else {
         $this->SetPageTitle('Page not found');
     }
     $this->SetContentCssClass('matchEdit');
     $this->SetContentConstraint(StoolballPage::ConstrainText());
     $except = array();
     if ($this->tournament instanceof Match) {
         foreach ($this->tournament->GetAwayTeams() as $team) {
             $except[] = $team->GetId();
         }
     }
     $this->LoadClientScript("/scripts/lib/jquery-ui-1.8.11.custom.min.js");
     $this->LoadClientScript("/play/teams/suggest-teams.js.php?except=" . trim(implode(",", $except), ","));
     ?>
     <link rel="stylesheet" type="text/css" href="/css/custom-theme/jquery-ui-1.8.11.custom.css" media="all" />
     <?php 
 }
 /**
  * Creates the controls to edit the matches
  *
  */
 private function CreateMatchControls(Match $tournament, XhtmlElement $box)
 {
     $css_class = 'TournamentEdit';
     $box->SetCssClass($css_class);
     $this->SetCssClass('');
     $box->SetXhtmlId($this->GetNamingPrefix());
     $this->AddControl($box);
     # Preserve tournament title and date, because we need them for the page title when "add" is clicked
     $title = new TextBox($this->GetNamingPrefix() . 'Title', $tournament->GetTitle(), $this->IsValidSubmit());
     $title->SetMode(TextBoxMode::Hidden());
     $box->AddControl($title);
     $date = new TextBox($this->GetNamingPrefix() . 'Start', $tournament->GetStartTime(), $this->IsValidSubmit());
     $date->SetMode(TextBoxMode::Hidden());
     $box->AddControl($date);
     # Matches editor
     $this->EnsureAggregatedEditors();
     $this->matches_editor->DataObjects()->SetItems($tournament->GetMatchesInTournament());
     $this->matches_editor->SetTeams($tournament->GetAwayTeams());
     $box->AddControl($this->matches_editor);
 }
 /**
  * Saves the seasons a match is in
  *
  * @param Match $match
  * @param bool $b_is_new_match
  */
 public function SaveSeasons(Match $match, $b_is_new_match)
 {
     $s_match = $this->GetSettings()->GetTable('Match');
     $s_season_match = $this->GetSettings()->GetTable('SeasonMatch');
     $season_table = $this->GetSettings()->GetTable('Season');
     $comp_table = $this->GetSettings()->GetTable('Competition');
     # Get ids of the tournament matches as well as this match, because they must necessarily be in the same season as their tournament
     # so we'll update the tournament matches whenever we update the season
     $a_matches_in_seasons = array();
     # Check GetId() rather than $b_is_new_match because match is being added as a multi-part process. Even though it's
     # new, by this point in the process it has an id that we need to use.
     if ($match->GetId()) {
         $a_matches_in_seasons[] = $match->GetId();
     }
     if (!$b_is_new_match and $match->GetMatchType() == MatchType::TOURNAMENT) {
         $s_sql = "SELECT match_id FROM {$s_match} WHERE tournament_match_id = " . Sql::ProtectNumeric($match->GetId());
         $o_result = $this->GetDataConnection()->query($s_sql);
         while ($row = $o_result->fetch()) {
             $a_matches_in_seasons[] = $row->match_id;
         }
         $o_result->closeCursor();
     }
     # All changes to master data from here are logged, because this method can be called from the public interface
     # Clear out seasons for this match and its tournament matches, ready to re-insert
     if (count($a_matches_in_seasons)) {
         $sql = "DELETE FROM {$s_season_match} WHERE match_id IN (" . join(', ', $a_matches_in_seasons) . ')';
         $this->LoggedQuery($sql);
     }
     # Add seasons again with new data
     foreach ($match->Seasons() as $season) {
         /* @var $season Season */
         foreach ($a_matches_in_seasons as $i_match_id) {
             $sql = "INSERT INTO {$s_season_match} (season_id, match_id) VALUES (" . Sql::ProtectNumeric($season->GetId()) . ', ' . Sql::ProtectNumeric($i_match_id) . ') ';
             $this->LoggedQuery($sql);
         }
         # If participation in this match implies the team is part of the whole season (ie not practice or tournament or friendly),
         # make sure the team is in the season
         if ($match->GetMatchType() == MatchType::CUP or $match->GetMatchType() == MatchType::LEAGUE) {
             require_once 'stoolball/season-manager.class.php';
             $season_manager = new SeasonManager($this->GetSettings(), $this->GetDataConnection());
             if ($match->GetHomeTeamId()) {
                 $season_manager->EnsureTeamIsInSeason($match->GetHomeTeamId(), $season->GetId());
             }
             $a_away = $match->GetAwayTeams();
             if (is_array($a_away) and count($a_away)) {
                 foreach ($a_away as $o_away_team) {
                     if (is_null($o_away_team)) {
                         continue;
                     }
                     $season_manager->EnsureTeamIsInSeason($o_away_team->GetId(), $season->GetId());
                 }
             }
             unset($season_manager);
         }
     }
     # The number of players in the match is derived from the competitions it's in. It's never entered directly even
     # by admins or displayed. Done to save extra queries when rendering scorecard editing interfaces. If people want to
     # display the number of players per match they can enter the results with the players' names.
     # Get the max number of players who may play based on the competitions the match is in, so long as this isn't a tournament or friendly.
     # For a tournament we'll ask the user instead, so just ignore this code and keep the existing value. Even in a season different
     # tournaments may have different rules, so really can't automate. Friendlies are just as flexible so, again, can't predict.
     if ($match->GetId() and $match->GetMatchType() != MatchType::TOURNAMENT and $match->GetMatchType() != MatchType::TOURNAMENT_MATCH and $match->GetMatchType() != MatchType::FRIENDLY) {
         $season_ids = array();
         foreach ($match->Seasons() as $season) {
             $season_ids[] = $season->GetId();
         }
         if (count($season_ids)) {
             $s_sql = "SELECT MAX({$comp_table}.players_per_team) AS players_per_team, MAX({$comp_table}.overs) AS overs\r\n\t\t\t\tFROM {$season_table} INNER JOIN {$comp_table} ON {$season_table}.competition_id = {$comp_table}.competition_id\r\n\t\t\t\tWHERE {$season_table}.season_id IN (" . implode(',', $season_ids) . ")";
             $result = $this->GetDataConnection()->query($s_sql);
             if (!$this->GetDataConnection()->isError()) {
                 $row = $result->fetch();
                 $match->SetMaximumPlayersPerTeam($row->players_per_team);
                 $match->SetOvers($row->overs);
             }
             $result->closeCursor();
         }
         # Update the match. Using the GetMaximumPlayersPerTeam property because it will give us the existing value
         # (possibly the default value if the code above didn't run because there were no seasons).
         $sql = "UPDATE {$s_match} SET\r\n\t\t\t\t\t\tplayers_per_team = " . Sql::ProtectNumeric($match->GetMaximumPlayersPerTeam()) . ",\r\n\t\t\t\t\t\tovers = " . Sql::ProtectNumeric($match->GetOvers()) . "\r\n\t\t\t\t\t\tWHERE match_id = " . Sql::ProtectNumeric($match->GetId());
         $this->LoggedQuery($sql);
     }
     # This season is mentioned in search results for a match, so request an update,
     # and note for auditing that the match has been changed
     $sql = "UPDATE nsa_match SET \r\n\t    update_search = 1, \r\n\t    date_changed = " . gmdate("U") . ", \r\n        modified_by_id = " . Sql::ProtectNumeric(AuthenticationManager::GetUser()->GetId()) . "\r\n\t    WHERE match_id = " . Sql::ProtectNumeric($match->GetId(), false);
     $this->LoggedQuery($sql);
     # Match data has changed so notify moderator
     $this->QueueForNotification($match->GetId(), $b_is_new_match);
 }
 function OnLoadPageData()
 {
     /* @var $o_last_match Match */
     /* @var $season Season */
     /* @var $team Team */
     # First best guess at where user came from is the page field posted back,
     # second best is tournaments page. Either can be tampered with, so there will be
     # a check later before they're used for redirection. If there's a context
     # season or team its URL will be read from the db and overwrite this later.
     if (isset($_POST['page'])) {
         $this->destination_url_if_cancelled = $_POST['page'];
     } else {
         $this->destination_url_if_cancelled = "/tournaments";
     }
     # new data manager
     $match_manager = new MatchManager($this->GetSettings(), $this->GetDataConnection());
     $match_manager->FilterByMatchType(array(MatchType::TOURNAMENT));
     # Check whether cancel was clicked
     if ($this->IsPostback() and $this->editor->CancelClicked()) {
         # new tournament, nothing saved yet, so just send user back where they came from
         $this->Cancel();
     }
     # Save match
     if ($this->IsPostback() and $this->IsValid()) {
         # Get posted match
         $this->tournament = $this->editor->GetDataObject();
         # Save match
         $match_manager->SaveFixture($this->tournament);
         if (count($this->tournament->GetAwayTeams())) {
             $match_manager->SaveTeams($this->tournament);
         }
         if ($this->season instanceof Season) {
             $this->tournament->Seasons()->Add($this->season);
             $match_manager->SaveSeasons($this->tournament, true);
         }
         http_response_code(303);
         $this->Redirect($this->tournament->AddTournamentTeamsUrl());
     }
     if (isset($this->season)) {
         $season_manager = new SeasonManager($this->GetSettings(), $this->GetDataConnection());
         $season_manager->ReadById(array($this->season->GetId()));
         $this->season = $season_manager->GetFirst();
         $this->editor->SetContextSeason($this->season);
         $this->destination_url_if_cancelled = $this->season->GetNavigateUrl();
         unset($season_manager);
         # If we're adding a match to a season, get last game in season for its date
         $match_manager->ReadLastInSeason($this->season->GetId());
     }
     if (isset($this->team)) {
         # Get more information about the team itself
         require_once 'stoolball/team-manager.class.php';
         $team_manager = new TeamManager($this->GetSettings(), $this->GetDataConnection());
         $team_manager->ReadById(array($this->team->GetId()));
         $this->team = $team_manager->GetFirst();
         $this->editor->SetContextTeam($this->team);
         $this->destination_url_if_cancelled = $this->team->GetNavigateUrl();
         # Get the last game already scheduled for the team to use its date
         $match_manager->ReadLastForTeam($this->team->GetId());
         # Read teams played in the last year in order to get their grounds, which will be put at the top of the select list
         $team_manager->ReadRecentOpponents(array($this->team->GetId()), 12);
         $this->editor->ProbableTeams()->SetItems($team_manager->GetItems());
         unset($team_manager);
     }
     # Use the date of the most recent tournament if it was this year, otherwise just use the default of today
     $o_last_match = $match_manager->GetFirst();
     if (is_object($o_last_match) and gmdate('Y', $o_last_match->GetStartTime()) == gmdate('Y')) {
         if ($o_last_match->GetIsStartTimeKnown()) {
             # If the last match has a time, use it
             $this->editor->SetDefaultTime($o_last_match->GetStartTime());
         } else {
             # If the last match has no time, use 11am BST
             $this->editor->SetDefaultTime(gmmktime(10, 0, 0, gmdate('m', $o_last_match->GetStartTime()), gmdate('d', $o_last_match->GetStartTime()), gmdate('Y', $o_last_match->GetStartTime())));
         }
     }
     unset($match_manager);
     # Get grounds
     $o_ground_manager = new GroundManager($this->GetSettings(), $this->GetDataConnection());
     $o_ground_manager->ReadAll();
     $a_grounds = $o_ground_manager->GetItems();
     $this->editor->Grounds()->SetItems($a_grounds);
     unset($o_ground_manager);
 }
    /**
     * Creates the controls when the editor is in its team view
     *
     */
    private function CreateTeamControls(Match $match, XhtmlElement $match_box)
    {
        $css_class = 'TournamentEdit';
        $match_box->SetCssClass($css_class);
        $this->SetCssClass('');
        $match_box->SetXhtmlId($this->GetNamingPrefix());
        $this->AddControl($match_box);
        # Preserve match title and date, because we need them for the page title when "add" is clicked
        $title = new TextBox($this->GetNamingPrefix() . 'Title', $match->GetTitle(), $this->IsValidSubmit());
        $title->SetMode(TextBoxMode::Hidden());
        $match_box->AddControl($title);
        $date = new TextBox($this->GetNamingPrefix() . 'Start', $match->GetStartTime(), $this->IsValidSubmit());
        $date->SetMode(TextBoxMode::Hidden());
        $match_box->AddControl($date);
        $match_box->AddControl(<<<HTML
        
        <div class="panel"><div><div>
            <h2 class="large"><span><span><span>How many teams do you have room for?</span></span></span></h2>
            <p>Tell us how many teams you have room for and who's coming, and we'll list your tournament with how many spaces are left.</p>
HTML
);
        $max = new TextBox($this->GetNamingPrefix() . 'MaxTeams', $match->GetMaximumTeamsInTournament(), $this->IsValidSubmit());
        $max->SetMode(TextBoxMode::Number());
        $max->SetCssClass('max-teams numeric');
        $match_box->AddControl(new FormPart("Maximum teams", new XhtmlElement('div', $max)));
        $match_box->AddControl("</div></div></div>");
        # Teams editor
        $this->EnsureAggregatedEditors();
        $this->teams_editor->DataObjects()->SetItems($match->GetAwayTeams());
        $match_box->AddControl($this->teams_editor);
        # Change Save button to "Next" button
        if ($this->show_step_number) {
            $this->SetButtonText('Next &raquo;');
        }
    }