/// <summary>Handles the Click event of the mnuMiscStartNewSeason control. Allows the user to add a new season to the database.</summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">
        ///     The <see cref="RoutedEventArgs" /> instance containing the event data.
        /// </param>
        private async void mnuMiscStartNewSeason_Click(object sender, RoutedEventArgs e)
        {
            if (!SQLiteIO.IsTSTEmpty())
            {
                var r =
                    MessageBox.Show(
                        "Are you sure you want to do this? This is an irreversible action.\nStats and box Scores will be retained, and you'll be able to use all the tool's features on them.",
                        "NBA Stats Tracker",
                        MessageBoxButton.YesNo,
                        MessageBoxImage.Question);
                if (r == MessageBoxResult.Yes)
                {
                    SQLiteIO.SaveSeasonToDatabase();

                    CurSeason = SQLiteIO.GetMaxSeason(CurrentDB);
                    var ibw = new InputBoxWindow("Enter a name for the new season", (CurSeason + 1).ToString());
                    ibw.ShowDialog();

                    var seasonName = String.IsNullOrWhiteSpace(InputBoxWindow.UserInput)
                                         ? (CurSeason + 1).ToString()
                                         : InputBoxWindow.UserInput;

                    var q = "alter table Teams rename to TeamsS" + CurSeason;
                    DB.ExecuteNonQuery(q);

                    q = "alter table PlayoffTeams rename to PlayoffTeamsS" + CurSeason;
                    DB.ExecuteNonQuery(q);

                    q = "alter table Opponents rename to OpponentsS" + CurSeason;
                    DB.ExecuteNonQuery(q);

                    q = "alter table PlayoffOpponents rename to PlayoffOpponentsS" + CurSeason;
                    DB.ExecuteNonQuery(q);

                    q = "alter table Players rename to PlayersS" + CurSeason;
                    DB.ExecuteNonQuery(q);

                    q = "alter table PlayoffPlayers rename to PlayoffPlayersS" + CurSeason;
                    DB.ExecuteNonQuery(q);

                    CurSeason++;

                    SQLiteIO.PrepareNewDB(DB, CurSeason, CurSeason, true);
                    DB.Insert("SeasonNames", new Dictionary<string, string> { { "ID", CurSeason.ToString() }, { "Name", seasonName } });
                    SeasonList.Add(new KeyValuePair<int, string>(CurSeason, seasonName));

                    foreach (var key in TST.Keys.ToList())
                    {
                        var ts = TST[key];
                        for (var i = 0; i < ts.Totals.Length; i++)
                        {
                            ts.Totals[i] = 0;
                            ts.PlTotals[i] = 0;
                        }
                        ts.Record[0] = 0;
                        ts.Record[1] = 0;
                        ts.PlRecord[0] = 0;
                        ts.PlRecord[1] = 0;
                        ts.CalcAvg();
                        TST[key] = ts;
                    }

                    foreach (var key in TSTOpp.Keys.ToList())
                    {
                        var ts = TSTOpp[key];
                        for (var i = 0; i < ts.Totals.Length; i++)
                        {
                            ts.Totals[i] = 0;
                            ts.PlTotals[i] = 0;
                        }
                        ts.Record[0] = 0;
                        ts.Record[1] = 0;
                        ts.PlRecord[0] = 0;
                        ts.PlRecord[1] = 0;
                        ts.CalcAvg();
                        TSTOpp[key] = ts;
                    }

                    foreach (var ps in PST)
                    {
                        for (var i = 0; i < ps.Value.Totals.Length; i++)
                        {
                            ps.Value.Totals[i] = 0;
                            ps.Value.PlTotals[i] = 0;
                        }
                        ps.Value.IsAllStar = false;
                        ps.Value.IsNBAChampion = false;
                        if (ps.Value.Contract.Option == PlayerContractOption.Team2Yr)
                        {
                            ps.Value.Contract.Option = PlayerContractOption.Team;
                        }
                        else if (ps.Value.Contract.Option == PlayerContractOption.Team
                                 || ps.Value.Contract.Option == PlayerContractOption.Player)
                        {
                            ps.Value.Contract.Option = PlayerContractOption.None;
                        }
                        try
                        {
                            ps.Value.Contract.ContractSalaryPerYear.RemoveAt(0);
                        }
                        catch (ArgumentOutOfRangeException)
                        {
                        }
                        ps.Value.CalcAvg();
                    }

                    populateSeasonCombo();
                    SQLiteIO.SaveSeasonToDatabase(CurrentDB, TST, TSTOpp, PST, CurSeason, CurSeason);
                    ChangeSeason(CurSeason);
                    Tf = new Timeframe(CurSeason);
                    IsEnabled = false;
                    await UpdateAllData();
                    UpdateStatus("New season started. Database saved.");
                    IsEnabled = true;
                }
            }
        }
        /// <summary>
        ///     Handles the Click event of the btnImport2K12 control. Asks the user for the folder containing the NBA 2K12 save (in the case
        ///     of the old method), or the REDitor-exported CSV files.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">
        ///     The <see cref="RoutedEventArgs" /> instance containing the event data.
        /// </param>
        private async void btnImport2K12_Click(object sender, RoutedEventArgs e)
        {
            if (String.IsNullOrEmpty(CurrentDB))
            {
                return;
            }

            if (CurSeason != SQLiteIO.GetMaxSeason(CurrentDB))
            {
                if (
                    MessageBox.Show(
                        "Note that the currently selected season isn't the latest one in the database. "
                        + "Are you sure you want to import into this season?",
                        "NBA Stats Tracker",
                        MessageBoxButton.YesNo,
                        MessageBoxImage.Question) != MessageBoxResult.Yes)
                {
                    return;
                }
            }

            if (Tf.IsBetween)
            {
                Tf = new Timeframe(CurSeason);
                await UpdateAllData();
            }

            var fbd = new FolderBrowserDialog
                {
                    Description = "Select folder with REDitor-exported CSVs",
                    ShowNewFolderButton = false,
                    SelectedPath = Tools.GetRegistrySetting("LastImportDir", "")
                };
            var dr = FolderBrowserLauncher.ShowFolderBrowser(fbd, this.GetIWin32Window());
            if (dr != System.Windows.Forms.DialogResult.OK)
            {
                return;
            }

            if (String.IsNullOrWhiteSpace(fbd.SelectedPath))
            {
                return;
            }

            Tools.SetRegistrySetting("LastImportDir", fbd.SelectedPath);

            IsEnabled = false;
            status.Content = "Please wait...";
            status.FontWeight = FontWeights.Bold;

            var result = await Task.Run(() => REDitor.ImportCurrentYear(ref TST, ref TSTOpp, ref PST, fbd.SelectedPath));

            IsEnabled = true;
            status.FontWeight = FontWeights.Normal;
            status.Content = "Ready";

            if (result != 0)
            {
                MessageBox.Show(
                    "Import failed! Please reload your database immediatelly to avoid saving corrupt data.",
                    "NBA Stats Tracker",
                    MessageBoxButton.OK,
                    MessageBoxImage.Error);
                return;
            }

            UpdateStatus("NBA 2K12/2K13 stats imported successfully! Please save the current season!");
        }
        /// <summary>Handles the Click event of the btnAdd control. Allows the user to add teams or players the database.</summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">
        ///     The <see cref="RoutedEventArgs" /> instance containing the event data.
        /// </param>
        private async void btnAdd_Click(object sender, RoutedEventArgs e)
        {
            if (String.IsNullOrEmpty(CurrentDB))
            {
                return;
            }
            if (Tf.IsBetween)
            {
                IsEnabled = false;
                Tf = new Timeframe(CurSeason);
                await UpdateAllData();
                IsEnabled = true;
            }

            AddInfo = "";
            var aw = new AddWindow(ref PST);
            aw.ShowDialog();

            if (!String.IsNullOrEmpty(AddInfo))
            {
                if (AddInfo != "$$NST Players Added")
                {
                    var parts = Tools.SplitLinesToArray(AddInfo);
                    var newTeams = parts.Where(s => !String.IsNullOrWhiteSpace(s)).ToList();

                    var oldlen = TST.Count;
                    if (SQLiteIO.IsTSTEmpty())
                    {
                        oldlen = 0;
                    }

                    for (var i = 0; i < newTeams.Count; i++)
                    {
                        if (TST.Count(pair => pair.Value.Name == newTeams[i]) == 1)
                        {
                            MessageBox.Show(
                                "There's a team with the name " + newTeams[i] + " already in the database so it won't be added again.");
                            continue;
                        }
                        var newid = oldlen + i;
                        TST[newid] = new TeamStats(newid, newTeams[i]);
                        TSTOpp[newid] = new TeamStats(newid, newTeams[i]);
                    }
                    await saveAndReloadSeason();
                    UpdateStatus("Teams were added, database saved.");
                }
                else
                {
                    await saveAndReloadSeason();
                    UpdateStatus("Players were added, database saved.");
                }
            }
        }
        /// <summary>Handles the SelectionChanged event of the cmbSeasonNum control. Changes the curSeason property accordingly.</summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">
        ///     The <see cref="SelectionChangedEventArgs" /> instance containing the event data.
        /// </param>
        private async void cmbSeasonNum_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cmbSeasonNum.SelectedIndex == -1)
            {
                return;
            }

            CurSeason = ((KeyValuePair<int, string>) (((cmbSeasonNum)).SelectedItem)).Key;

            if (CurSeason == Tf.SeasonNum && !Tf.IsBetween)
            {
                return;
            }

            Tf = new Timeframe(CurSeason);
            if (!LoadingSeason)
            {
                IsEnabled = false;
                await UpdateAllData();
                IsEnabled = true;
            }
        }
        /// <summary>Handles the Click event of the btnExport2K12 control. Exports the current team and player stats to an NBA 2K save.</summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">
        ///     The <see cref="RoutedEventArgs" /> instance containing the event data.
        /// </param>
        private async void btnExport2K12_Click(object sender, RoutedEventArgs e)
        {
            if (TST.Count != 30)
            {
                MessageBox.Show("You can't export a database that has less/more than 30 teams to an NBA 2K12 save.");
                return;
            }

            if (CurSeason != SQLiteIO.GetMaxSeason(CurrentDB))
            {
                if (
                    MessageBox.Show(
                        "Note that the currently selected season isn't the latest one in the database. "
                        + "Are you sure you want to export from this season?",
                        "NBA Stats Tracker",
                        MessageBoxButton.YesNo,
                        MessageBoxImage.Question) != MessageBoxResult.Yes)
                {
                    return;
                }
            }

            if (Tf.IsBetween)
            {
                Tf = new Timeframe(CurSeason);
                await UpdateAllData();
            }

            var fbd = new FolderBrowserDialog
                {
                    Description = "Select folder with REDitor-exported CSVs",
                    ShowNewFolderButton = false,
                    SelectedPath = Tools.GetRegistrySetting("LastExportDir", "")
                };
            var dr = FolderBrowserLauncher.ShowFolderBrowser(fbd, this.GetIWin32Window());

            if (dr != System.Windows.Forms.DialogResult.OK)
            {
                return;
            }

            if (String.IsNullOrWhiteSpace(fbd.SelectedPath))
            {
                return;
            }

            IsEnabled = false;

            Tools.SetRegistrySetting("LastExportDir", fbd.SelectedPath);

            if (mnuOptionsCompatibilityCheck.IsChecked)
            {
                var temptst = new Dictionary<int, TeamStats>();
                var temptstOpp = new Dictionary<int, TeamStats>();
                var temppst = new Dictionary<int, PlayerStats>();
                var result =
                    await Task.Run(() => REDitor.ImportCurrentYear(ref temptst, ref temptstOpp, ref temppst, fbd.SelectedPath, true));

                if (result != 0)
                {
                    MessageBox.Show("Export failed.");
                    IsEnabled = true;
                    return;
                }

                var incompatible = false;

                if (temptst.Count != TST.Count)
                {
                    incompatible = true;
                }
                else
                {
                    for (var i = 0; i < temptst.Count; i++)
                    {
                        if (temptst[i].Name != TST[i].Name)
                        {
                            incompatible = true;
                            break;
                        }

                        if ((!temptst[i].Record.SequenceEqual(TST[i].Record)) || (!temptst[i].PlRecord.SequenceEqual(TST[i].PlRecord)))
                        {
                            incompatible = true;
                            break;
                        }
                    }
                }

                if (incompatible)
                {
                    var r =
                        MessageBox.Show(
                            "The file currently loaded seems incompatible with the NBA 2K save you're trying to save into."
                            + "\nThis could be happening for a number of reasons:\n\n"
                            + "1. The file currently loaded isn't one that had stats imported to it from your 2K save.\n"
                            + "2. The Win/Loss record for one or more teams would be different after this procedure.\n\n"
                            + "If you're updating using a box score, then either you're not using the NST database you imported your stats\n"
                            + "into before the game, or you entered the box score incorrectly. Remember that you need to import your stats\n"
                            + "into a database right before the game starts, let the game end and save the Association, and then update the\n"
                            + "database using the box score. If you follow these steps correctly, you shouldn't get this message when you try\n"
                            + "to export the stats from the database to your 2K save.\n\n"
                            + "Are you sure you want to continue? SAVE CORRUPTION MAY OCCUR, AND I WON'T BE HELD LIABLE FOR IT. ALWAYS KEEP BACKUPS.",
                            "NBA Stats Tracker",
                            MessageBoxButton.YesNo,
                            MessageBoxImage.Warning);

                    if (r == MessageBoxResult.No)
                    {
                        IsEnabled = true;
                        return;
                    }
                }
            }

            var eresult = REDitor.ExportCurrentYear(TST, PST, fbd.SelectedPath, mnuOptionsExportTeamsOnly.IsChecked);

            IsEnabled = true;

            if (eresult != 0)
            {
                MessageBox.Show("Export failed.");
                return;
            }
            UpdateStatus("Exported to " + fbd.SelectedPath + " successfully!");
        }
 /// <summary>
 ///     Handles the Click event of the btnSaveCurrentSeason control.
 ///     Saves the current season.
 /// </summary>
 /// <param name="sender">The source of the event.</param>
 /// <param name="e">
 ///     The <see cref="RoutedEventArgs" /> instance containing the event data.
 /// </param>
 private void btnSaveCurrentSeason_Click(object sender, RoutedEventArgs e)
 {
     IsEnabled = false;
     StartProgressWatchTimer();
     ProgressHelper.Progress = new ProgressInfo(0, "Saving database...");
     if (Tf.IsBetween)
     {
         Tf = new Timeframe(CurSeason);
         UpdateAllData()
             .ContinueWith(
                 t => SQLiteIO.SaveSeasonToDatabase(CurrentDB, TST, TSTOpp, PST, CurSeason, SQLiteIO.GetMaxSeason(CurrentDB)))
             .ContinueWith(t => UpdateAllData(true))
             .ContinueWith(t => finishSavingSeason(), UIScheduler)
             .FailFastOnException(UIScheduler);
     }
     else
     {
         Task.Factory.StartNew(
             () => SQLiteIO.SaveSeasonToDatabase(CurrentDB, TST, TSTOpp, PST, CurSeason, SQLiteIO.GetMaxSeason(CurrentDB)))
             .ContinueWith(t => UpdateAllData(true))
             .ContinueWith(t => finishSavingSeason(), UIScheduler)
             .FailFastOnException(UIScheduler);
     }
 }
        /// <summary>
        ///     Handles the Click event of the btnImport2K12 control.
        ///     Asks the user for the folder containing the NBA 2K12 save (in the case of the old method), or the REDitor-exported CSV files.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">
        ///     The <see cref="RoutedEventArgs" /> instance containing the event data.
        /// </param>
        private void btnImport2K12_Click(object sender, RoutedEventArgs e)
        {
            if (String.IsNullOrEmpty(CurrentDB))
            {
                return;
            }

            if (CurSeason != SQLiteIO.GetMaxSeason(CurrentDB))
            {
                if (
                    MessageBox.Show(
                        "Note that the currently selected season isn't the latest one in the database. " +
                        "Are you sure you want to import into this season?", "NBA Stats Tracker", MessageBoxButton.YesNo,
                        MessageBoxImage.Question) != MessageBoxResult.Yes)
                {
                    return;
                }
            }

            if (Tf.IsBetween)
            {
                Tf = new Timeframe(CurSeason);
                UpdateAllData();
            }

            var fbd = new FolderBrowserDialog
                {
                    Description = "Select folder with REDitor-exported CSVs",
                    ShowNewFolderButton = false,
                    SelectedPath = Misc.GetRegistrySetting("LastImportDir", "")
                };
            DialogResult dr = fbd.ShowDialog(this.GetIWin32Window());

            if (dr != System.Windows.Forms.DialogResult.OK)
            {
                return;
            }

            if (fbd.SelectedPath == "")
            {
                return;
            }

            Misc.SetRegistrySetting("LastImportDir", fbd.SelectedPath);

            int result = REDitor.ImportAll(ref TST, ref TSTOpp, ref PST, fbd.SelectedPath);

            if (result != 0)
            {
                MessageBox.Show("Import failed! Please reload your database immediatelly to avoid saving corrupt data.",
                                "NBA Stats Tracker", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            UpdateStatus("NBA 2K12 stats imported successfully! Verify that you want this by saving the current season.");
        }