private void btnAddPlayer_Click(object sender, EventArgs e)
        {
            using (var dialog = new frmCreatePlayer())
            {
                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    var record = new PlayerRecord();
                    record.FirstName = dialog.FirstName;
                    record.LastName = dialog.LastName;
                    if (dialog.AdditionalInformation)
                    {
                        record.ForumName = dialog.ForumName;
                        record.Email = dialog.Email;
                        record.Hometown = dialog.Hometown;
                        record.Region = dialog.PlayerRegion;
                        record.Faction = dialog.Faction;
                    }

                    Config.Settings.Players.Add(record);
                    Config.Settings.SavePlayers();

                    ListViewItem item = new ListViewItem();
                    item.Name = record.ID;
                    item.Text = record.FirstName;
                    item.SubItems.Add(record.LastName);
                    item.SubItems.Add(record.Region);

                    lstPlayers.BeginUpdate();
                    lstPlayers.Items.Add(item);
                    item.Selected = true;
                    lstPlayers.Sort();
                    lstPlayers.EndUpdate();
                }
            }
        }
        private void btnImport_Click(object sender, EventArgs e)
        {
            var targets = new Queue<string>();
            using (var dialog = new OpenFileDialog())
            {
                dialog.CheckFileExists = true;
                dialog.CheckPathExists = true;
                dialog.DefaultExt = ".export";
                dialog.ValidateNames = true;
                dialog.Title = "Select the file or files to Import...";
                dialog.RestoreDirectory = true;
                dialog.Multiselect = true;
                dialog.Filter = "Export Files (*.export)|*.export|All Files (*.*)|*.*";
                if (dialog.ShowDialog() == DialogResult.Cancel) return;

                foreach (string filename in dialog.FileNames)
                    targets.Enqueue(filename);
            }

            while (targets.Count > 0)
            {
                string target = targets.Dequeue();
                var xml = new XmlDocument();
                try
                {
                    xml.Load(target);
                }
                catch
                {
                    MessageBox.Show("An error occurred while trying to import " + Path.GetFileName(target) +
                                    ", it may not be an export or it is corrupted.", "Failed to Import",
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Error);
                    continue;
                }

                XmlNode exportNode = xml.SelectSingleNode("//Export");
                if (exportNode == null)
                {
                    MessageBox.Show("An error occurred while trying to import " + Path.GetFileName(target) +
                                    ", it does not contain an exported Event.", "Failed to Import", MessageBoxButtons.OK,
                                    MessageBoxIcon.Error);
                    continue;
                }

                XmlNodeList playerNodes = exportNode.SelectNodes("Players/Player");
                var newPlayers = new List<PlayerRecord>();
                if (playerNodes != null)
                {
                    foreach (XmlNode playerNode in playerNodes)
                    {
                        var record = new PlayerRecord(playerNode);
                        if (Config.Settings.GetPlayer(record.ID) == null)
                            newPlayers.Add(record);
                    }
                }

                XmlNode tournamentNode = exportNode.SelectSingleNode("Tournament");
                XmlNode leagueNode = exportNode.SelectSingleNode("League");
                if (tournamentNode != null)
                {
                    Tournament tournament = null;
                    try
                    {
                        tournament = new Tournament(tournamentNode);
                    }
                    catch
                    {
                        MessageBox.Show("An error occurred while trying to import " + Path.GetFileName(target) +
                                        ", found a Tournament record but failed to parse it.", "Failed to Import",
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Error);
                        continue;
                    }
                    Tournament tempTournament = Config.Settings.GetTournament(tournament.Name);
                    bool alreadyExists = false;
                    string prefix = "";
                    while (tempTournament != null)
                    {
                        alreadyExists = true;
                        prefix += "!";
                        tempTournament = Config.Settings.GetTournament(prefix + " " + tournament.Name);
                    }

                    string message = "The following information will be imported:\r\n";
                    message += "Tournament: " + tournament.Name + "\r\n";
                    if (alreadyExists)
                        message += "(A Tournament already exists with this name, adding \"" + prefix +
                                   "\" to the name.)\r\n";
                    if (newPlayers.Count > 0)
                        message += "New Players: " + newPlayers.Count.ToString() + " (out of " +
                                   playerNodes.Count.ToString() + " found.)\r\n";
                    message += "\r\nPress OK to import this Event.";

                    if (MessageBox.Show(message, "Confirm Import", MessageBoxButtons.OKCancel,
                                        MessageBoxIcon.Information,
                                        MessageBoxDefaultButton.Button1) == DialogResult.Cancel)
                        continue;

                    foreach (PlayerRecord record in newPlayers)
                        Config.Settings.Players.Add(record);

                    if (prefix.Length > 0) tournament.Name = prefix + " " + tournament.Name;
                    Config.Settings.Tournaments.Add(tournament);
                    Config.Settings.SaveEvents();

                    lstEvents.BeginUpdate();
                    var item = new ListViewItem();
                    item.Name = tournament.Name;
                    item.Text = tournament.Name;
                    item.SubItems.Add("Tournament");
                    item.SubItems.Add(tournament.Location);
                    item.SubItems.Add(tournament.Date.ToShortDateString());
                    item.SubItems.Add(tournament.Players.Count.ToString());
                    if (tournament.Rounds.Count == 0)
                        item.SubItems.Add("Not Started");
                    else if (tournament.Rounds.Count == tournament.TotalRounds &&
                             tournament.Rounds[tournament.TotalRounds - 1].Completed)
                        item.SubItems.Add("Finished");
                    else
                    {
                        int roundNum = tournament.Rounds.Count;
                        if (tournament.Rounds[roundNum - 1].Completed)
                            item.SubItems.Add("Round " + roundNum.ToString() + " of " +
                                              tournament.TotalRounds.ToString() + " Done");
                        else
                            item.SubItems.Add("Round " + roundNum.ToString() + " of " +
                                              tournament.TotalRounds.ToString() + " Active");
                    }
                    lstEvents.Items.Add(item);
                    lstEvents.Sort();
                    lstEvents.EndUpdate();
                }
                else if (leagueNode != null)
                {
                    var pastReference = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0);
                    League league = null;
                    try
                    {
                        league = new League(leagueNode);
                    }
                    catch
                    {
                        MessageBox.Show("An error occurred while trying to import " + Path.GetFileName(target) +
                                        ", found a League record but failed to parse it.", "Failed to Import",
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Error);
                        continue;
                    }
                    League tempLeague = Config.Settings.GetLeague(league.Name);
                    bool alreadyExists = false;
                    string prefix = "";
                    while (tempLeague != null)
                    {
                        alreadyExists = true;
                        prefix += "!";
                        tempLeague = Config.Settings.GetLeague(prefix + " " + league.Name);
                    }

                    string message = "The following information will be imported:\r\n";
                    message += "League: " + league.Name + "\r\n";
                    if (alreadyExists)
                        message += "(A League already exists with this name, adding \"" + prefix +
                                   "\" to the name.)\r\n";
                    if (newPlayers.Count > 0)
                        message += "New Players: " + newPlayers.Count.ToString() + " (out of " +
                                   playerNodes.Count.ToString() + " found.)\r\n";
                    message += "\r\nPress OK to import this Event.";

                    if (MessageBox.Show(message, "Confirm Import", MessageBoxButtons.OKCancel,
                                        MessageBoxIcon.Information,
                                        MessageBoxDefaultButton.Button1) == DialogResult.Cancel)
                        continue;

                    foreach (PlayerRecord record in newPlayers)
                        Config.Settings.Players.Add(record);

                    if (prefix.Length > 0) league.Name = prefix + " " + league.Name;
                    Config.Settings.Leagues.Add(league);
                    Config.Settings.SaveEvents();

                    lstEvents.BeginUpdate();

                    var item = new ListViewItem();
                    item.Name = league.Name;
                    item.Text = league.Name;
                    item.SubItems.Add("League");
                    item.SubItems.Add(league.Location);
                    item.SubItems.Add(league.StartDate.ToShortDateString());
                    item.SubItems.Add(league.Players.Count.ToString());
                    if (league.MatchesPlayed.Count == 0)
                        item.SubItems.Add("Not Started");
                    else if (league.EndDate < pastReference)
                        item.SubItems.Add("Finished");
                    else
                    {
                        item.SubItems.Add(league.MatchesPlayed.Count.ToString() + " Result" +
                                          (league.MatchesPlayed.Count == 1 ? "" : "s") + " Entered");
                    }
                    lstEvents.Items.Add(item);
                    lstEvents.Sort();
                    lstEvents.EndUpdate();
                }
                else
                {
                    MessageBox.Show("An error occurred while trying to import " + Path.GetFileName(target) +
                                    ", the Event information was not found.", "Failed to Import", MessageBoxButtons.OK,
                                    MessageBoxIcon.Error);
                    continue;
                }
            }
        }
        private void btnOK_Click(object sender, EventArgs e)
        {
            string ID = GetPlayerID(cmbName.Text);
            if (ID == null)
            {
                if (MessageBox.Show("\"" + cmbName.Text + "\" appears to be a new player. Add them now?", "New Player",
                    MessageBoxButtons.YesNo, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1) == DialogResult.No)
                    return;
                using (var dialog = new frmCreatePlayer(cmbName.Text))
                {
                    if (dialog.ShowDialog() == DialogResult.Cancel) return;

                    var record = new PlayerRecord();
                    record.FirstName = dialog.FirstName;
                    record.LastName = dialog.LastName;
                    if (dialog.AdditionalInformation)
                    {
                        record.ForumName = dialog.ForumName;
                        record.Email = dialog.Email;
                        record.Hometown = dialog.Hometown;
                        record.Region = dialog.PlayerRegion;
                        record.Faction = dialog.Faction;
                    }

                    Config.Settings.Players.Add(record);
                    Config.Settings.SavePlayers();
                    ID = GetPlayerID(cmbName.Text);

                    cmbName.Items.Add(record.Name);
                }
            }

            LeagueResultsEventArgs results = new LeagueResultsEventArgs(ID);

            foreach (ListViewItem item in lstAchievements.Items)
            {
                if (item.SubItems[2].Text != "0")
                {
                    Achievement achievement = ((Achievement)item.Tag).Clone();
                    achievement.Earned = Convert.ToInt32(item.SubItems[2].Text);
                    results.MatchResult.Achievements.Add(achievement);
                }
            }

            int myVPs = Convert.ToInt32(txtVPs.Text);
            int theirVPs = Convert.ToInt32(txtOpponentVPs.Text);

            results.MatchResult.VictoryPoints = myVPs;
            results.MatchResult.TournamentPoints = myVPs > theirVPs ? 3 : myVPs == theirVPs ? 1 : 0;
            results.MatchResult.Differential = myVPs - theirVPs;
            results.MatchResult.DatePlayed = DateTime.Now;

            if (LeagueResultsEnteredCallback != null) LeagueResultsEnteredCallback(this, results);

            if (chkContinuousAdd.Checked)
            {
                foreach (ListViewItem item in lstAchievements.Items)
                    item.SubItems[2].Text = "0";
                txtVPs.Text = "0";
                txtOpponentVPs.Text = "0";
                cmbName.Text = "";
                cmbName.Focus();
            }
            else
                this.Close();

        }
        private void btnAddNew_Click(object sender, EventArgs e)
        {
            using (var dialog = new frmCreatePlayer())
            {
                if (dialog.ShowDialog() == DialogResult.Cancel) return;

                var player = new PlayerRecord {FirstName = dialog.FirstName, LastName = dialog.LastName};
                if (dialog.AdditionalInformation)
                {
                    player.ForumName = dialog.ForumName;
                    player.Email = dialog.Email;
                    player.Hometown = dialog.Hometown;
                    player.Region = dialog.PlayerRegion;
                    player.Faction = dialog.Faction;
                }

                Config.Settings.Players.Add(player);
                Config.Settings.SavePlayers();

                var id = GetPlayerID(player.Name);
                var item = new ListViewItem { Name = id, Text = player.Name };
                item.SubItems.Add(player.Hometown);
                item.SubItems.Add("New");
                item.SubItems.Add(player.Faction.ToString());
                lstEnrolled.Items.Add(item);

                lblTotal.Text = "Total Players Enrolled: " + lstEnrolled.Items.Count.ToString();
            }
        }
        private void btnAddPlayer_Click(object sender, EventArgs e)
        {
            using (var dialog = new frmCreatePlayer())
            {
                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    var record = new PlayerRecord();
                    record.FirstName = dialog.FirstName;
                    record.LastName = dialog.LastName;
                    if (dialog.AdditionalInformation)
                    {
                        record.ForumName = dialog.ForumName;
                        record.Email = dialog.Email;
                        record.Hometown = dialog.Hometown;
                        record.Region = dialog.PlayerRegion;
                        record.Faction = dialog.Faction;
                    }

                    Config.Settings.Players.Add(record);
                    Config.Settings.SavePlayers();

                    foreach (Form form in MdiChildren)
                        if (form is frmPlayers)
                        {
                            ((frmPlayers) form).RefreshList();
                            break;
                        }
                }
            }
        }
        /// <summary>
        ///     Load all available data from the drive.
        /// </summary>
        public void Load()
        {
            Players.Clear();
            Tournaments.Clear();
            Leagues.Clear();

            var xml = new XmlDocument();
            if (File.Exists(Path.Combine(Program.BasePath, "LuciusIncidentLogbook.dat")))
            {
                xml.Load(Path.Combine(Program.BasePath, "LuciusIncidentLogbook.dat"));
                var baseNode = xml.SelectSingleNode("//Settings");

                if (baseNode != null)
                {
                    var node = baseNode.SelectSingleNode("SeparateTournamentFiles");
                    if (node != null)
                        SeparateEventFiles = Convert.ToBoolean(node.InnerText);
                    node = baseNode.SelectSingleNode("ArchivePath");
                    if (node != null)
                        ArchivePath = node.InnerText;
                    node = baseNode.SelectSingleNode("ConfirmNewRounds");
                    if (node != null)
                        ConfirmNewRounds = Convert.ToBoolean(node.InnerText);
                    node = baseNode.SelectSingleNode("OpenAfterPlayersAdded");
                    if (node != null)
                        OpenAfterPlayersAdded = Convert.ToBoolean(node.InnerText);
                    node = baseNode.SelectSingleNode("AssignTablesRandomly");
                    if (node != null)
                        AssignTablesRandomly = Convert.ToBoolean(node.InnerText);
                    node = baseNode.SelectSingleNode("AutoEnableWebServer");
                    if (node != null)
                        AutoEnableWebServer = Convert.ToBoolean(node.InnerText);
                    node = baseNode.SelectSingleNode("WebServerPassword");
                    if (node != null)
                        WebServerPassword = node.InnerText;
                    node = baseNode.SelectSingleNode("WebServerPort");
                    if (node != null)
                        WebServerPort = Convert.ToInt32(node.InnerText);
                    node = baseNode.SelectSingleNode("AutoCheckForUpdates");
                    if (node != null)
                        AutoCheckForUpdates = Convert.ToBoolean(node.InnerText);
                    node = baseNode.SelectSingleNode("BackupsToKeep");
                    if (node != null)
                        BackupsToKeep = Convert.ToInt32(node.InnerText);
                    node = baseNode.SelectSingleNode("BackupPath");
                    if (node != null)
                        BackupPath = node.InnerText;
                    node = baseNode.SelectSingleNode("Notes");
                    if (node != null)
                        Notes = node.InnerText;
                    node = baseNode.SelectSingleNode("SkipTiedRanks");
                    if (node != null)
                        SkipTiedRanks = Convert.ToBoolean(node.InnerText);
                    node = baseNode.SelectSingleNode("ForumName");
                    if (node != null)
                        ForumName = node.InnerText;
                    node = baseNode.SelectSingleNode("DisableReportIfSent");
                    if (node != null)
                        DisableReportIfSent = Convert.ToBoolean(node.InnerText);
                    node = baseNode.SelectSingleNode("Email/FromName");
                    if (node != null)
                        SMTPFromName = node.InnerText;
                    node = baseNode.SelectSingleNode("Email/FromAddress");
                    if (node != null)
                        SMTPFromAddress = node.InnerText;
                    node = baseNode.SelectSingleNode("Email/Server");
                    if (node != null)
                        SMTPServer = node.InnerText;
                    node = baseNode.SelectSingleNode("Email/Port");
                    if (node != null)
                        SMTPPort = Convert.ToInt32(node.InnerText);
                    node = baseNode.SelectSingleNode("Email/Username");
                    if (node != null)
                        SMTPUsername = node.InnerText;
                    node = baseNode.SelectSingleNode("Email/Password");
                    if (node != null)
                        SMTPPassword = Encryption.DecryptString(node.InnerText);
                }
            }
            if (!Directory.Exists(ArchivePath)) Directory.CreateDirectory(ArchivePath);
            if (!Directory.Exists(BackupPath)) Directory.CreateDirectory(BackupPath);

            if (File.Exists(Path.Combine(Program.BasePath, "Players.dat")))
            {
                xml.Load(Path.Combine(Program.BasePath, "Players.dat"));
                XmlNode baseNode = xml.SelectSingleNode("//Players");
                if (baseNode != null)
                {
                    XmlNodeList playerNodes = xml.SelectNodes("//Players/Player");
                    if (playerNodes != null)
                    {
                        foreach (XmlNode playerNode in playerNodes)
                        {
                            var record = new PlayerRecord(playerNode);
                            Players.Add(record);
                        }
                    }
                }
            }

            var needsSave = false;
            if (SeparateEventFiles)
            {
                string targetPath = Path.Combine(Program.BasePath, "Events");
                if (!Directory.Exists(targetPath)) Directory.CreateDirectory(targetPath);
                string[] tournamentFiles = Directory.GetFiles(targetPath, "*.tournament.dat",
                                                              SearchOption.TopDirectoryOnly);
                foreach (string tournamentFile in tournamentFiles)
                {
                    try
                    {
                        xml.Load(tournamentFile);
                        XmlNode tournamentNode = xml.SelectSingleNode("//Tournament");
                        if (tournamentNode != null)
                        {
                            var tournament = new Tournament(tournamentNode);
                            Tournaments.Add(tournament);
                            if (tournament.NeedsSave) needsSave = true;
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Unexpected error while parsing tournaments in '" + tournamentFile +
                                        ": " + ex.Message, "Exception", MessageBoxButtons.OK);
                    }
                }

                string[] leagueFiles = Directory.GetFiles(targetPath, "*.league.dat",
                                                          SearchOption.TopDirectoryOnly);
                foreach (string leagueFile in leagueFiles)
                {
                    try
                    {
                        xml.Load(leagueFile);
                        XmlNode leagueNode = xml.SelectSingleNode("//League");
                        if (leagueNode != null)
                        {
                            var league = new League(leagueNode);
                            Leagues.Add(league);
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Unexpected error while parsing leagues in '" + leagueFile +
                                        ": " + ex.Message, "Exception", MessageBoxButtons.OK);
                    }
                }
            }
            else
            {
                if (File.Exists(Path.Combine(Program.BasePath, "Events.dat")))
                {
                    xml.Load(Path.Combine(Program.BasePath, "Events.dat"));
                    XmlNodeList tournamentNodes = xml.SelectNodes("//Events/Tournaments/Tournament");
                    if (tournamentNodes != null)
                        foreach (XmlNode tournamentNode in tournamentNodes)
                        {
                            var tournament = new Tournament(tournamentNode);
                            Tournaments.Add(tournament);
                            if (tournament.NeedsSave) needsSave = true;
                        }

                    XmlNodeList leagueNodes = xml.SelectNodes("//Events/Leagues/League");
                    if (leagueNodes != null)
                        foreach (XmlNode leagueNode in leagueNodes)
                            Leagues.Add(new League(leagueNode));
                }
            }
            if (needsSave) SaveEvents();
        }