using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace AdvertsingProfitControl
{
    public partial class NewModifyRecord : Form
    {
        private static readonly FrmLogConsole LogConsole = FrmLogConsole.GetStaticInstance;
        //Create an array that contains all the ad items from the database.
        private readonly List<string> _adItemCollection;
        //This object contains all the unused ad items.
        private AutoCompleteStringCollection _trimmedAdItemCollection = new AutoCompleteStringCollection();
        //Contains all the ad specials that are in the database (i.e. "Daily Coupons").
        private readonly AutoCompleteStringCollection _adSpecialList;
        //This object contains all the suppliers that were found in the database.
        private readonly AutoCompleteStringCollection _supplierCollection;
        //This array keeps track of the number of times an Ad Item is used, if used once then it may only be used AFTER an AdSpecialRow and only once after that.
        //Once an item has been used twice, it will not appear again in the AutoCompleteSuggestions.
        //The structure of the used ad item list is as follows:
        //List(0) is section one and List(1) is section two. Section one is not ad special and section two is.
        private readonly List<string>[] _usedAdItems = new List<string>[2];
        //This string keeps track of the last ad item used. This item can then be used to safely remove an ad item from the list of used items.
        //Used in the OnCellValidating event to store the last ad item used in the event that the user changes a row that already exists.
        private string _beginningCellValue = "";
        //Flag showing whether or not the AdSpecialRow has been made in this session.
        private int _adSpecialIndex = -1;
        private readonly AdvertisingProfitControlTableHelper _tableHelperFunctions = new AdvertisingProfitControlTableHelper();
        //Represents the date that is being modified, if this changes then the form needs to be cleared and refilled with the new date.
        private DateTime _currentActiveDate;
        //
        private bool _isFormDirty;

        public NewModifyRecord(DateTime date)
        {
            InitializeComponent();           
            //Start by grabbing all the AdItems and putting them into memory.
            var databaseTracker = new DatabaseTracker();
            var databaseReader = new DatabaseReader();
            weekEndingCalendar.BoldedDates = databaseReader.RetrieveDates(databaseTracker.DatabaseConnectionString).ToArray();
            weekEndingCalendar.SelectionStart = date;
            weekEndingCalendar.DateChanged += ValidateDateChanged;
            _currentActiveDate = date;
            Text = @"Modify Record (Current Record: " + date.ToString("d") + @")";
            //next pull all the ad items into memory.
            _adItemCollection = databaseReader.GetAdItemsSuggestionList(databaseTracker.DatabaseConnectionString);
            //Now pull all the suppliers and the ad special list into memory.
            _supplierCollection = databaseReader.GetSupplierSuggestionList(databaseTracker.DatabaseConnectionString);
            _adSpecialList = databaseReader.RetrieveAdSpecialList(databaseTracker.DatabaseConnectionString);
            //Initialize the used ad item collection.
            _usedAdItems[0] = new List<string>();
            _usedAdItems[1] = new List<string>();
            //Assign the events for the comments text box and display the remaining character count for the user.
            commentsTextBox.TextChanged += DisplayRemainingCommentCharacterCount;
            commentsGroupBox.Text = @"Comments (Characters Remaining: " + commentsTextBox.MaxLength + @")";
            //Setup the events for that the Projected and Actual Sales DataGridViews will share.
            //Events are assigned with regard to which event gets triggered first and so on..
            //Hook the row add event so we can paint a row number in the header cell of the row.
            projectionsDataGridView.RowsAdded += DisplayRowNumbers;
            inventoryDataGridView.RowsAdded += DisplayRowNumbers;
            actualSalesDataGridView.RowsAdded += DisplayRowNumbers;
            //Assign all the tables to store the cell's contents on enter so changes (if any) can be detected and flagged (marked as dirty).
            projectionsDataGridView.CellEnter += StoreBeginningCellValue;
            inventoryDataGridView.CellEnter += StoreBeginningCellValue;
            actualSalesDataGridView.CellEnter += StoreBeginningCellValue;
            //Update the contents of the used as item list on row leave.
            projectionsDataGridView.RowLeave += UpdateUsedAdItemCollectionOnRowLeave;
            inventoryDataGridView.RowLeave += UpdateUsedAdItemCollectionOnRowLeave;
            actualSalesDataGridView.RowLeave += UpdateUsedAdItemCollectionOnRowLeave;
            //Validate, clean and format the contents of the cell that fires the cell validating event.
            projectionsDataGridView.CellValidating += ValidateSalesDataGridViewCellContents;
            inventoryDataGridView.CellValidating += ValidateInventoryCellContents;
            actualSalesDataGridView.CellValidating += ValidateSalesDataGridViewCellContents;
            //Validate that the row the user is trying to leave is legal (has at least an ad item entered) and prevent the user from leaving the row is its not.
            projectionsDataGridView.RowValidating += ValidateProjectedRow;
            inventoryDataGridView.RowValidating += ValidateInventoryRow;
            actualSalesDataGridView.RowValidating += ValidateActualSalesRow;
            //Update the used ad item collection by removing the contents of the ad item column when a row is deleted.
            projectionsDataGridView.UserDeletingRow += UpdateUsedAdItemCollectionOnRowRemoving;
            inventoryDataGridView.UserDeletingRow += UpdateUsedAdItemCollectionOnRowRemoving;
            actualSalesDataGridView.UserDeletingRow += UpdateUsedAdItemCollectionOnRowRemoving;
            //Once a row has been removed update the other tables keep them uniform.
            projectionsDataGridView.RowsRemoved += ProjectionRowRemoved;
            inventoryDataGridView.RowsRemoved += InventoryRowRemoved;
            actualSalesDataGridView.RowsRemoved += ActualSalesRowRemoved;
            //Grab the underlying text box object in the ad item cell, and build an auto complete list for the user.
            projectionsDataGridView.EditingControlShowing += DisplayAutoCompleteOnEditingControlShowing;
            inventoryDataGridView.EditingControlShowing += DisplayAutoCompleteOnEditingControlShowing;
            actualSalesDataGridView.EditingControlShowing += DisplayAutoCompleteOnEditingControlShowing;
            //After all events have been set, construct the DataGridVeiws for use.
            ConstructApcDataGridViews();
            //Set-up events for the Invoice table.
            invoicesDataGridView.CellEnter += StoreBeginningCellValue;
            //Validate that the row the user is trying to leave is legal (has at least an ad item entered) and prevent the user from leaving the row is its not.
            invoicesDataGridView.RowValidating += ValidateInvoiceRow;
            //Validate, clean and format the contents of the cell that fires the cell validating event.
            invoicesDataGridView.CellValidating += ValidateInvoicesCellContents;
            //Grab the underlying text box object in the ad item cell, and build an auto complete list for the user.
            invoicesDataGridView.EditingControlShowing += DisplaySupplierAutoComleteOnEditingShadowControl;
            //Subscribe the method to allow the user to delete saved rows from the Invoices table.
            invoicesDataGridView.UserDeletingRow += UpdateInvoicesOnRowDeleting;
            //Finally build the last DataGridView for the form.
            ConstructInvoicesDataGridView();//No weekly sales table is nice.
            //Subscribe the comments text box to check if changes have been made on leave.
            commentsTextBox.Enter += StoreBeginningTextBoxValue;
            commentsTextBox.KeyDown += CheckForKeyCommand;
            commentsTextBox.Leave += CheckForTextChangeOnLeave;
            //Subscribe the weekly sales text boxes to validation, update required checks and auto-complete methods.
            sundayWeeklySalesTextBox.Enter += StoreBeginningTextBoxValue;
            sundayWeeklySalesTextBox.Validating += ValidateWeeklySales;
            mondayWeeklySalesTextBox.Enter += StoreBeginningTextBoxValue;
            mondayWeeklySalesTextBox.Validating += ValidateWeeklySales;
            tuesdayWeeklySalesTextBox.Enter += StoreBeginningTextBoxValue;
            tuesdayWeeklySalesTextBox.Validating += ValidateWeeklySales;
            wednesdayWeeklySalesTextBox.Enter += StoreBeginningTextBoxValue;
            wednesdayWeeklySalesTextBox.Validating += ValidateWeeklySales;
            thursdayWeeklySalesTextBox.Enter += StoreBeginningTextBoxValue;
            thursdayWeeklySalesTextBox.Validating += ValidateWeeklySales;
            fridayWeeklySalesTextBox.Enter += StoreBeginningTextBoxValue;
            fridayWeeklySalesTextBox.Validating += ValidateWeeklySales;
            saturdayWeeklySalesTextBox.Enter += StoreBeginningTextBoxValue;
            saturdayWeeklySalesTextBox.Validating += ValidateWeeklySales;
            totalWeeklySalesTextBox.Enter += StoreBeginningTextBoxValue;
            totalWeeklySalesTextBox.Validating += ValidateWeeklySales;
            //Subscribe the taxable text boxes to validation and update events.
            sundayTaxableTextBox.Enter += StoreBeginningTextBoxValue;
            sundayTaxableTextBox.Validating += ValidateTaxableFields;
            mondayTaxableTextBox.Enter += StoreBeginningTextBoxValue;
            mondayTaxableTextBox.Validating += ValidateTaxableFields;
            tuesdayTaxableTextBox.Enter += StoreBeginningTextBoxValue;
            tuesdayTaxableTextBox.Validating += ValidateTaxableFields;
            wednesdayTaxableTextBox.Enter += StoreBeginningTextBoxValue;
            wednesdayTaxableTextBox.Validating += ValidateTaxableFields;
            thursdayTaxableTextBox.Enter += StoreBeginningTextBoxValue;
            thursdayTaxableTextBox.Validating += ValidateTaxableFields;
            fridayTaxableTextBox.Enter += StoreBeginningTextBoxValue;
            fridayTaxableTextBox.Validating += ValidateTaxableFields;
            saturdayTaxableTextBox.Enter += StoreBeginningTextBoxValue;
            saturdayTaxableTextBox.Validating += ValidateTaxableFields;
            totalTaxableTextBox.Enter += StoreBeginningTextBoxValue;
            totalTaxableTextBox.Validating += ValidateTaxableFields;
            //Subscribe the Cost Analysis text boxes to the validation and update events.
            salesPerManHourTextBox.Enter += StoreBeginningTextBoxValue;
            salesPerManHourTextBox.Validating += ValidateCostAnalysisValues;
            salaryPercentageTextBox.Enter += StoreBeginningTextBoxValue;
            salaryPercentageTextBox.Validating += ValidateCostAnalysisValues;
            salaryDollarsTextBox.Enter += StoreBeginningTextBoxValue;
            salaryDollarsTextBox.Validating += ValidateCostAnalysisValues;
            suppliesTextBox.Enter += StoreBeginningTextBoxValue;
            suppliesTextBox.Validating += ValidateCostAnalysisValues;
            LoadDate(date);
        }

        public sealed override string Text
        {
            get { return base.Text; }
            set { base.Text = value; }
        }

        #region Global Event Handlers

        /// <summary>
        /// Stores the beginning value in a text box into the _beginningCellValue field.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void StoreBeginningTextBoxValue(object sender, EventArgs e)
        {
            var textBox = (TextBox)sender;
            _beginningCellValue = textBox.Text;
        }

        #endregion

        #region Invoice Table Events

        /// <summary>
        /// Event Used: RowValidating
        /// Validates that the row has required information, namely an invoice date, number and supplier.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void ValidateInvoiceRow(object sender, DataGridViewCellCancelEventArgs e)
        {
            var dataGridView = (DataGridView)sender;
            if (dataGridView.Rows[e.RowIndex].IsNewRow) return;
            DateTime dateTime;
            //Check to make sure the Invoice Date, Invoice Number and the Supplier values are set.
            if (dataGridView.Rows[e.RowIndex].Cells[(int)InvoiceTableColumns.InvoiceDate].EditedFormattedValue.ToString() == "" || !DateTime.TryParse(dataGridView.Rows[e.RowIndex].Cells[(int)InvoiceTableColumns.InvoiceDate].EditedFormattedValue.ToString(), out dateTime))
            {
                dataGridView.Rows[e.RowIndex].HeaderCell.Style.BackColor = ApplicationColors.RowError;
                MessageBox.Show(@"An invoice date must be specified.", @"Invalid Invoice Date", MessageBoxButtons.OK, MessageBoxIcon.Error);
                e.Cancel = true;
                dataGridView.CurrentCell = dataGridView.Rows[e.RowIndex].Cells[(int)InvoiceTableColumns.InvoiceDate];
                return;
            }

            if (dataGridView.Rows[e.RowIndex].Cells[(int)InvoiceTableColumns.Supplier].EditedFormattedValue.ToString() == "")
            {
                dataGridView.Rows[e.RowIndex].HeaderCell.Style.BackColor = ApplicationColors.RowError;
                MessageBox.Show(@"A supplier must be specified.", @"Invalid Supplier", MessageBoxButtons.OK, MessageBoxIcon.Error);
                e.Cancel = true;
                dataGridView.CurrentCell = dataGridView.Rows[e.RowIndex].Cells[(int)InvoiceTableColumns.Supplier];
                return;
            }

            if (
                dataGridView.Rows[e.RowIndex].Cells[(int)InvoiceTableColumns.InvoiceNumber].EditedFormattedValue
                    .ToString() == "")
            {
                dataGridView.Rows[e.RowIndex].HeaderCell.Style.BackColor = ApplicationColors.RowError;
                MessageBox.Show(@"An invoice number must be specified.", @"Invalid Invoice Number", MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
                dataGridView.CurrentCell = dataGridView.Rows[e.RowIndex].Cells[(int)InvoiceTableColumns.InvoiceNumber];
                e.Cancel = true;
            }
        }

        /// <summary>
        /// Event Used: CellValidating
        /// Verifies the contents of the invoice table's cells. Also applies formating where needed.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ValidateInvoicesCellContents(object sender, DataGridViewCellValidatingEventArgs e)
        {
            //Grab the DataGirdView that fired the event and make it into a local variable.
            var dataGridView = (DataGridView)sender;
            var userInput = dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].EditedFormattedValue.ToString().Trim();
            var textInfo = new CultureInfo("en-US", false).TextInfo;
            //Check for isNewRow if it is, return no need to check it for anything.
            if (dataGridView.Rows[e.RowIndex].IsNewRow)
            {
                return;
            }
            //Mark the row as dirty assuming the user made changes
            if (userInput != _beginningCellValue)
            {
                dataGridView.Rows[e.RowIndex].Cells[(int)InvoiceTableColumns.IsDirty].Value = true;
            }
            else
            {
                return;
            }
            //Check to see if we're in the invoice date column make sure the date is valid.
            switch (e.ColumnIndex)
            {
                case (int)InvoiceTableColumns.InvoiceDate:
                    //Clear any error text a cell has for this column.
                    dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].ErrorText = "";
                    if (userInput != "")
                    {
                        DateTime date;
                        //Try parsing the date to make sure its valid, otherwise clear it from the cell and inform the user.
                        if (DateTime.TryParse(userInput, out date))
                        {
                            dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = date.ToString("d");
                            dataGridView.Rows[e.RowIndex].HeaderCell.Style.BackColor = ApplicationColors.PendingEdit;
                            _isFormDirty = true;
                        }
                        else
                        {
                            MessageBox.Show(@"The date '" + userInput + @"' is not a valid date.", @"Invalid Date", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].ErrorText = "Invoice Date Must be in a Valid Format";
                            dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = "";
                        }
                    }
                    else
                    {
                        dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = "";
                        dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].ErrorText = "An Invoice Date is Required";
                    }
                    break;
                case (int)InvoiceTableColumns.InvoiceNumber:
                    //Clear any error text a cell has for this column.
                    dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].ErrorText = "";
                    if (userInput != "")
                    {
                        long parsedNumber;
                        if (long.TryParse(userInput, out parsedNumber))
                        {
                            dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = parsedNumber;
                            dataGridView.Rows[e.RowIndex].HeaderCell.Style.BackColor = ApplicationColors.PendingEdit;
                            _isFormDirty = true;
                        }
                        else
                        {
                            MessageBox.Show(@"The invoice number must be a numeric value.", @"Non Numeric Invoice Number", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = "";
                            dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].ErrorText = "Invoice Number Must be Numeric";
                        }
                    }
                    else
                    {
                        dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = "";
                        dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].ErrorText = "An Invoice Number is Required";
                    }
                    break;
                case (int)InvoiceTableColumns.Supplier:
                    //Clear any error text a cell has for this column.
                    dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].ErrorText = "";
                    if (userInput != "")
                    {
                        //TODO: Create a custom engine to do this.
                        //Pretty up the entered text since there is something here.
                        dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = textInfo.ToTitleCase(userInput);
                        dataGridView.Rows[e.RowIndex].HeaderCell.Style.BackColor = ApplicationColors.PendingEdit;
                        _isFormDirty = true;
                    }
                    else
                    {
                        dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = "";
                        dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].ErrorText = "A Supplier is Required";
                    }
                    break;
                case (int)InvoiceTableColumns.InvoiceNote:
                    dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = userInput;
                    dataGridView.Rows[e.RowIndex].HeaderCell.Style.BackColor = ApplicationColors.PendingEdit;
                    _isFormDirty = true;
                    break;
                default:
                    //Should only process the InvoiceNetAmountAtCost and InvoiceNetAmount columns.
                    if (e.ColumnIndex != (int)InvoiceTableColumns.Id &&
                        e.ColumnIndex < (int)InvoiceTableColumns.InvoiceNote)
                    {
                        dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].ErrorText = "";
                        //Now check to make sure the user input isn't null
                        //Math.Round(parsedNumber, 2).ToString("N", new CultureInfo("en-US"));
                        if (userInput != "")
                        {
                            double parsedNumber;
                            if (double.TryParse(userInput, out parsedNumber))
                            {
                                //Since the input is a number format it to show the cents and display it.
                                dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = Math.Round(parsedNumber, 2).ToString("N", new CultureInfo("en-US"));
                                dataGridView.Rows[e.RowIndex].HeaderCell.Style.BackColor = ApplicationColors.PendingEdit;
                                _isFormDirty = true;
                            }
                            else
                            {
                                dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = "";
                                dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].ErrorText = "Only Numeric Values Allowed.";
                            }
                        }
                    }
                    break;
            }
            dataGridView.RefreshEdit();
        }

        /// <summary>
        /// Event Used: EditingShadowControlShowing
        /// Adds an auto-complete list of suppliers to the Suppliers cell.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DisplaySupplierAutoComleteOnEditingShadowControl(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            var dataGridView = (DataGridView)sender;
            var autoText = e.Control as TextBox;
            if (autoText == null) return;
            if (!(e.Control is DataGridViewTextBoxEditingControl) || dataGridView.CurrentCell.ColumnIndex != (int)InvoiceTableColumns.Supplier) return;
            autoText.AutoCompleteMode = AutoCompleteMode.Suggest;
            autoText.AutoCompleteSource = AutoCompleteSource.CustomSource;
            autoText.AutoCompleteCustomSource = _supplierCollection;
        }

        /// <summary>
        /// Checks to see if the row that the user is attempting to delete has been saved to the database.
        /// If so, this method will try to delete the record, failing that it will cancel the row deletion.
        /// </summary>
        /// <param name="sender">Invoice table.</param>
        /// <param name="e"></param>
        private void UpdateInvoicesOnRowDeleting(object sender, DataGridViewRowCancelEventArgs e)
        {
            var rowIndex = e.Row.Index;
            //See if there is an ID number in the ID column.
            if (invoicesDataGridView.Rows[rowIndex].Cells[(int)InvoiceTableColumns.Id].EditedFormattedValue.ToString() == "") return;
            //Ask the user to make damn sure they want to remove this record.
            var result = MessageBox.Show(@"Deleting this row will remove it from the database permanently. Do you wish to continue?", @"Remove Invoice Number " + invoicesDataGridView.Rows[rowIndex].Cells[(int)InvoiceTableColumns.InvoiceNumber].EditedFormattedValue, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (result == DialogResult.Yes)
            {
                //If so create the database interaction objects.
                var dbTracker = new DatabaseTracker();
                var dbWriter = new DatabaseWriter(dbTracker.DatabaseConnectionString);
                var id =
                    int.Parse(
                        invoicesDataGridView.Rows[rowIndex].Cells[(int)InvoiceTableColumns.Id].EditedFormattedValue
                            .ToString());
                if (dbWriter.DeleteInvoiceRow(id))
                {
                    informationLabel.Text = @"Successfully removed row " + (rowIndex + 1) + @" from the database.";
                }
                else
                {
                    //The operation failed.
                    errorLabel.Text = @"Failed to delete row " + (rowIndex + 1) + @" from invoices.";
                    e.Cancel = true;
                }
            }
            else
            {
                e.Cancel = true;
            }
        }

        #endregion

        #region APC DataGridView Events

        /// <summary>
        /// Event Used: RowsAdded
        /// Draws the row number in the row's cell header whenever a row is added.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void DisplayRowNumbers(object sender, DataGridViewRowsAddedEventArgs e)
        {
            var table = ((DataGridView)sender);
            table.Rows[e.RowIndex].HeaderCell.Value = (e.RowIndex + 1).ToString();
        }

        /// <summary>
        /// Event Used: CellEnter
        /// Stores the initial contents of the cell being entered to be compared later 
        /// to see if the user has made any changes (IsDirty).
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void StoreBeginningCellValue(object sender, DataGridViewCellEventArgs e)
        {
            var dataGridView = (DataGridView)sender;
            _beginningCellValue = dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].EditedFormattedValue.ToString();
        }

        /// <summary>
        /// Event Used: OnRowLeave
        /// Adds the ad items to the used ad item collection if they are not already in the collection.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UpdateUsedAdItemCollectionOnRowLeave(object sender, DataGridViewCellEventArgs e)
        {
            var dataGridView = ((DataGridView)sender);
            if (dataGridView.Rows[e.RowIndex].IsNewRow) { return; } //Return if the row is a new row as nothing needs to be done here.
            int adItemIndex;

            switch (dataGridView.Name)
            {
                case "projectionsDataGridView":
                    adItemIndex = (int)SalesTableColumns.AdItem;
                    break;
                case "actualSalesDataGridView":
                    adItemIndex = (int)SalesTableColumns.AdItem;
                    break;
                default:
                    adItemIndex = (int)InventoryTableColumns.AdItem;
                    break;
            }
            var userInput = dataGridView.Rows[e.RowIndex].Cells[adItemIndex].EditedFormattedValue.ToString();
            //Paint the rows to identify what group they belong to.
            _tableHelperFunctions.PaintRowGroupsFromIndex(e.RowIndex, dataGridView);
            //Add in used Ad Items to the list.
            if (userInput == "") return;
            //Clear the old ad item out of the used ad item collection.
            var parser = new RowParsing();
            if (parser.GetRowAttribute(dataGridView.Rows[e.RowIndex]) == RowAttribute.AdSpecialRow)
            {
                _adSpecialIndex = e.RowIndex;
                return;
            }
            //Section one (1) detected.
            if (_adSpecialIndex == -1 || e.RowIndex < _adSpecialIndex)
            {
                if (_usedAdItems[0].Contains(userInput)) return;
                _usedAdItems[0].Add(userInput);
                LogConsole.WriteToLog(FrmLogConsole.Level.Debug, "Adding \"" + userInput + "\" to section one (1).");
            }
            //Section two (2) detected.
            else
            {
                if (_usedAdItems[1].Contains(userInput)) return;
                _usedAdItems[1].Add(userInput);
                LogConsole.WriteToLog(FrmLogConsole.Level.Debug, "Adding \"" + userInput + "\" to section two (2).");
            }
        }

        /// <summary>
        /// Event Used: OnEditingControlShowing
        /// Configures the auto complete collection and how it will be shown to the user. This method detects the section,
        /// either one (1) or two (2), based on the gAdSpecialIndex and removes items from the auto complete accordingly.
        /// Just a measure to help reduce redundancy in the tables.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DisplayAutoCompleteOnEditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            var dataGridView = ((DataGridView)sender);
            var autoText = e.Control as TextBox;
            //Get the index of the ad item column
            const int adItemIndex = (int)SalesTableColumns.AdItem;
            if (e.Control is DataGridViewTextBoxEditingControl && dataGridView.CurrentCell.ColumnIndex == adItemIndex)
            {
                //Create a copy of the main ad item list that can be freely manipulated.
                var customAutoComplete = new AutoCompleteStringCollection();
                var customList = _adItemCollection.ToList();

                //IF the current row is less than the AdSpecialRow, remove all used items with the section 1 attribute.
                if (_adSpecialIndex == -1 || dataGridView.CurrentCell.RowIndex < _adSpecialIndex)
                {
                    foreach (var adItem in _usedAdItems[0])
                    {
                        customList.RemoveAll(w => w.Equals(adItem, StringComparison.OrdinalIgnoreCase));
                    }
                }
                //Occurs AFTER the AdSpecial row.
                else if (dataGridView.CurrentCell.RowIndex > _adSpecialIndex)
                {
                    foreach (var adItem in _usedAdItems[1])
                    {
                        customList.RemoveAll(w => w.Equals(adItem, StringComparison.OrdinalIgnoreCase));
                    }
                }
                foreach (var item in customList)
                {
                    customAutoComplete.Add(item);
                }
                autoText.KeyDown += ChangeAutoCompleteListOnKeyCombo;
                _trimmedAdItemCollection = customAutoComplete; //Make a temporary copy of the list for use with the TextBox event handler.
                autoText.AutoCompleteMode = AutoCompleteMode.Suggest;
                autoText.AutoCompleteSource = AutoCompleteSource.CustomSource;
                autoText.AutoCompleteCustomSource = customAutoComplete;
            }
            else if (e.Control is DataGridViewTextBoxEditingControl && dataGridView.CurrentCell.ColumnIndex != adItemIndex)
            {
                autoText.AutoCompleteMode = AutoCompleteMode.None;
            }
        }

        /// <summary>
        /// Event Used: UserDeleteingRow
        /// This function is responsible for removing ad Items from the gUsedAdItem array; this must be done during the row removing
        /// event handler so the data in the row can be grabbed and used.
        /// </summary>
        /// <param name="sender">The DataGridView that fired the event.</param>
        /// <param name="e">Parameters, mainly allowing for canceling the event.</param>
        private void UpdateUsedAdItemCollectionOnRowRemoving(object sender, CancelEventArgs e)
        {
            //Create an object that represents the DataGridView that fired the event.
            var dataGridView = (DataGridView)sender;
            if (dataGridView.CurrentRow == null) return;
            //Create the database writer object so rows that are in the database can be deleted.
            var dbTracker = new DatabaseTracker();
            var dbWriter = new DatabaseWriter(dbTracker.DatabaseConnectionString);
            var currentRowIndex = dataGridView.CurrentRow.Index;
            //Remove the ad item from the gUsedAdItem collection, if it exists.
            if (_adSpecialIndex == -1)
            {
                //If the ID number is set, i.e. not equal to null then attempt to remove it from the database.
                if (dataGridView.Rows[currentRowIndex].Cells[0].EditedFormattedValue.ToString() != "")
                {
                    var result = MessageBox.Show(@"Removing this row will permanently delete this record from the database. Do you wish to continue?", @"Remove " + dataGridView.Rows[currentRowIndex].Cells[1].EditedFormattedValue, MessageBoxButtons.YesNo);
                    if (result == DialogResult.Yes)
                    {
                        //Attempt to delete the row from the database by its ID number.
                        var projectionsRowId = int.Parse(projectionsDataGridView.Rows[currentRowIndex].Cells[(int)SalesTableColumns.Id].EditedFormattedValue.ToString());
                        var inventoryRowId = int.Parse(inventoryDataGridView.Rows[currentRowIndex].Cells[(int)SalesTableColumns.Id].EditedFormattedValue.ToString());
                        var actualSalesRowId = int.Parse(actualSalesDataGridView.Rows[currentRowIndex].Cells[(int)SalesTableColumns.Id].EditedFormattedValue.ToString());
                        if (dbWriter.DeleteApcRow(projectionsRowId, inventoryRowId, actualSalesRowId))
                        {
                            informationLabel.Text = @"Successfully removed row " + (currentRowIndex + 1) + @" from the database.";
                        }
                        else
                        {
                            //If the removing failed cancel the row deletion in the DataGridView.
                            e.Cancel = true;
                            MessageBox.Show(@"Failed to delete " + dataGridView.Rows[currentRowIndex].Cells[1].EditedFormattedValue +
                                @" from the database.", @"Failed to Update Database");
                            return;
                        }
                    }
                }
                //If the ad item entered in the first cell is in the gUsedAdItems collection, then remove it from there.
                _usedAdItems[0].Remove(dataGridView.Rows[currentRowIndex].Cells[(int)SalesTableColumns.AdItem].EditedFormattedValue.ToString());
            }
            else if (currentRowIndex < _adSpecialIndex)
            {
                //If the ID number is set, i.e. not equal to null then attempt to remove it from the database.
                if (dataGridView.Rows[currentRowIndex].Cells[0].EditedFormattedValue.ToString() != "")
                {
                    var result = MessageBox.Show(@"Removing this row will permanently delete this record from the database. Do you wish to continue?", @"Remove " + dataGridView.Rows[currentRowIndex].Cells[1].EditedFormattedValue, MessageBoxButtons.YesNo);
                    if (result == DialogResult.Yes)
                    {
                        //Attempt to delete the row from the database by its ID number.
                        var projectionsRowId = int.Parse(projectionsDataGridView.Rows[currentRowIndex].Cells[(int)SalesTableColumns.Id].EditedFormattedValue.ToString());
                        var inventoryRowId = int.Parse(inventoryDataGridView.Rows[currentRowIndex].Cells[(int)SalesTableColumns.Id].EditedFormattedValue.ToString());
                        var actualSalesRowId = int.Parse(actualSalesDataGridView.Rows[currentRowIndex].Cells[(int)SalesTableColumns.Id].EditedFormattedValue.ToString());
                        if (dbWriter.DeleteApcRow(projectionsRowId, inventoryRowId, actualSalesRowId))
                        {
                            informationLabel.Text = @"Successfully removed row " + (currentRowIndex + 1) + @" from the database.";
                        }
                        else
                        {
                            //If the removing failed cancel the row deletion in the DataGridView.
                            e.Cancel = true;
                            MessageBox.Show(@"Failed to delete " + dataGridView.Rows[currentRowIndex].Cells[1].EditedFormattedValue +
                                @" from the database.", @"Failed to Update Database");
                            return;
                        }
                    }
                }
                //If the ad item entered in the first cell is in the gUsedAdItems collection, then remove it from there.
                _usedAdItems[0].Remove(dataGridView.Rows[currentRowIndex].Cells[(int)SalesTableColumns.AdItem].EditedFormattedValue.ToString());
                //Also decrement the _adSpecialIndex so that it points to the correct row.
                _adSpecialIndex--;
            }
            else if (currentRowIndex > _adSpecialIndex)
            {
                //If the ID number is set, i.e. not equal to null then attempt to remove it from the database.
                if (dataGridView.Rows[currentRowIndex].Cells[0].EditedFormattedValue.ToString() != "")
                {
                    var result = MessageBox.Show(@"Removing this row will permanently delete this record from the database. Do you wish to continue?", @"Remove " + dataGridView.Rows[currentRowIndex].Cells[1].EditedFormattedValue, MessageBoxButtons.YesNo);
                    if (result == DialogResult.Yes)
                    {
                        //Attempt to delete the row from the database by its ID number.
                        var projectionsRowId = int.Parse(projectionsDataGridView.Rows[currentRowIndex].Cells[(int)SalesTableColumns.Id].EditedFormattedValue.ToString());
                        var inventoryRowId = int.Parse(inventoryDataGridView.Rows[currentRowIndex].Cells[(int)SalesTableColumns.Id].EditedFormattedValue.ToString());
                        var actualSalesRowId = int.Parse(actualSalesDataGridView.Rows[currentRowIndex].Cells[(int)SalesTableColumns.Id].EditedFormattedValue.ToString());
                        if (dbWriter.DeleteApcRow(projectionsRowId, inventoryRowId, actualSalesRowId))
                        {
                            informationLabel.Text = @"Successfully removed row " + (currentRowIndex + 1) + @" from the database.";
                        }
                        else
                        {
                            //If the removing failed cancel the row deletion in the DataGridView.
                            e.Cancel = true;
                            MessageBox.Show(@"Failed to delete " + dataGridView.Rows[currentRowIndex].Cells[1].EditedFormattedValue +
                                @" from the database.", @"Failed to Update Database");
                            return;
                        }
                    }
                }
                //If the ad item entered in the first cell is in the gUsedAdItems collection, then remove it from there.
                _usedAdItems[1].Remove(dataGridView.Rows[currentRowIndex].Cells[(int)SalesTableColumns.AdItem].EditedFormattedValue.ToString());
            }
            else if (currentRowIndex == _adSpecialIndex)
            {
                //Handle removing the AdSpecial row.
                var result = MessageBox.Show(@"Deleting the Ad Special row will remove all rows beneath it. Do you wish to continue?", @"Clear " + dataGridView.Rows[currentRowIndex].Cells[1].EditedFormattedValue, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (result == DialogResult.Yes)
                {
                    //Clear all events that handle row removal from both DataGridViews.
                    //Projections table
                    projectionsDataGridView.RowsRemoved -= ProjectionRowRemoved;
                    projectionsDataGridView.UserDeletingRow -= UpdateUsedAdItemCollectionOnRowRemoving;
                    //Inventory table
                    inventoryDataGridView.RowsRemoved -= InventoryRowRemoved;
                    inventoryDataGridView.UserDeletingRow -= UpdateUsedAdItemCollectionOnRowRemoving;
                    //Actual Sales table
                    actualSalesDataGridView.RowsRemoved -= ActualSalesRowRemoved;
                    actualSalesDataGridView.UserDeletingRow -= UpdateUsedAdItemCollectionOnRowRemoving;
                    //Now for-each through each row that is underneath the Ad Special row.
                    for (var rowIndex = dataGridView.RowCount; currentRowIndex != rowIndex; rowIndex--)
                    {
                        if (projectionsDataGridView.RowCount == inventoryDataGridView.RowCount &&
                            projectionsDataGridView.RowCount == actualSalesDataGridView.RowCount)
                        {
                            if (dataGridView.Rows[currentRowIndex].Cells[(int)SalesTableColumns.Id].EditedFormattedValue.ToString() != "")
                            {
                                //Attempt to delete the row from the database by its ID number.
                                var projectionsRowId = int.Parse(projectionsDataGridView.Rows[currentRowIndex].Cells[(int)SalesTableColumns.Id].EditedFormattedValue.ToString());
                                var inventoryRowId = int.Parse(inventoryDataGridView.Rows[currentRowIndex].Cells[(int)SalesTableColumns.Id].EditedFormattedValue.ToString());
                                var actualSalesRowId = int.Parse(actualSalesDataGridView.Rows[currentRowIndex].Cells[(int)SalesTableColumns.Id].EditedFormattedValue.ToString());
                                if (dbWriter.DeleteApcRow(projectionsRowId, inventoryRowId, actualSalesRowId))
                                {
                                    informationLabel.Text += @"Successfully removed row " + (currentRowIndex + 1) + @" from the database." + Environment.NewLine;
                                }
                                else
                                {
                                    //If the removing failed cancel the row deletion in the DataGridView.
                                    e.Cancel = true;
                                    MessageBox.Show(@"Failed to delete " + dataGridView.Rows[currentRowIndex].Cells[1].EditedFormattedValue +
                                        @" from the database.", @"Failed to Update Database");
                                    return;
                                }
                            }
                        }
                        if (projectionsDataGridView.Rows[currentRowIndex].IsNewRow != true)
                        {
                            projectionsDataGridView.Rows.RemoveAt(currentRowIndex);
                        }
                        if (inventoryDataGridView.Rows[currentRowIndex].IsNewRow != true)
                        {
                            inventoryDataGridView.Rows.RemoveAt(currentRowIndex);
                        }
                        if (actualSalesDataGridView.Rows[currentRowIndex].IsNewRow != true)
                        {
                            actualSalesDataGridView.Rows.RemoveAt(currentRowIndex);
                        }
                        //If the ad item entered in the first cell is in the gUsedAdItems collection, then remove it from there.
                        _usedAdItems[1].Remove(dataGridView.Rows[currentRowIndex].Cells[(int)SalesTableColumns.AdItem].EditedFormattedValue.ToString());
                    }
                    //Re-enable all row removal events on both tables.
                    //Projections table
                    projectionsDataGridView.RowsRemoved += ProjectionRowRemoved;
                    projectionsDataGridView.UserDeletingRow += UpdateUsedAdItemCollectionOnRowRemoving;
                    //Inventory table
                    inventoryDataGridView.RowsRemoved += InventoryRowRemoved;
                    inventoryDataGridView.UserDeletingRow += UpdateUsedAdItemCollectionOnRowRemoving;
                    //Actual Sales table
                    actualSalesDataGridView.RowsRemoved += ActualSalesRowRemoved;
                    actualSalesDataGridView.UserDeletingRow += UpdateUsedAdItemCollectionOnRowRemoving;
                    //Reset the gAdSpecialIndex to -1.
                    _adSpecialIndex = -1;
                    e.Cancel = true; //Prevent the new row from being removed.
                }
                else
                {
                    e.Cancel = true;
                }
            }
        }

        private void ChangeAutoCompleteListOnKeyCombo(object sender, KeyEventArgs e)
        {
            var textBox = (TextBox)sender;
            informationLabel.Text = "";

            if (e.Modifiers == Keys.Alt && e.KeyCode == Keys.S)
            {
                if (_adSpecialIndex == -1)
                {
                    textBox.AutoCompleteCustomSource = _adSpecialList;
                    informationLabel.Text = @"Auto complete mode changed to Ad Special.";
                }
                else
                {
                    textBox.AutoCompleteCustomSource = _trimmedAdItemCollection;
                    informationLabel.Text = @"An Ad Special row already exists, auto complete mode\n can not be changed.";
                }
            }
            else if (e.Modifiers == Keys.Alt && e.KeyCode == Keys.A)
            {
                textBox.AutoCompleteCustomSource = _trimmedAdItemCollection;
                informationLabel.Text = @"Auto complete mode changed to Ad Items.";
            }
            e.Handled = false;
        }

        #endregion

        #region Sales DataGridView Events

        /// <summary>
        /// Event Used: CellValidating
        /// Validates the contents of a cell, before leaving it. If the contents
        /// are valid then the appropriate formatting is applied if needed.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ValidateSalesDataGridViewCellContents(object sender, DataGridViewCellValidatingEventArgs e)
        {
            //Grab the DataGirdView that fired the event and make it into a local variable.
            var dataGridView = (DataGridView)sender;
            var userInput = dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].EditedFormattedValue.ToString();
            //TODO: Write a custom parsing engine for detecting when bins are entered.
            var textInfo = new CultureInfo("en-US", false).TextInfo;
            //Check for isNewRow if it is, return no need to check it for anything.
            if (dataGridView.Rows[e.RowIndex].IsNewRow)
            {
                return;
            }

            if (userInput == _beginningCellValue)
            {
                return;
            }
            //Check to make sure we're not in the boolean fields or the ID field.
            if (e.ColumnIndex >= (int)SalesTableColumns.IsHeaderRow || e.ColumnIndex == (int)SalesTableColumns.Id)
            {
                return;
            }
            //Cell validating gets to handle updating the used ad item list since it handles cells on by one, instead by a whole row.
            if (userInput != _beginningCellValue && e.ColumnIndex == (int)SalesTableColumns.AdItem)
            {
                //The user is trying to change the ad special text to something else.
                if (e.RowIndex == _adSpecialIndex)
                {
                    var parser = new RowParsing();
                    if (parser.CheckForGroupKeyWord(userInput) == "NoGroupFound")
                    {
                        MessageBox.Show(
                            @"The Ad Special row's column one (1) cannot be changed. You must delete this row by clicking on the header cell and pressing 'Delete'.",
                            @"Invalid Operation on Ad Special Row", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = _beginningCellValue;
                        dataGridView.RefreshEdit();
                        return;
                    }
                    //Mark all ad special members as dirty since the user changed the ad special.
                    for (var index = _adSpecialIndex + 1; index < dataGridView.RowCount; index++)
                    {
                        //Add overflow protection
                        if (index < projectionsDataGridView.RowCount)
                        {
                            if (!projectionsDataGridView.Rows[index].IsNewRow)
                            {
                                projectionsDataGridView.Rows[index].Cells[(int)SalesTableColumns.IsDirty].Value = true;
                            }
                        }
                        if (index < actualSalesDataGridView.RowCount)
                        {
                            if (!actualSalesDataGridView.Rows[index].IsNewRow)
                            {
                                actualSalesDataGridView.Rows[index].Cells[(int)SalesTableColumns.IsDirty].Value = true;
                            }
                        }
                        if (index < inventoryDataGridView.RowCount)
                        {
                            if (!inventoryDataGridView.Rows[index].IsNewRow)
                            {
                                inventoryDataGridView.Rows[index].Cells[(int)InventoryTableColumns.IsDirty].Value = true;
                            }
                        }
                    }
                }
                _usedAdItems[_adSpecialIndex == -1 || e.RowIndex < _adSpecialIndex ? 0 : 1].Remove(_beginningCellValue);
                dataGridView.Rows[e.RowIndex].Cells[(int)SalesTableColumns.IsDirty].Value = true;
            }
            else if (userInput != _beginningCellValue)
            {
                dataGridView.Rows[e.RowIndex].Cells[(int)SalesTableColumns.IsDirty].Value = true;
                //Set the coloring for the header cell.
                dataGridView.Rows[e.RowIndex].HeaderCell.Style.BackColor = ApplicationColors.PendingEdit;
                _isFormDirty = true;
            }
            double parsedNumber;
            //Check to see if the current column is the ad item column.
            switch (e.ColumnIndex)
            {
                case (int)SalesTableColumns.AdItem: //Ad Item
                    //If there is text after all the whitespace has been cleared, clear the error text property regardless of whether or not it is set.
                    if (!string.IsNullOrEmpty(Regex.Replace(userInput, @"\s+", "")))
                    {
                        //Clear the error text since there is in fact an item entered.
                        dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].ErrorText = "";
                        //Send the ad item text through the formatting engine and assign the new value to the cell.
                        dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = TextFormat.FormatAdItemText(userInput);
                        var parser = new RowParsing();
                        if (parser.CheckForGroupKeyWord(userInput) == "NoGroupFound")
                        {
                            dataGridView.Rows[e.RowIndex].HeaderCell.Style.BackColor = ApplicationColors.PendingEdit;
                            _isFormDirty = true;
                        }
                        else
                        {
                            _adSpecialIndex = e.RowIndex;
                            //Since this is the ad special row don't give it any color coding.
                            dataGridView.Rows[e.RowIndex].HeaderCell.Style.BackColor = DefaultBackColor;
                        }
                        //Force a refresh so the cell's text updates and displays for the user.
                        dataGridView.RefreshEdit();
                        return;
                    }
                    //Otherwise, show an error.
                    dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].ErrorText = "Ad Item needed";
                    break;
                case (int)SalesTableColumns.Sold: //Sold
                    //This Reg-ex pattern will match any number followed by the word bin(s), to allow specifying the number of bins of product were ordered.
                    var inventoryStringCheck = new Regex(@"^[0-9]{1,2} \bbin(s){0,1}\b", RegexOptions.IgnoreCase);

                    if (
                        inventoryStringCheck.IsMatch(
                            dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].EditedFormattedValue.ToString()))
                    {
                        //IF a match has been found, then make sure the word 'bin(s)' is capitalized to keep things looking pretty.
                        dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = textInfo.ToTitleCase(userInput);
                        dataGridView.Rows[e.RowIndex].HeaderCell.Style.BackColor = ApplicationColors.PendingEdit;
                        _isFormDirty = true;
                        dataGridView.RefreshEdit();
                        return;
                    }
                    //Try parsing the text entered as a number and if that fails then break out and clear the value entered.
                    if (double.TryParse(userInput, out parsedNumber))
                    {
                        //Add the formatted value to the cell.
                        dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = Math.Round(parsedNumber, 2).ToString("N", new CultureInfo("en-US"));
                        dataGridView.Rows[e.RowIndex].HeaderCell.Style.BackColor = ApplicationColors.PendingEdit;
                        _isFormDirty = true;
                    }
                    else
                    {
                        if (userInput == "")
                        {
                            return;
                        }
                        MessageBox.Show(@"Non numeric characters in column " + (e.ColumnIndex + 1) + @" are not allowed.", @"Invalid Characters Detected");
                        dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = "";
                        dataGridView.RefreshEdit();
                        e.Cancel = true;
                        return;
                    }
                    break;
                case (int)SalesTableColumns.SalePrice:
                    //If the column is the "Sale Price" column try to parse the contents to a Double and apply number formatting to the contents.
                    //Check for the cost column to see if there are any strings formatted like such:
                    var regExpression = new Regex(@"^\d+( *)?/( *)?\${0,1}?\d+(\.\d+)?", RegexOptions.IgnoreCase); // [0-9]/($)?[0-9]
                    //IF the current cell is in the sale price column, check for the string format above, else move to the default method.
                    if (regExpression.IsMatch(dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].EditedFormattedValue.ToString()))
                    {
                        //Grab the input and split it at the forward slash (/) for formatting.
                        var input = dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].EditedFormattedValue.ToString();
                        input = input.Replace(" ", "");
                        //Remove any dollar signs as these cause errors.
                        input = input.Replace("$", "");
                        var stringArray = input.Split('/');
                        //Format the last number as Currency, and round it up if necessary.
                        dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value =
                            $@"{stringArray[0]}/{Math.Round(decimal.Parse(stringArray[1]), 2):C}";
                        dataGridView.Rows[e.RowIndex].HeaderCell.Style.BackColor = ApplicationColors.PendingEdit;
                        _isFormDirty = true;
                        //Always refresh edit so the new value shows up to the user.
                        dataGridView.RefreshEdit();
                        return; //And return, there is no need to go further.
                    }
                    //Try parsing the text entered as a number and if that fails then break out and clear the value entered.
                    if (double.TryParse(userInput, out parsedNumber))
                    {
                        dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = Math.Round(parsedNumber, 2).ToString("N", new CultureInfo("en-US"));
                        dataGridView.Rows[e.RowIndex].HeaderCell.Style.BackColor = ApplicationColors.PendingEdit;
                        _isFormDirty = true;
                    }
                    else
                    {
                        if (userInput == "")
                        {
                            return;
                        }
                        MessageBox.Show(@"Non numeric characters in column " + (e.ColumnIndex + 1) + @" are not allowed.", @"Invalid Characters Detected");
                        dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = "";
                        dataGridView.RefreshEdit();
                        e.Cancel = true;
                        return;
                    }
                    break;
                default:
                    //Purely here for protection against parsing the Boolean columns by mistake.
                    if (e.ColumnIndex == (int)SalesTableColumns.Id || e.ColumnIndex >= (int)SalesTableColumns.IsHeaderRow) { return; }
                    //If the column is any other then check to see if the entered value can be parsed to a double (is a number), if not then throw an error to the user.
                    if (double.TryParse(userInput, out parsedNumber))
                    {
                        dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = Math.Round(parsedNumber, 2).ToString("N", new CultureInfo("en-US"));
                        dataGridView.Rows[e.RowIndex].HeaderCell.Style.BackColor = ApplicationColors.PendingEdit;
                        _isFormDirty = true;
                    }
                    else
                    {
                        if (userInput == "")
                        {
                            return;
                        }
                        MessageBox.Show(@"Non numeric characters in column " + (e.ColumnIndex + 1) + @" are not allowed.", @"Invalid Characters Detected");
                        dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = "";
                        dataGridView.RefreshEdit();
                        e.Cancel = true;
                        return;
                    }
                    break;
            }
            //Always refresh edit so the new value shows up to the user.
            dataGridView.RefreshEdit();
        }

        #endregion

        #region Projected Sales DataGridView Events

        /// <summary>
        /// Event Used: RowValidating
        /// Checks to make sure the row is valid (has an ad item) and
        /// then copies the contents where possible over to the inventory
        /// and actual sales DataGridViews.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ValidateProjectedRow(object sender, DataGridViewCellCancelEventArgs e)
        {
            //Grab the index of the ad item, assuming the Sales tables and the Inventory table stay in the same position.
            const int adItemIndex = (int)SalesTableColumns.AdItem;
            //Do not even attempt anything since this is a new row and nothing to worry about.
            if (projectionsDataGridView.Rows[e.RowIndex].IsNewRow)
            {
                return;
            }
            //Clear all whitespace and check for a null value in the ad item column.
            if (Regex.Replace(projectionsDataGridView.Rows[e.RowIndex].Cells[adItemIndex].EditedFormattedValue.ToString(), @"\s+", "") == "")
            {
                projectionsDataGridView.Rows[e.RowIndex].HeaderCell.Style.BackColor = ApplicationColors.RowError;
                MessageBox.Show(@"An ad item is required.", @"No Ad Item Specified");
                projectionsDataGridView.Rows[e.RowIndex].Cells[adItemIndex].Selected = true;
                e.Cancel = true;
            }
            //Check to see if the user left a row that already exists and doesn't require being copied over.
            if (projectionsDataGridView.Rows[e.RowIndex].Cells[adItemIndex].EditedFormattedValue.ToString() == actualSalesDataGridView.Rows[e.RowIndex].Cells[adItemIndex].EditedFormattedValue.ToString())
            {
                return;
            }
            //Next check to see if the user changed the ad item is the corresponding row.
            if (projectionsDataGridView.Rows[e.RowIndex].Cells[adItemIndex].EditedFormattedValue.ToString() != actualSalesDataGridView.Rows[e.RowIndex].Cells[adItemIndex].EditedFormattedValue.ToString())
            {
                if (projectionsDataGridView.RowCount == actualSalesDataGridView.RowCount)
                {
                    var adItemText = projectionsDataGridView.Rows[e.RowIndex].Cells[adItemIndex].EditedFormattedValue.ToString();
                    actualSalesDataGridView.Rows[e.RowIndex].Cells[adItemIndex].Value = adItemText;
                    actualSalesDataGridView.Rows[e.RowIndex].Cells[(int) SalesTableColumns.IsDirty].Value = true;
                    actualSalesDataGridView.Rows[e.RowIndex].HeaderCell.Style.BackColor = ApplicationColors.PendingEdit;
                    inventoryDataGridView.Rows[e.RowIndex].Cells[adItemIndex].Value = adItemText;
                    inventoryDataGridView.Rows[e.RowIndex].Cells[(int) InventoryTableColumns.IsDirty].Value = true;
                    inventoryDataGridView.Rows[e.RowIndex].HeaderCell.Style.BackColor = ApplicationColors.PendingEdit;
                    projectionsDataGridView.RefreshEdit();
                    //Remove the last ad item from the UsedAdItem array, the new one will be added in the OnRowLeave event handler.
                    if (_adSpecialIndex == -1 || e.RowIndex < _adSpecialIndex)
                    {
                        _usedAdItems[0].RemoveAll(I => I.Equals(_beginningCellValue, StringComparison.OrdinalIgnoreCase));
                    }
                    else
                    {
                        _usedAdItems[1].RemoveAll(I => I.Equals(_beginningCellValue, StringComparison.OrdinalIgnoreCase));
                    }

                    return;
                }
            }
            var rowContents = new object[projectionsDataGridView.ColumnCount];
            //Spin through the DataGridViewCells in the row and add their contents to an array.
            for (var i = 0; i < projectionsDataGridView.ColumnCount; i++)
            {
                //Grab the Ad Item in the first cell and add it into the array.
                switch (i)
                {
                    case (int)SalesTableColumns.AdItem:
                        rowContents[i] = projectionsDataGridView.Rows[e.RowIndex].Cells[i].EditedFormattedValue.ToString();
                        break;
                    case (int)SalesTableColumns.SalePrice:
                        //IF the Sale Price cell is empty then place 0.00 into the array as a place holder value (assuming this row is a HeaderRow).
                        if (projectionsDataGridView.Rows[e.RowIndex].Cells[i].EditedFormattedValue.ToString() == "")
                        {
                            rowContents[i] = "";
                        }
                        //ELSE place the value from the Projections table into the array, since Sale Price can be determined before actual data is used.
                        else
                        {
                            rowContents[i] = projectionsDataGridView.Rows[e.RowIndex].Cells[i].EditedFormattedValue.ToString();
                        }
                        break;
                    case (int)SalesTableColumns.Cost:
                        //IF the Cost cell is empty then place 0.00 into the array as a place holder value (assuming this row is a HeaderRow).
                        if (projectionsDataGridView.Rows[e.RowIndex].Cells[i].EditedFormattedValue.ToString() == "")
                        {
                            rowContents[i] = "";
                        }
                        //ELSE place the value from the Projections table into the array, since Cost can be determined before actual data is used.
                        else
                        {
                            rowContents[i] = projectionsDataGridView.Rows[e.RowIndex].Cells[i].EditedFormattedValue.ToString();
                        }
                        break;
                    case (int)SalesTableColumns.IsDirty:
                        rowContents[i] = true;
                        break;
                    case (int)SalesTableColumns.IsHeaderRow:
                        rowContents[i] = false;
                        break;
                    case (int)SalesTableColumns.IsMemberRow:
                        rowContents[i] = false;
                        break;
                    default:
                        rowContents[i] = "";
                        break;
                }
            }
            actualSalesDataGridView.Rows.Add(rowContents);
            //Build a collection of objects for the inventory table to use.
            var inventoryNewRow = new object[inventoryDataGridView.ColumnCount];
            //Spin through the DataGridViewCells in the row and add their contents to an array.
            for (var i = 0; i < projectionsDataGridView.ColumnCount; i++)
            {
                //Grab the Ad Item in the first cell and add it into the array.
                switch (i)
                {
                    case (int)SalesTableColumns.Id:
                        inventoryNewRow[(int)InventoryTableColumns.Id] = "";
                        break;
                    case (int)SalesTableColumns.AdItem:
                        inventoryNewRow[(int)InventoryTableColumns.AdItem] =
                            projectionsDataGridView.Rows[e.RowIndex].Cells[i].EditedFormattedValue.ToString();
                        break;
                    case (int)InventoryTableColumns.IsDirty:
                        inventoryNewRow[(int)InventoryTableColumns.IsDirty] = true;
                        break;
                    case (int)InventoryTableColumns.IsHeaderRow:
                        inventoryNewRow[(int)InventoryTableColumns.IsHeaderRow] = false;
                        break;
                    case (int)InventoryTableColumns.IsMemberRow:
                        inventoryNewRow[(int)InventoryTableColumns.IsMemberRow] = false;
                        break;
                    default:
                        if (i > (int)InventoryTableColumns.IsHeaderRow) continue;
                        inventoryNewRow[i] = "";
                        break;
                }
            }
            inventoryDataGridView.Rows.Add(inventoryNewRow);
            //Set the row headers of the other tables to show up as pending; this row is valid without a doubt.
            if (e.RowIndex != _adSpecialIndex)
            {
                inventoryDataGridView.Rows[e.RowIndex].HeaderCell.Style.BackColor = ApplicationColors.PendingEdit;
                actualSalesDataGridView.Rows[e.RowIndex].HeaderCell.Style.BackColor = ApplicationColors.PendingEdit;
            }
            else
            {
                inventoryDataGridView.Rows[e.RowIndex].HeaderCell.Style.BackColor = DefaultBackColor;
                actualSalesDataGridView.Rows[e.RowIndex].HeaderCell.Style.BackColor = DefaultBackColor;
            }
        }

        private void ProjectionRowRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
        {
            var dataGridView = ((DataGridView)sender);
            //Provide protection against overflows
            if ((e.RowIndex + 1) > dataGridView.Rows.Count)
            {
                return;
            }
            //Disable all row removing events from the other two tables to prevent interference.
            inventoryDataGridView.UserDeletingRow -= UpdateUsedAdItemCollectionOnRowRemoving;
            inventoryDataGridView.RowsRemoved -= InventoryRowRemoved;

            actualSalesDataGridView.UserDeletingRow -= UpdateUsedAdItemCollectionOnRowRemoving;
            actualSalesDataGridView.RowsRemoved -= ActualSalesRowRemoved;

            //IF the row count on the passed DataGridView is less then the other table's row count...
            if (projectionsDataGridView.RowCount <= actualSalesDataGridView.RowCount && projectionsDataGridView.RowCount <= actualSalesDataGridView.RowCount)
            {
                //... it is lower so its safe to assume that both tables have the same row that can be removed.
                if (!actualSalesDataGridView.Rows[e.RowIndex].IsNewRow)
                {
                    actualSalesDataGridView.Rows.RemoveAt(e.RowIndex);
                }

                if (!inventoryDataGridView.Rows[e.RowIndex].IsNewRow)
                {
                    inventoryDataGridView.Rows.RemoveAt(e.RowIndex);
                }
            }
            //ELSE IF the row count is larger then the other table's row count...
            else
            {
                //... Log the error and then what?
                //TODO: Figure out if this is an error condition.
                LogConsole.WriteToLog(FrmLogConsole.Level.Error, "The Projections table has more rows then the Actual Sales table.");
                LogConsole.WriteToLog(FrmLogConsole.Level.Error, "Projections Row Count: " + projectionsDataGridView.RowCount);
                LogConsole.WriteToLog(FrmLogConsole.Level.Error, "Inventory Row Count: " + inventoryDataGridView.RowCount);
                LogConsole.WriteToLog(FrmLogConsole.Level.Error, "Actual Sales Row Count: " + actualSalesDataGridView.RowCount);
                errorLabel.Text = @"Error removing rows from Actual Sales and Inventory.";
            }
            //... After all the row removal has been finished re-enable the row removal events.
            inventoryDataGridView.UserDeletingRow += UpdateUsedAdItemCollectionOnRowRemoving;
            inventoryDataGridView.RowsRemoved += InventoryRowRemoved;

            actualSalesDataGridView.UserDeletingRow += UpdateUsedAdItemCollectionOnRowRemoving;
            actualSalesDataGridView.RowsRemoved += ActualSalesRowRemoved;

            //Reset the row numbers in the tables.
            for (var i = e.RowIndex; i < (dataGridView.RowCount); i++)
            {
                projectionsDataGridView.Rows[i].HeaderCell.Value = (i + 1).ToString();
                inventoryDataGridView.Rows[i].HeaderCell.Value = (i + 1).ToString();
                actualSalesDataGridView.Rows[i].HeaderCell.Value = (i + 1).ToString();
            }
            //Refresh the DataGridViews so the header cell's number get repainted properly and repaint the rows in case any groups get messed up during row removal.
            projectionsDataGridView.RefreshEdit();
            inventoryDataGridView.RefreshEdit();
            actualSalesDataGridView.RefreshEdit();
            _tableHelperFunctions.PaintRowGroups(dataGridView);
        }

        #endregion

        #region Inventory DataGridView Events

        /// <summary>
        /// Event Used: CellValidating
        /// Validates the contents of the cell that the user is attempting to leave. Applies formatting
        /// to text as needed and prevents the user from leaving invalid cells.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ValidateInventoryCellContents(object sender, DataGridViewCellValidatingEventArgs e)
        {
            //Grab the DataGirdView that fired the event and make it into a local variable.
            var dataGridView = ((DataGridView)sender);
            var userInput = dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].EditedFormattedValue.ToString();
            //TODO: Write a custom parsing engine for detecting when bins are entered.
            var textInfo = new CultureInfo("en-US", false).TextInfo;
            //Check for isNewRow if it is, return no need to check it for anything.
            if (dataGridView.Rows[e.RowIndex].IsNewRow)
            {
                return;
            }

            if (userInput == _beginningCellValue)
            {
                return;
            }
            //Check to make sure we're not in the boolean fields or the ID field.
            if (e.ColumnIndex >= (int)InventoryTableColumns.IsHeaderRow || e.ColumnIndex == (int)InventoryTableColumns.Id)
            {
                return;
            }
            //Cell validating gets to handle updating the used ad item list since it handles cells on by one, instead by a whole row.
            if (userInput != _beginningCellValue && e.ColumnIndex == (int)InventoryTableColumns.AdItem)
            {
                //The user is trying to change the ad special text to something else.
                if (e.RowIndex == _adSpecialIndex)
                {
                    var parser = new RowParsing();
                    if (parser.CheckForGroupKeyWord(userInput) == "NoGroupFound")
                    {
                        MessageBox.Show(@"The Ad Special row's column one (1) cannot be changed. You must delete this row by clicking on the header cell and pressing 'Delete'.", @"Invalid Operation on Ad Special Row", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = _beginningCellValue;
                        dataGridView.RefreshEdit();
                        return;
                    }
                    //Mark all ad special members as dirty since the user changed the ad special.
                    for (var index = _adSpecialIndex + 1; index < dataGridView.RowCount; index++)
                    {
                        //Add overflow protection
                        if (index < projectionsDataGridView.RowCount)
                        {
                            if (!projectionsDataGridView.Rows[index].IsNewRow)
                            {
                                projectionsDataGridView.Rows[index].Cells[(int)SalesTableColumns.IsDirty].Value = true;
                            }
                        }
                        if (index < actualSalesDataGridView.RowCount)
                        {
                            if (!actualSalesDataGridView.Rows[index].IsNewRow)
                            {
                                actualSalesDataGridView.Rows[index].Cells[(int)SalesTableColumns.IsDirty].Value = true;
                            }
                        }
                        if (index < inventoryDataGridView.RowCount)
                        {
                            if (!inventoryDataGridView.Rows[index].IsNewRow)
                            {
                                inventoryDataGridView.Rows[index].Cells[(int)InventoryTableColumns.IsDirty].Value = true;
                            }
                        }
                    }
                }
                _usedAdItems[_adSpecialIndex == -1 || e.RowIndex < _adSpecialIndex ? 0 : 1].Remove(_beginningCellValue);
                dataGridView.Rows[e.RowIndex].Cells[(int)InventoryTableColumns.IsDirty].Value = true;
            }
            else if (userInput != _beginningCellValue)
            {
                dataGridView.Rows[e.RowIndex].Cells[(int)InventoryTableColumns.IsDirty].Value = true;
            }
            //Check to see if the current column is the ad item column.
            switch (e.ColumnIndex)
            {
                case (int)InventoryTableColumns.AdItem:
                    //If there is text after all the whitespace has been cleared, clear the error text property regardless of whether or not it is set.
                    if (!string.IsNullOrEmpty(Regex.Replace(userInput, @"\s+", "")))
                    {
                        //Clear the error text since there is in fact an item entered.
                        dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].ErrorText = "";
                        //Send the ad item text through the formatting engine and assign the new value to the cell.
                        dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = TextFormat.FormatAdItemText(userInput);
                        var parser = new RowParsing();
                        if (parser.CheckForGroupKeyWord(userInput) == "NoGroupFound")
                        {
                            dataGridView.Rows[e.RowIndex].HeaderCell.Style.BackColor = ApplicationColors.PendingEdit;
                            _isFormDirty = true;
                        }
                        else
                        {
                            _adSpecialIndex = e.RowIndex;
                            //Since this is the ad special row don't give it any color coding.
                            dataGridView.Rows[e.RowIndex].HeaderCell.Style.BackColor = DefaultBackColor;
                        }
                        //Force a refresh so the cell's text updates and displays for the user.
                        dataGridView.RefreshEdit();
                        return;
                    }
                    //If column one (1) is blank then cancel cell validating.
                    dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].ErrorText = "Ad Item needed";
                    break;
                default:
                    //Purely here for protection against parsing the Boolean columns by mistake.
                    if (e.ColumnIndex == (int)InventoryTableColumns.Id || e.ColumnIndex >= (int)InventoryTableColumns.IsHeaderRow) { return; }
                    //This Reg-ex pattern will match any number followed by the word bin(s), to allow specifying the number of bins of product were ordered.
                    var inventoryStringCheck = new Regex(@"^[0-9]{1,2} \bbin(s){0,1}\b", RegexOptions.IgnoreCase);

                    if (
                        inventoryStringCheck.IsMatch(
                            dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].EditedFormattedValue.ToString()))
                    {
                        //IF a match has been found, then make sure the word 'bin(s)' is capitalized to keep things looking pretty.
                        dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = textInfo.ToTitleCase(userInput);
                        dataGridView.Rows[e.RowIndex].HeaderCell.Style.BackColor = ApplicationColors.PendingEdit;
                        _isFormDirty = true;
                        dataGridView.RefreshEdit();
                        return;
                    }
                    double parsedNumber;
                    //Try parsing the text entered as a number and if that fails then break out and clear the value entered.
                    if (userInput != "" && double.TryParse(userInput, out parsedNumber))
                    {
                        //Add the value to the cell.
                        dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = userInput;
                        dataGridView.Rows[e.RowIndex].HeaderCell.Style.BackColor = ApplicationColors.PendingEdit;
                        _isFormDirty = true;
                        return;
                    }
                    //Prevent the user from being bombarded by message boxes. All validation has been completed at this point so there's nothing to worry about.
                    if (userInput != "")
                    {
                        MessageBox.Show(@"Non numeric characters in column " + (e.ColumnIndex + 1) + @" are not allowed.", @"Invalid Characters Detected");
                        dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = "";
                        dataGridView.RefreshEdit();
                        e.Cancel = true;
                    }
                    break;
            }
            //Always refresh edit so the new value shows up to the user.
            dataGridView.RefreshEdit();
        }

        /// <summary>
        /// Event Used: RowValidating
        /// Checks to make sure the row is valid (has an ad item) and
        /// then copies the contents where possible over to the projections
        /// and actual sales DataGridViews.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ValidateInventoryRow(object sender, DataGridViewCellCancelEventArgs e)
        {
            //Grab the index of the ad item, assuming the Sales tables and the Inventory table stay in the same position.
            const int adItemIndex = (int)InventoryTableColumns.AdItem;
            //Do not even attempt anything since this is a new row and nothing to worry about.
            if (inventoryDataGridView.Rows[e.RowIndex].IsNewRow)
            {
                return;
            }
            //Clear all whitespace and check for a null value in the ad item column.
            if (Regex.Replace(inventoryDataGridView.Rows[e.RowIndex].Cells[adItemIndex].EditedFormattedValue.ToString(), @"\s+", "") == "")
            {
                inventoryDataGridView.Rows[e.RowIndex].HeaderCell.Style.BackColor = ApplicationColors.RowError;
                MessageBox.Show(@"An ad item is required.", @"No Ad Item Specified");
                inventoryDataGridView.Rows[e.RowIndex].Cells[adItemIndex].Selected = true;
                e.Cancel = true;
            }
            //Check to see if the user left a row that already exists and doesn't require being copied over.
            if (inventoryDataGridView.Rows[e.RowIndex].Cells[adItemIndex].EditedFormattedValue.ToString() == actualSalesDataGridView.Rows[e.RowIndex].Cells[adItemIndex].EditedFormattedValue.ToString())
            {
                return;
            }
            //Next check to see if the user changed the ad item is the corresponding row.
            if (inventoryDataGridView.Rows[e.RowIndex].Cells[adItemIndex].EditedFormattedValue.ToString() != actualSalesDataGridView.Rows[e.RowIndex].Cells[adItemIndex].EditedFormattedValue.ToString())
            {
                if (inventoryDataGridView.RowCount == actualSalesDataGridView.RowCount)
                {
                    var adItemText = inventoryDataGridView.Rows[e.RowIndex].Cells[adItemIndex].EditedFormattedValue.ToString();
                    projectionsDataGridView.Rows[e.RowIndex].Cells[adItemIndex].Value = adItemText;
                    projectionsDataGridView.Rows[e.RowIndex].Cells[(int) SalesTableColumns.IsDirty].Value = true;
                    projectionsDataGridView.Rows[e.RowIndex].HeaderCell.Style.BackColor = ApplicationColors.PendingEdit;
                    actualSalesDataGridView.Rows[e.RowIndex].Cells[adItemIndex].Value = adItemText;
                    actualSalesDataGridView.Rows[e.RowIndex].Cells[(int) SalesTableColumns.IsDirty].Value = true;
                    actualSalesDataGridView.Rows[e.RowIndex].HeaderCell.Style.BackColor = ApplicationColors.PendingEdit;
                    //inventoryDataGridView.RefreshEdit();
                    //Remove the last ad item from the UsedAdItem array, the new one will be added in the OnRowLeave event handler.
                    if (_adSpecialIndex == -1 || e.RowIndex < _adSpecialIndex)
                    {
                        _usedAdItems[0].RemoveAll(I => I.Equals(_beginningCellValue, StringComparison.OrdinalIgnoreCase));
                    }
                    else
                    {
                        _usedAdItems[1].RemoveAll(I => I.Equals(_beginningCellValue, StringComparison.OrdinalIgnoreCase));
                    }

                    return;
                }
            }
            var rowContents = new object[actualSalesDataGridView.ColumnCount];
            //Spin through the DataGridViewCells in the row and add their contents to an array.
            for (var i = 0; i < actualSalesDataGridView.ColumnCount; i++)
            {
                //Grab the Ad Item in the first cell and add it into the array.
                switch (i)
                {
                    case (int)SalesTableColumns.AdItem:
                        rowContents[i] = inventoryDataGridView.Rows[e.RowIndex].Cells[(int)InventoryTableColumns.AdItem].EditedFormattedValue.ToString();
                        break;
                    case (int)SalesTableColumns.IsDirty:
                        rowContents[i] = true;
                        break;
                    case (int)SalesTableColumns.IsHeaderRow:
                        rowContents[i] = false;
                        break;
                    case (int)SalesTableColumns.IsMemberRow:
                        rowContents[i] = false;
                        break;
                    default:
                        rowContents[i] = "";
                        break;
                }
            }
            projectionsDataGridView.Rows.Add(rowContents);
            actualSalesDataGridView.Rows.Add(rowContents);
            if (e.RowIndex != _adSpecialIndex)
            {
                //Apply color coding to the respective row headers on the other tables.
                projectionsDataGridView.Rows[e.RowIndex].HeaderCell.Style.BackColor = ApplicationColors.PendingEdit;
                actualSalesDataGridView.Rows[e.RowIndex].HeaderCell.Style.BackColor = ApplicationColors.PendingEdit;
            }
            else
            {
                //Apply color coding to the respective row headers on the other tables.
                projectionsDataGridView.Rows[e.RowIndex].HeaderCell.Style.BackColor = DefaultBackColor;
                actualSalesDataGridView.Rows[e.RowIndex].HeaderCell.Style.BackColor = DefaultBackColor;
            }
        }

        private void InventoryRowRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
        {
            var dataGridView = ((DataGridView)sender);
            //Provide protection against overflows
            if ((e.RowIndex + 1) > dataGridView.Rows.Count)
            {
                return;
            }
            //Disable all row removing events from the other two tables to prevent interference.
            projectionsDataGridView.UserDeletingRow -= UpdateUsedAdItemCollectionOnRowRemoving;
            projectionsDataGridView.RowsRemoved -= ProjectionRowRemoved;

            actualSalesDataGridView.UserDeletingRow -= UpdateUsedAdItemCollectionOnRowRemoving;
            actualSalesDataGridView.RowsRemoved -= ActualSalesRowRemoved;

            //IF the row count on the passed DataGridView is less then the other table's row count...
            if (inventoryDataGridView.RowCount <= projectionsDataGridView.RowCount && inventoryDataGridView.RowCount <= actualSalesDataGridView.RowCount)
            {
                //... it is lower so its safe to assume that both tables have the same row that can be removed.
                if (!projectionsDataGridView.Rows[e.RowIndex].IsNewRow)
                {
                    projectionsDataGridView.Rows.RemoveAt(e.RowIndex);
                }

                if (!actualSalesDataGridView.Rows[e.RowIndex].IsNewRow)
                {
                    actualSalesDataGridView.Rows.RemoveAt(e.RowIndex);
                }
            }
            //ELSE IF the row count is larger then the other table's row count...
            else
            {
                //... Log the error and then what?
                //TODO: Figure out if this is an error condition.
                LogConsole.WriteToLog(FrmLogConsole.Level.Error, "The Inventory table has more rows then the Actual Sales table.");
                LogConsole.WriteToLog(FrmLogConsole.Level.Error, "Projections Row Count: " + projectionsDataGridView.RowCount);
                LogConsole.WriteToLog(FrmLogConsole.Level.Error, "Inventory Row Count: " + inventoryDataGridView.RowCount);
                LogConsole.WriteToLog(FrmLogConsole.Level.Error, "Actual Sales Row Count: " + actualSalesDataGridView.RowCount);
                errorLabel.Text = @"Error removing rows from Actual Sales and Inventory.";
            }
            //... After all the row removal has been finished re-enable the row removal events.
            projectionsDataGridView.UserDeletingRow += UpdateUsedAdItemCollectionOnRowRemoving;
            projectionsDataGridView.RowsRemoved += ProjectionRowRemoved;

            actualSalesDataGridView.UserDeletingRow += UpdateUsedAdItemCollectionOnRowRemoving;
            actualSalesDataGridView.RowsRemoved += ActualSalesRowRemoved;

            //Reset the row numbers in each table.
            for (var i = e.RowIndex; i < (dataGridView.RowCount); i++)
            {
                projectionsDataGridView.Rows[i].HeaderCell.Value = (i + 1).ToString();
                inventoryDataGridView.Rows[i].HeaderCell.Value = (i + 1).ToString();
                actualSalesDataGridView.Rows[i].HeaderCell.Value = (i + 1).ToString();
            }
            //Refresh the DataGridViews so the header cell's number get repainted properly and repaint the rows in case any groups get messed up during row removal.
            projectionsDataGridView.RefreshEdit();
            inventoryDataGridView.RefreshEdit();
            actualSalesDataGridView.RefreshEdit();
            _tableHelperFunctions.PaintRowGroups(dataGridView);
        }

        #endregion

        #region Actual Sales DataGridView Events

        /// <summary>
        /// Event Used: RowValidating
        /// Checks to make sure the row is valid (has an ad item) and
        /// then copies the contents where possible over to the inventory
        /// and actual sales DataGridViews.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ValidateActualSalesRow(object sender, DataGridViewCellCancelEventArgs e)
        {
            //Grab the index of the ad item, assuming the Sales tables and the Inventory table stay in the same position.
            const int adItemIndex = (int)SalesTableColumns.AdItem;
            //Do not even attempt anything since this is a new row and nothing to worry about.
            if (actualSalesDataGridView.Rows[e.RowIndex].IsNewRow)
            {
                return;
            }
            //Clear all whitespace and check for a null value in the ad item column.
            if (Regex.Replace(actualSalesDataGridView.Rows[e.RowIndex].Cells[adItemIndex].EditedFormattedValue.ToString(), @"\s+", "") == "")
            {
                actualSalesDataGridView.Rows[e.RowIndex].HeaderCell.Style.BackColor = ApplicationColors.RowError;
                MessageBox.Show(@"An ad item is required.", @"No Ad Item Specified");
                actualSalesDataGridView.Rows[e.RowIndex].Cells[adItemIndex].Selected = true;
                e.Cancel = true;
            }
            //Check to see if the user left a row that already exists and doesn't require being copied over.
            if (actualSalesDataGridView.Rows[e.RowIndex].Cells[adItemIndex].EditedFormattedValue.ToString() == projectionsDataGridView.Rows[e.RowIndex].Cells[adItemIndex].EditedFormattedValue.ToString())
            {
                return;
            }
            //Next check to see if the user changed the ad item is the corresponding row.
            if (actualSalesDataGridView.Rows[e.RowIndex].Cells[adItemIndex].EditedFormattedValue.ToString() != projectionsDataGridView.Rows[e.RowIndex].Cells[adItemIndex].EditedFormattedValue.ToString())
            {
                if (actualSalesDataGridView.RowCount == projectionsDataGridView.RowCount)
                {
                    var adItemText = actualSalesDataGridView.Rows[e.RowIndex].Cells[adItemIndex].EditedFormattedValue.ToString();
                    projectionsDataGridView.Rows[e.RowIndex].Cells[adItemIndex].Value = adItemText;
                    projectionsDataGridView.Rows[e.RowIndex].Cells[(int) SalesTableColumns.IsDirty].Value = true;
                    projectionsDataGridView.Rows[e.RowIndex].HeaderCell.Style.BackColor = ApplicationColors.PendingEdit;
                    inventoryDataGridView.Rows[e.RowIndex].Cells[adItemIndex].Value = adItemText;
                    inventoryDataGridView.Rows[e.RowIndex].Cells[(int) InventoryTableColumns.IsDirty].Value = true;
                    inventoryDataGridView.Rows[e.RowIndex].HeaderCell.Style.BackColor = ApplicationColors.PendingEdit;
                    //projectionsDataGridView.RefreshEdit();
                    //Remove the last ad item from the UsedAdItem array, the new one will be added in the OnRowLeave event handler.
                    if (_adSpecialIndex == -1 || e.RowIndex < _adSpecialIndex)
                    {
                        _usedAdItems[0].RemoveAll(I => I.Equals(_beginningCellValue, StringComparison.OrdinalIgnoreCase));
                    }
                    else
                    {
                        _usedAdItems[1].RemoveAll(I => I.Equals(_beginningCellValue, StringComparison.OrdinalIgnoreCase));
                    }

                    return;
                }
            }
            var rowContents = new object[actualSalesDataGridView.ColumnCount];
            //Spin through the DataGridViewCells in the row and add their contents to an array.
            for (var i = 0; i < actualSalesDataGridView.ColumnCount; i++)
            {
                //Grab the Ad Item in the first cell and add it into the array.
                switch (i)
                {
                    case (int)SalesTableColumns.AdItem:
                        rowContents[i] = actualSalesDataGridView.Rows[e.RowIndex].Cells[i].EditedFormattedValue.ToString();
                        break;
                    case (int)SalesTableColumns.SalePrice:
                        rowContents[i] = actualSalesDataGridView.Rows[e.RowIndex].Cells[i].EditedFormattedValue.ToString();
                        break;
                    case (int)SalesTableColumns.Cost:
                        rowContents[i] = actualSalesDataGridView.Rows[e.RowIndex].Cells[i].EditedFormattedValue.ToString();
                        break;
                    case (int)SalesTableColumns.IsDirty:
                        rowContents[i] = true;
                        break;
                    case (int)SalesTableColumns.IsHeaderRow:
                        rowContents[i] = false;
                        break;
                    case (int)SalesTableColumns.IsMemberRow:
                        rowContents[i] = false;
                        break;
                    default:
                        rowContents[i] = "";
                        break;
                }
            }
            projectionsDataGridView.Rows.Add(rowContents);
            //Build a collection of objects for the inventory table to use.
            var inventoryNewRow = new object[inventoryDataGridView.ColumnCount];
            //Spin through the DataGridViewCells in the row and add their contents to an array.
            for (var i = 0; i < actualSalesDataGridView.ColumnCount; i++)
            {
                //Grab the Ad Item in the first cell and add it into the array.
                switch (i)
                {
                    case (int)SalesTableColumns.AdItem:
                        inventoryNewRow[(int)InventoryTableColumns.AdItem] =
                            actualSalesDataGridView.Rows[e.RowIndex].Cells[i].EditedFormattedValue.ToString();
                        break;
                    case (int)SalesTableColumns.IsDirty:
                        inventoryNewRow[(int)InventoryTableColumns.IsDirty] = true;
                        break;
                    case (int)InventoryTableColumns.IsHeaderRow:
                        inventoryNewRow[(int)InventoryTableColumns.IsHeaderRow] = false;
                        break;
                    case (int)InventoryTableColumns.IsMemberRow:
                        inventoryNewRow[(int)InventoryTableColumns.IsMemberRow] = false;
                        break;
                    default:
                        if (i > (int)InventoryTableColumns.IsHeaderRow) continue;
                        inventoryNewRow[i] = "";
                        break;
                }
            }
            inventoryDataGridView.Rows.Add(inventoryNewRow);

            if (e.RowIndex != _adSpecialIndex)
            {
                //Apply color coding to the respective row headers on the other tables.
                projectionsDataGridView.Rows[e.RowIndex].HeaderCell.Style.BackColor = ApplicationColors.PendingEdit;
                inventoryDataGridView.Rows[e.RowIndex].HeaderCell.Style.BackColor = ApplicationColors.PendingEdit;
            }
            else
            {
                //Apply color coding to the respective row headers on the other tables.
                projectionsDataGridView.Rows[e.RowIndex].HeaderCell.Style.BackColor = DefaultBackColor;
                inventoryDataGridView.Rows[e.RowIndex].HeaderCell.Style.BackColor = DefaultBackColor;
            }
        }

        private void ActualSalesRowRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
        {
            var dataGridView = ((DataGridView)sender);
            //Provide protection against overflows
            if ((e.RowIndex + 1) > dataGridView.Rows.Count)
            {
                return;
            }
            //Disable all row removing events from the other two tables to prevent interference.
            projectionsDataGridView.UserDeletingRow -= UpdateUsedAdItemCollectionOnRowRemoving;
            projectionsDataGridView.RowsRemoved -= ProjectionRowRemoved;

            inventoryDataGridView.UserDeletingRow -= UpdateUsedAdItemCollectionOnRowRemoving;
            inventoryDataGridView.RowsRemoved -= InventoryRowRemoved;

            //IF the row count on the passed DataGridView is less then the other table's row count...
            if (actualSalesDataGridView.RowCount <= projectionsDataGridView.RowCount && actualSalesDataGridView.RowCount <= inventoryDataGridView.RowCount)
            {
                //... it is lower so its safe to assume that both tables have the same row that can be removed.
                if (!projectionsDataGridView.Rows[e.RowIndex].IsNewRow)
                {
                    projectionsDataGridView.Rows.RemoveAt(e.RowIndex);
                }

                if (!inventoryDataGridView.Rows[e.RowIndex].IsNewRow)
                {
                    inventoryDataGridView.Rows.RemoveAt(e.RowIndex);
                }
            }
            //ELSE IF the row count is larger then the other table's row count...
            else
            {
                //... Log the error and then what?
                //TODO: Figure out if this is an error condition.
                LogConsole.WriteToLog(FrmLogConsole.Level.Error, "The Actual Sales table has more rows then the Projections table.");
                LogConsole.WriteToLog(FrmLogConsole.Level.Error, "Projections Row Count: " + projectionsDataGridView.RowCount);
                LogConsole.WriteToLog(FrmLogConsole.Level.Error, "Inventory Row Count: " + inventoryDataGridView.RowCount);
                LogConsole.WriteToLog(FrmLogConsole.Level.Error, "Actual Sales Row Count: " + actualSalesDataGridView.RowCount);
                errorLabel.Text = @"Error removing rows from Actual Sales and Inventory.";
            }
            //... After all the row removal has been finished re-enable the row removal events.
            projectionsDataGridView.UserDeletingRow += UpdateUsedAdItemCollectionOnRowRemoving;
            projectionsDataGridView.RowsRemoved += ProjectionRowRemoved;

            inventoryDataGridView.UserDeletingRow += UpdateUsedAdItemCollectionOnRowRemoving;
            inventoryDataGridView.RowsRemoved += InventoryRowRemoved;

            //Reset the row numbers in the tables.
            for (var i = e.RowIndex; i < (dataGridView.RowCount); i++)
            {
                projectionsDataGridView.Rows[i].HeaderCell.Value = (i + 1).ToString();
                inventoryDataGridView.Rows[i].HeaderCell.Value = (i + 1).ToString();
                actualSalesDataGridView.Rows[i].HeaderCell.Value = (i + 1).ToString();
            }
            //Refresh the DataGridViews so the header cell's number get repainted properly and repaint the rows in case any groups get messed up during row removal.
            projectionsDataGridView.RefreshEdit();
            inventoryDataGridView.RefreshEdit();
            actualSalesDataGridView.RefreshEdit();
            _tableHelperFunctions.PaintRowGroups(dataGridView);
        }

        #endregion

        #region DataGridView Construction Functions

        /// <summary>
        /// Fills the APC DataGridViews with the appropriate columns and starting row for the user to start
        /// entering data.
        /// </summary>
        private void ConstructApcDataGridViews()
        {
            //Construct a list of column names for the projections/actual sales DataGridViews and the inventory DataGirdView.
            string[] saleColumnNames =
            {
                "ID", "AdItem", "Sold", "SalePrice", "TotalSales", "Cost", "ProfitReturn",
                "TotalProfitReturn", "IsHeader", "IsMember", "IsDirty"
            };
            string[] inventoryColumnNames =
            {
                "ID", "AdItem", "BeginningInventory", "Received", "Total", "EndingInventory", "IsHeader", "IsMember", "IsDirty"
            };

            foreach (var name in saleColumnNames)
            {
                if (!name.StartsWith("Is"))
                {
                    var column = new DataGridViewTextBoxColumn
                    {
                        Name = name,
                        HeaderText = TextFormat.AddSpacesToSentence(name, false),
                        ValueType = typeof(string),
                        SortMode = DataGridViewColumnSortMode.NotSortable,
                        MaxInputLength = 20
                    };
                    if (name.Contains("ID"))
                    {
                        //column.Visible = false;
                    }
                    projectionsDataGridView.Columns.Add(column);
                }
                else
                {
                    var column = new DataGridViewCheckBoxColumn
                    {
                        Name = name,
                        HeaderText = TextFormat.AddSpacesToSentence(name, false),
                        ValueType = typeof(bool),
                        //Visible = false,
                        SortMode = DataGridViewColumnSortMode.NotSortable
                    };
                    projectionsDataGridView.Columns.Add(column);
                }
            }
            //Add the columns into the inventory DataGridView after setting their types.
            foreach (var name in inventoryColumnNames)
            {
                if (!name.StartsWith("Is"))
                {
                    var column = new DataGridViewTextBoxColumn
                    {
                        Name = name,
                        HeaderText = TextFormat.AddSpacesToSentence(name, false),
                        ValueType = typeof(string),
                        SortMode = DataGridViewColumnSortMode.NotSortable,
                        MaxInputLength = 20
                    };
                    inventoryDataGridView.Columns.Add(column);
                }
                else
                {
                    var column = new DataGridViewCheckBoxColumn
                    {
                        Name = name,
                        HeaderText = TextFormat.AddSpacesToSentence(name, false),
                        ValueType = typeof(bool),
                        //Visible = false,
                        SortMode = DataGridViewColumnSortMode.NotSortable
                    };
                    inventoryDataGridView.Columns.Add(column);
                }
            }
            //
            foreach (var name in saleColumnNames)
            {
                if (!name.StartsWith("Is"))
                {
                    var column = new DataGridViewTextBoxColumn
                    {
                        Name = name,
                        HeaderText = TextFormat.AddSpacesToSentence(name, false),
                        ValueType = typeof(string),
                        SortMode = DataGridViewColumnSortMode.NotSortable,
                        MaxInputLength = 20
                    };
                    actualSalesDataGridView.Columns.Add(column);
                }
                else
                {
                    var column = new DataGridViewCheckBoxColumn
                    {
                        Name = name,
                        HeaderText = TextFormat.AddSpacesToSentence(name, false),
                        ValueType = typeof(bool),
                        //Visible = false,
                        SortMode = DataGridViewColumnSortMode.NotSortable
                    };
                    actualSalesDataGridView.Columns.Add(column);
                }
            }
        }

        /// <summary>
        /// Constructs the invoices DataGridView.
        /// </summary>
        private void ConstructInvoicesDataGridView()
        {
            string[] invoicesColumnNames = { "ID", "InvoiceDate", "Supplier", "InvoiceNumber", "InvoiceNetAmountAtCost", "InvoiceNetAmount", "InvoiceNote", "IsDirty" };

            foreach (var name in invoicesColumnNames)
            {
                if (!name.StartsWith("Is"))
                {
                    var column = new DataGridViewTextBoxColumn
                    {
                        Name = name,
                        HeaderText = TextFormat.AddSpacesToSentence(name, false),
                        ValueType = typeof(string),
                        SortMode = DataGridViewColumnSortMode.NotSortable,
                        MaxInputLength = 20
                    };
                    if (name.Contains("ID"))
                    {
                        //column.Visible = false;
                    }
                    invoicesDataGridView.Columns.Add(column);
                }
                else
                {
                    var column = new DataGridViewCheckBoxColumn
                    {
                        Name = name,
                        ValueType = typeof(bool),
                        //Visible = false,
                        SortMode = DataGridViewColumnSortMode.NotSortable
                    };
                    invoicesDataGridView.Columns.Add(column);
                }
            }
        }

        #endregion

        #region Comments TextBox Events

        /// <summary>
        /// Allows the user to select all the text in the comments text box.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CheckForKeyCommand(object sender, KeyEventArgs e)
        {
            if (!e.Control || e.KeyCode != Keys.A) return;
            commentsTextBox.SelectionStart = 0;
            commentsTextBox.SelectionLength = commentsTextBox.Text.Length;
            e.Handled = true;
            e.SuppressKeyPress = true;
        }

        /// <summary>
        /// Event Used: TextChanged
        /// Calculates and displays the remaining number of characters available for the user to enter
        /// and changes the color of the label displaying the character count to red when 20% or less characters remain.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DisplayRemainingCommentCharacterCount(object sender, EventArgs e)
        {
            //If the amount of characters left is less then 20% (or 80% or more characters have been used) then color the label red, otherwise color it its default color.
            commentsGroupBox.ForeColor = (double)commentsTextBox.TextLength / commentsTextBox.MaxLength < .8 ? default(Color) : Color.DarkRed;
            commentsGroupBox.Text = @"Comments (Characters Remaining: " + (commentsTextBox.MaxLength - commentsTextBox.TextLength) + @")";
        }

        private void CheckForTextChangeOnLeave(object sender, EventArgs e)
        {
            if (commentsTextBox.Text == _beginningCellValue) return;
            //Clear white spaces and check if the string is null.
            if (commentsTextBox.Text.Trim() == "" && isCommentDirtyCheckBox.Tag == null)
            {
                //The user cleared the comment(s) they were making but the comments were never committed to the database.
                //So the comments are no longer dirty.
                isCommentDirtyCheckBox.Checked = false;
            }
            else
            {
                //Otherwise the comment(s) were committed to the database and will need updating.
                //If its empty then the record will be cleared from the database.
                isCommentDirtyCheckBox.Checked = true;
                _isFormDirty = true;
            }
        }

        #endregion

        #region Weekly Sales Events

        /// <summary>
        /// Event Used: Validating
        /// Validates the contents of the weekly sales text boxes and adds up the total.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ValidateWeeklySales(object sender, CancelEventArgs e)
        {
            var textBox = (TextBox)sender;
            if (_beginningCellValue == textBox.Text) return;
            //There was a change to the starting value of the text box if we've made it this far.
            if (textBox.Text != "")
            {
                double dollarValue;
                if (double.TryParse(textBox.Text.Trim(), out dollarValue))
                {
                    //Input is valid so mark the section as dirty.
                    isWeeklySalesDirtyCheckBox.Checked = true;
                    _isFormDirty = true;
                    //And apply formatting.
                    textBox.Text = Math.Round(dollarValue, 2).ToString("N", new CultureInfo("en-US"));
                    //Check to see if the number is equal to zero (0) i.e. "0.00".
                    if (textBox.Text == @"0.00") textBox.Text = "";
                }
                else
                {
                    MessageBox.Show(@"The value must be numeric.", @"Input Must be Numeric");
                    textBox.Text = "";
                }
            }
            if (isWeeklySalesDirtyCheckBox.Tag != null)
            {
                isWeeklySalesDirtyCheckBox.Checked = true;
                _isFormDirty = true;
            }
            //Update the total sales text box before returning.
            var totalWeeklySales = 0.00;
            if (sundayWeeklySalesTextBox.Text != "") totalWeeklySales += double.Parse(sundayWeeklySalesTextBox.Text);
            if (mondayWeeklySalesTextBox.Text != "") totalWeeklySales += double.Parse(mondayWeeklySalesTextBox.Text);
            if (tuesdayWeeklySalesTextBox.Text != "") totalWeeklySales += double.Parse(tuesdayWeeklySalesTextBox.Text);
            if (wednesdayWeeklySalesTextBox.Text != "") totalWeeklySales += double.Parse(wednesdayWeeklySalesTextBox.Text);
            if (thursdayWeeklySalesTextBox.Text != "") totalWeeklySales += double.Parse(thursdayWeeklySalesTextBox.Text);
            if (fridayWeeklySalesTextBox.Text != "") totalWeeklySales += double.Parse(fridayWeeklySalesTextBox.Text);
            if (saturdayWeeklySalesTextBox.Text != "") totalWeeklySales += double.Parse(saturdayWeeklySalesTextBox.Text);
            if (Math.Abs(totalWeeklySales) > 0)
            {
                totalWeeklySalesTextBox.Text = totalWeeklySales.ToString("N", new CultureInfo("en-US"));
            }
            else
            {
                //Check to see if the weekly sales have been added to the database.
                if (isWeeklySalesDirtyCheckBox.Tag == null)
                {
                    //If the tag doesn't have an ID in it then we're clear to simply clear the is dirty flag.
                    isWeeklySalesDirtyCheckBox.Checked = false;
                }
                else if (isWeeklySalesDirtyCheckBox.Tag != null && textBox.Text == "")
                {
                    //If the user has already added the fields to the database but has removed a value
                    //update that accordingly.
                    isWeeklySalesDirtyCheckBox.Checked = true;
                    _isFormDirty = true;
                }
                totalWeeklySalesTextBox.Text = "";
            }
        }

        #endregion

        #region Taxable Events

        /// <summary>
        /// Validates the contents of the Taxable text boxes and adds up the total.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ValidateTaxableFields(object sender, CancelEventArgs e)
        {
            var textBox = (TextBox)sender;
            if (_beginningCellValue == textBox.Text) return;
            //There was a change to the starting value of the text box if we've made it this far.
            if (textBox.Text != "")
            {
                double dollarValue;
                if (double.TryParse(textBox.Text.Trim(), out dollarValue))
                {
                    //Input is valid so mark the section as dirty.
                    isTaxableDirtyCheckBox.Checked = true;
                    _isFormDirty = true;
                    //And apply formatting.
                    textBox.Text = Math.Round(dollarValue, 2).ToString("N", new CultureInfo("en-US"));
                    //Check to see if the number is equal to zero (0) i.e. "0.00".
                    if (textBox.Text == @"0.00") textBox.Text = "";
                }
                else
                {
                    MessageBox.Show(@"The value must be numeric.", @"Input Must be Numeric");
                    textBox.Text = "";
                }
            }
            if (isTaxableDirtyCheckBox.Tag != null)
            {
                isTaxableDirtyCheckBox.Checked = true;
                _isFormDirty = true;
            }
            //Update the total sales text box before returning.
            var totalTaxable = 0.00;
            if (sundayTaxableTextBox.Text != "") totalTaxable += double.Parse(sundayTaxableTextBox.Text);
            if (mondayTaxableTextBox.Text != "") totalTaxable += double.Parse(mondayTaxableTextBox.Text);
            if (tuesdayTaxableTextBox.Text != "") totalTaxable += double.Parse(tuesdayTaxableTextBox.Text);
            if (wednesdayTaxableTextBox.Text != "") totalTaxable += double.Parse(wednesdayTaxableTextBox.Text);
            if (thursdayTaxableTextBox.Text != "") totalTaxable += double.Parse(thursdayTaxableTextBox.Text);
            if (fridayTaxableTextBox.Text != "") totalTaxable += double.Parse(fridayTaxableTextBox.Text);
            if (saturdayTaxableTextBox.Text != "") totalTaxable += double.Parse(saturdayTaxableTextBox.Text);
            if (Math.Abs(totalTaxable) > 0)
            {
                totalTaxableTextBox.Text = totalTaxable.ToString("N", new CultureInfo("en-US"));
            }
            else
            {
                //Check to see if the weekly sales have been added to the database.
                if (isTaxableDirtyCheckBox.Tag == null)
                {
                    //If the tag doesn't have an ID in it then we're clear to simply clear the is dirty flag.
                    isTaxableDirtyCheckBox.Checked = false;
                }
                else if (isTaxableDirtyCheckBox.Tag != null && textBox.Text == "")
                {
                    //If the user has already added the fields to the database but has removed a value
                    //update that accordingly.
                    isTaxableDirtyCheckBox.Checked = true;
                    _isFormDirty = true;
                }
                totalTaxableTextBox.Text = "";
            }
        }

        #endregion

        #region Cost Analysis Events

        /// <summary>
        /// Validates the cost analysis text boxes.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ValidateCostAnalysisValues(object sender, CancelEventArgs e)
        {
            var textBox = (TextBox)sender;
            if (_beginningCellValue == textBox.Text) return;
            //There was a change to the starting value of the text box if we've made it this far.
            if (textBox.Text != "")
            {
                double value;
                if (double.TryParse(textBox.Text.Trim(), out value))
                {
                    //Input is valid so mark the section as dirty.
                    isCostAnalysisDirtyCheckBox.Checked = true;
                    _isFormDirty = true;
                    //And apply formatting.
                    textBox.Text = Math.Round(value, 2).ToString("N", new CultureInfo("en-US"));
                    //Check to see if the number is equal to zero (0) i.e. "0.00".
                    if (textBox.Text == @"0.00") textBox.Text = "";
                }
                else
                {
                    MessageBox.Show(@"The value must be numeric.", @"Input Must be Numeric");
                    textBox.Text = "";
                }
            }
            else
            {
                //Since the text box that fired this event is empty check to see if this group has been committed to the database.
                if (isCostAnalysisDirtyCheckBox.Tag == null)
                {
                    //Since it hasn't check to see if the other text boxes are empty.
                    var isDirty = salesPerManHourTextBox.Text.Trim() == "";
                    if (isDirty)
                    {
                        isCostAnalysisDirtyCheckBox.Checked = false;
                        return;
                    }
                    isDirty = salaryPercentageTextBox.Text.Trim() == "";
                    if (isDirty)
                    {
                        isCostAnalysisDirtyCheckBox.Checked = false;
                        return;
                    }
                    isDirty = salaryDollarsTextBox.Text.Trim() == "";
                    if (isDirty)
                    {
                        isCostAnalysisDirtyCheckBox.Checked = false;
                        return;
                    }
                    isDirty = suppliesTextBox.Text.Trim() == "";
                    if (isDirty)
                    {
                        isCostAnalysisDirtyCheckBox.Checked = false;
                    }
                }
                else if (isCostAnalysisDirtyCheckBox.Tag != null && textBox.Text == "")
                {
                    //If the user has already added the fields to the database but has removed a value
                    //update that accordingly.
                    isCostAnalysisDirtyCheckBox.Checked = true;
                    _isFormDirty = true;
                }
            }
        }

        #endregion

        private void ValidateDateChanged(object sender, DateRangeEventArgs e)
        {
            if (e.Start == _currentActiveDate || !weekEndingCalendar.BoldedDates.Contains(e.Start)) return;
            if (_isFormDirty)
            {
                var result = MessageBox.Show(@"Would you like to save the changes you have made to this record?", @"Changes Detected", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (result == DialogResult.Yes)
                {
                    _currentActiveDate = e.Start;
                }
                else
                {
                    weekEndingCalendar.SelectionStart = _currentActiveDate;
                    return;
                }
            }
            Text = @"Modify Record (Current Record: " + e.Start.ToString("d") + @")";
            //Clear the form state.
            ClearFormState();
            //Load the specified date from the database.
            LoadDate(e.Start);
        }

        private void LoadDate(DateTime date)
        {
            var databaseTracker = new DatabaseTracker();
            var databaseReader = new DatabaseReader();
            var dateId = databaseReader.RetrieveDateIdByDateString(date.ToString("d"), databaseTracker.DatabaseConnectionString);
            var projections = databaseReader.ReturnProjectionsTable(dateId, databaseTracker.DatabaseConnectionString);
            var inventory = databaseReader.ReturnInventoryTable(dateId, databaseTracker.DatabaseConnectionString);
            var actualSales = databaseReader.ReturnActualSales(dateId, databaseTracker.DatabaseConnectionString);
            LoadProjectionsTable(projections);
            LoadInventory(inventory);
            LoadActualSales(actualSales);
            var invoices = databaseReader.ReturnInvoiceTable(dateId, databaseTracker.DatabaseConnectionString);
            var comments = databaseReader.RetrieveComments(int.Parse(dateId), databaseTracker.DatabaseConnectionString);
            if (comments.Count == 2)
            {
                LoadComments(int.Parse(comments[0]), comments[1]);
            }
            else
            {
                LogConsole.WriteToLog(FrmLogConsole.Level.Info, "No comments to display for the date of " + _currentActiveDate.ToString("d") + ".");
                informationLabel.Text += @"No comments to display." + Environment.NewLine;
            }
            var weeklySales = databaseReader.ReturnWeeklySalesFromDateId(dateId,
                databaseTracker.DatabaseConnectionString);
            if (weeklySales.Rows.Count == 1)
            {
                LoadWeeklySales(weeklySales);
            }
            else
            {
                informationLabel.Text += @"No weekly sales to display." + Environment.NewLine;
            }

            var taxable = databaseReader.ReturnTaxableFromDateId(dateId, databaseTracker.DatabaseConnectionString);
            if (taxable.Rows.Count == 1)
            {
                LoadTaxable(taxable);
            }
            else
            {
                informationLabel.Text += @"No taxable data to display." + Environment.NewLine;
            }
            LoadInvoices(invoices);
            var costAnalysis = databaseReader.ReturnCostAnalysis(int.Parse(dateId),
                databaseTracker.DatabaseConnectionString);
            if (costAnalysis.Rows.Count == 1)
            {
                LoadCostAnalysis(costAnalysis);
            }
            else
            {
                informationLabel.Text += @"No cost analysis data to display." + Environment.NewLine;
            }
        }

        private void ClearFormState()
        {
            projectionsDataGridView.CellEnter -= StoreBeginningCellValue;
            projectionsDataGridView.RowLeave -= UpdateUsedAdItemCollectionOnRowLeave;
            projectionsDataGridView.CellValidating -= ValidateSalesDataGridViewCellContents;
            projectionsDataGridView.RowValidating -= ValidateProjectedRow;
            projectionsDataGridView.RowsRemoved -= ProjectionRowRemoved;
            inventoryDataGridView.CellEnter -= StoreBeginningCellValue;
            inventoryDataGridView.RowLeave -= UpdateUsedAdItemCollectionOnRowLeave;
            inventoryDataGridView.CellValidating -= ValidateInventoryCellContents;
            inventoryDataGridView.RowValidating -= ValidateInventoryRow;
            inventoryDataGridView.RowsRemoved -= InventoryRowRemoved;
            actualSalesDataGridView.CellEnter -= StoreBeginningCellValue;
            actualSalesDataGridView.RowLeave -= UpdateUsedAdItemCollectionOnRowLeave;
            actualSalesDataGridView.CellValidating -= ValidateSalesDataGridViewCellContents;
            actualSalesDataGridView.RowValidating -= ValidateActualSalesRow;
            actualSalesDataGridView.RowsRemoved -= ActualSalesRowRemoved;
            invoicesDataGridView.CellEnter -= StoreBeginningCellValue;
            invoicesDataGridView.RowValidating -= ValidateInvoiceRow;
            invoicesDataGridView.CellValidating -= ValidateInvoicesCellContents;
            commentsTextBox.Enter -= StoreBeginningTextBoxValue;
            commentsTextBox.KeyDown -= CheckForKeyCommand;
            commentsTextBox.Leave -= CheckForTextChangeOnLeave;
            sundayWeeklySalesTextBox.Enter -= StoreBeginningTextBoxValue;
            sundayWeeklySalesTextBox.Validating -= ValidateWeeklySales;
            mondayWeeklySalesTextBox.Enter -= StoreBeginningTextBoxValue;
            mondayWeeklySalesTextBox.Validating -= ValidateWeeklySales;
            tuesdayWeeklySalesTextBox.Enter -= StoreBeginningTextBoxValue;
            tuesdayWeeklySalesTextBox.Validating -= ValidateWeeklySales;
            wednesdayWeeklySalesTextBox.Enter -= StoreBeginningTextBoxValue;
            wednesdayWeeklySalesTextBox.Validating -= ValidateWeeklySales;
            thursdayWeeklySalesTextBox.Enter -= StoreBeginningTextBoxValue;
            thursdayWeeklySalesTextBox.Validating -= ValidateWeeklySales;
            fridayWeeklySalesTextBox.Enter -= StoreBeginningTextBoxValue;
            fridayWeeklySalesTextBox.Validating -= ValidateWeeklySales;
            saturdayWeeklySalesTextBox.Enter -= StoreBeginningTextBoxValue;
            saturdayWeeklySalesTextBox.Validating -= ValidateWeeklySales;
            totalWeeklySalesTextBox.Enter -= StoreBeginningTextBoxValue;
            totalWeeklySalesTextBox.Validating -= ValidateWeeklySales;
            sundayTaxableTextBox.Enter -= StoreBeginningTextBoxValue;
            sundayTaxableTextBox.Validating -= ValidateTaxableFields;
            mondayTaxableTextBox.Enter -= StoreBeginningTextBoxValue;
            mondayTaxableTextBox.Validating -= ValidateTaxableFields;
            tuesdayTaxableTextBox.Enter -= StoreBeginningTextBoxValue;
            tuesdayTaxableTextBox.Validating -= ValidateTaxableFields;
            wednesdayTaxableTextBox.Enter -= StoreBeginningTextBoxValue;
            wednesdayTaxableTextBox.Validating -= ValidateTaxableFields;
            thursdayTaxableTextBox.Enter -= StoreBeginningTextBoxValue;
            thursdayTaxableTextBox.Validating -= ValidateTaxableFields;
            fridayTaxableTextBox.Enter -= StoreBeginningTextBoxValue;
            fridayTaxableTextBox.Validating -= ValidateTaxableFields;
            saturdayTaxableTextBox.Enter -= StoreBeginningTextBoxValue;
            saturdayTaxableTextBox.Validating -= ValidateTaxableFields;
            totalTaxableTextBox.Enter -= StoreBeginningTextBoxValue;
            totalTaxableTextBox.Validating -= ValidateTaxableFields;
            salesPerManHourTextBox.Enter -= StoreBeginningTextBoxValue;
            salesPerManHourTextBox.Validating -= ValidateCostAnalysisValues;
            salaryPercentageTextBox.Enter -= StoreBeginningTextBoxValue;
            salaryPercentageTextBox.Validating -= ValidateCostAnalysisValues;
            salaryDollarsTextBox.Enter -= StoreBeginningTextBoxValue;
            salaryDollarsTextBox.Validating -= ValidateCostAnalysisValues;
            suppliesTextBox.Enter -= StoreBeginningTextBoxValue;
            suppliesTextBox.Validating -= ValidateCostAnalysisValues;
            //Clear errors and information.
            informationLabel.Text = "";
            errorLabel.Text = "";
            //Clear projections
            projectionsDataGridView.Rows.Clear();
            //Clear inventory
            inventoryDataGridView.Rows.Clear();
            //Clear actual sales
            actualSalesDataGridView.Rows.Clear();
            //Reset the ad special index.
            _adSpecialIndex = -1;
            //Clear the beginning cell value variable.
            _beginningCellValue = "";
            //Reset the form's dirty flag
            _isFormDirty = false;
            //Clear invoices
            invoicesDataGridView.Rows.Clear();
            //Clear comments
            isCommentDirtyCheckBox.Checked = false;
            isCommentDirtyCheckBox.Text = @"IsCommentDirty";
            isCommentDirtyCheckBox.Tag = null;
            commentsTextBox.Text = "";
            commentsGroupBox.Text = @"Comments (Characters Remaining: " + commentsTextBox.MaxLength + @")";
            //Clear weekly sales.
            isWeeklySalesDirtyCheckBox.Checked = false;
            isWeeklySalesDirtyCheckBox.Text = @"IsWeeklySalesDirty";
            isWeeklySalesDirtyCheckBox.Tag = null;
            sundayWeeklySalesTextBox.Text = "";
            mondayWeeklySalesTextBox.Text = "";
            tuesdayWeeklySalesTextBox.Text = "";
            wednesdayWeeklySalesTextBox.Text = "";
            thursdayWeeklySalesTextBox.Text = "";
            fridayWeeklySalesTextBox.Text = "";
            saturdayWeeklySalesTextBox.Text = "";
            totalWeeklySalesTextBox.Text = "";
            //Clear taxable.
            isTaxableDirtyCheckBox.Checked = false;
            isTaxableDirtyCheckBox.Text = @"IsTaxableDirty";
            isTaxableDirtyCheckBox.Tag = null;
            sundayTaxableTextBox.Text = "";
            mondayTaxableTextBox.Text = "";
            tuesdayTaxableTextBox.Text = "";
            wednesdayTaxableTextBox.Text = "";
            thursdayTaxableTextBox.Text = "";
            fridayTaxableTextBox.Text = "";
            saturdayTaxableTextBox.Text = "";
            totalTaxableTextBox.Text = "";
            //Clear cost analysis
            isCostAnalysisDirtyCheckBox.Checked = false;
            isCostAnalysisDirtyCheckBox.Text = @"IsCostAnalysisDirty";
            isCostAnalysisDirtyCheckBox.Tag = null;
            salesPerManHourTextBox.Text = "";
            salaryPercentageTextBox.Text = "";
            salaryDollarsTextBox.Text = "";
            suppliesTextBox.Text = "";
            //Re-enable the events for all the controls.
            projectionsDataGridView.CellEnter += StoreBeginningCellValue;
            projectionsDataGridView.RowLeave += UpdateUsedAdItemCollectionOnRowLeave;
            projectionsDataGridView.CellValidating += ValidateSalesDataGridViewCellContents;
            projectionsDataGridView.RowValidating += ValidateProjectedRow;
            projectionsDataGridView.RowsRemoved += ProjectionRowRemoved;
            inventoryDataGridView.CellEnter += StoreBeginningCellValue;
            inventoryDataGridView.RowLeave += UpdateUsedAdItemCollectionOnRowLeave;
            inventoryDataGridView.CellValidating += ValidateInventoryCellContents;
            inventoryDataGridView.RowValidating += ValidateInventoryRow;
            inventoryDataGridView.RowsRemoved += InventoryRowRemoved;
            actualSalesDataGridView.CellEnter += StoreBeginningCellValue;
            actualSalesDataGridView.RowLeave += UpdateUsedAdItemCollectionOnRowLeave;
            actualSalesDataGridView.CellValidating += ValidateSalesDataGridViewCellContents;
            actualSalesDataGridView.RowValidating += ValidateActualSalesRow;
            actualSalesDataGridView.RowsRemoved += ActualSalesRowRemoved;

            invoicesDataGridView.CellEnter += StoreBeginningCellValue;
            invoicesDataGridView.RowValidating += ValidateInvoiceRow;
            invoicesDataGridView.CellValidating += ValidateInvoicesCellContents;

            commentsTextBox.Enter += StoreBeginningTextBoxValue;
            commentsTextBox.KeyDown += CheckForKeyCommand;
            commentsTextBox.Leave += CheckForTextChangeOnLeave;

            sundayWeeklySalesTextBox.Enter += StoreBeginningTextBoxValue;
            sundayWeeklySalesTextBox.Validating += ValidateWeeklySales;
            mondayWeeklySalesTextBox.Enter += StoreBeginningTextBoxValue;
            mondayWeeklySalesTextBox.Validating += ValidateWeeklySales;
            tuesdayWeeklySalesTextBox.Enter += StoreBeginningTextBoxValue;
            tuesdayWeeklySalesTextBox.Validating += ValidateWeeklySales;
            wednesdayWeeklySalesTextBox.Enter += StoreBeginningTextBoxValue;
            wednesdayWeeklySalesTextBox.Validating += ValidateWeeklySales;
            thursdayWeeklySalesTextBox.Enter += StoreBeginningTextBoxValue;
            thursdayWeeklySalesTextBox.Validating += ValidateWeeklySales;
            fridayWeeklySalesTextBox.Enter += StoreBeginningTextBoxValue;
            fridayWeeklySalesTextBox.Validating += ValidateWeeklySales;
            saturdayWeeklySalesTextBox.Enter += StoreBeginningTextBoxValue;
            saturdayWeeklySalesTextBox.Validating += ValidateWeeklySales;
            totalWeeklySalesTextBox.Enter += StoreBeginningTextBoxValue;
            totalWeeklySalesTextBox.Validating += ValidateWeeklySales;

            sundayTaxableTextBox.Enter += StoreBeginningTextBoxValue;
            sundayTaxableTextBox.Validating += ValidateTaxableFields;
            mondayTaxableTextBox.Enter += StoreBeginningTextBoxValue;
            mondayTaxableTextBox.Validating += ValidateTaxableFields;
            tuesdayTaxableTextBox.Enter += StoreBeginningTextBoxValue;
            tuesdayTaxableTextBox.Validating += ValidateTaxableFields;
            wednesdayTaxableTextBox.Enter += StoreBeginningTextBoxValue;
            wednesdayTaxableTextBox.Validating += ValidateTaxableFields;
            thursdayTaxableTextBox.Enter += StoreBeginningTextBoxValue;
            thursdayTaxableTextBox.Validating += ValidateTaxableFields;
            fridayTaxableTextBox.Enter += StoreBeginningTextBoxValue;
            fridayTaxableTextBox.Validating += ValidateTaxableFields;
            saturdayTaxableTextBox.Enter += StoreBeginningTextBoxValue;
            saturdayTaxableTextBox.Validating += ValidateTaxableFields;
            totalTaxableTextBox.Enter += StoreBeginningTextBoxValue;
            totalTaxableTextBox.Validating += ValidateTaxableFields;

            salesPerManHourTextBox.Enter += StoreBeginningTextBoxValue;
            salesPerManHourTextBox.Validating += ValidateCostAnalysisValues;
            salaryPercentageTextBox.Enter += StoreBeginningTextBoxValue;
            salaryPercentageTextBox.Validating += ValidateCostAnalysisValues;
            salaryDollarsTextBox.Enter += StoreBeginningTextBoxValue;
            salaryDollarsTextBox.Validating += ValidateCostAnalysisValues;
            suppliesTextBox.Enter += StoreBeginningTextBoxValue;
            suppliesTextBox.Validating += ValidateCostAnalysisValues;
        }

        #region Data Loading Methods

        private void LoadProjectionsTable(DataTable projections)
        {
            //Assuming all the tables are correctly aligned.
            //Disable the relevant events in the DataGridViews
            projectionsDataGridView.CellEnter -= StoreBeginningCellValue;
            projectionsDataGridView.RowLeave -= UpdateUsedAdItemCollectionOnRowLeave;
            projectionsDataGridView.CellValidating -= ValidateSalesDataGridViewCellContents;
            projectionsDataGridView.RowValidating -= ValidateProjectedRow;

            for(var rowIndex = 0; rowIndex < projections.Rows.Count; rowIndex++)
            {
                var newRow = new DataGridViewRow();
                for (var cellIndex = 0; cellIndex < projections.Rows[rowIndex].ItemArray.Length; cellIndex++)
                {
                    //ID and Ad Item.
                    if (cellIndex <= 1)
                    {
                        var cell = new DataGridViewTextBoxCell
                        {
                            Value = projections.Rows[rowIndex].ItemArray[cellIndex].ToString()
                        };
                        newRow.Cells.Add(cell);
                        continue;
                    }
                    //Everything in between the ad item cell and the row attribute cells.
                    if (cellIndex > 1 && cellIndex <= 7)
                    {
                        if (projections.Rows[rowIndex].ItemArray[cellIndex].ToString() == "0")
                        {
                            var cell = new DataGridViewTextBoxCell {Value = ""};
                            newRow.Cells.Add(cell);
                        }
                        else
                        {
                            var cell = new DataGridViewTextBoxCell { Value = projections.Rows[rowIndex].ItemArray[cellIndex].ToString() };
                            newRow.Cells.Add(cell);
                        }
                        continue;
                    }
                    //Check the attribute cell.
                    if (cellIndex == 8)
                    {
                        var isHeaderCell = new DataGridViewCheckBoxCell(false);
                        var isMemberCell = new DataGridViewCheckBoxCell(false);
                        var rowAttribute = int.Parse(projections.Rows[rowIndex].ItemArray[cellIndex].ToString());
                        switch (rowAttribute)
                        {
                            case 1:
                                //Header row
                                isHeaderCell.Value = true;
                                newRow.DefaultCellStyle.BackColor = ApplicationColors.HeaderRow;
                                break;
                            case 2:
                                //Member Row
                                isMemberCell.Value = true;
                                newRow.DefaultCellStyle.BackColor = ApplicationColors.MemberRow;
                                break;
                        }
                        newRow.Cells.Add(isHeaderCell);
                        newRow.Cells.Add(isMemberCell);
                        continue;
                    }
                    //Check the group it is part of if any.
                    if (cellIndex == 9)
                    {
                        if (projections.Rows[rowIndex].ItemArray[cellIndex].ToString() != "0" && _adSpecialIndex == -1)
                        {
                            var databaseTracker = new DatabaseTracker();
                            var databaseReader = new DatabaseReader();
                            var groupName =
                                databaseReader.ReturnGroupNameFromGroupId(
                                    projections.Rows[rowIndex].ItemArray[cellIndex].ToString(),
                                    databaseTracker.DatabaseConnectionString);
                            var adSpecialRow = new DataGridViewRow();
                            projectionsDataGridView.Rows.Add(adSpecialRow);
                            projectionsDataGridView.Rows[rowIndex].Cells[1].Value = groupName;
                            projectionsDataGridView.Rows[rowIndex].DefaultCellStyle.BackColor = ApplicationColors.AdSpecial;
                            _adSpecialIndex = rowIndex;
                        }
                    }                 
                }
                projectionsDataGridView.Rows.Add(newRow);
            }
            //Re-enable the events
            projectionsDataGridView.CellEnter += StoreBeginningCellValue;
            projectionsDataGridView.RowLeave += UpdateUsedAdItemCollectionOnRowLeave;
            projectionsDataGridView.CellValidating += ValidateSalesDataGridViewCellContents;
            projectionsDataGridView.RowValidating += ValidateProjectedRow;
        }

        private void LoadInventory(DataTable inventoryTable)
        {
            //Assuming all the tables are correctly aligned.
            //Disable the relevant events in the DataGridViews
            inventoryDataGridView.CellEnter -= StoreBeginningCellValue;
            inventoryDataGridView.RowLeave -= UpdateUsedAdItemCollectionOnRowLeave;
            inventoryDataGridView.CellValidating -= ValidateInventoryCellContents;
            inventoryDataGridView.RowValidating -= ValidateInventoryRow;
            //Create a local ad special index since Projections should have filled the ad special index in for the class.
            var adSpecialIndex = -1;

            for (var rowIndex = 0; rowIndex < inventoryTable.Rows.Count; rowIndex++)
            {
                var newRow = new DataGridViewRow();
                for (var cellIndex = 0; cellIndex < inventoryTable.Rows[rowIndex].ItemArray.Length; cellIndex++)
                {
                    //ID and Ad Item.
                    if (cellIndex <= 1)
                    {
                        var cell = new DataGridViewTextBoxCell
                        {
                            Value = inventoryTable.Rows[rowIndex].ItemArray[cellIndex].ToString()
                        };
                        newRow.Cells.Add(cell);
                        continue;
                    }
                    //Everything in between the ad item cell and the row attribute cells.
                    if (cellIndex > 1 && cellIndex <= 5)
                    {
                        if (inventoryTable.Rows[rowIndex].ItemArray[cellIndex].ToString() == "0")
                        {
                            var cell = new DataGridViewTextBoxCell { Value = "" };
                            newRow.Cells.Add(cell);
                        }
                        else
                        {
                            var cell = new DataGridViewTextBoxCell { Value = inventoryTable.Rows[rowIndex].ItemArray[cellIndex].ToString() };
                            newRow.Cells.Add(cell);
                        }
                        continue;
                    }
                    //Check the attribute cell.
                    if (cellIndex == 6)
                    {
                        var isHeaderCell = new DataGridViewCheckBoxCell(false);
                        var isMemberCell = new DataGridViewCheckBoxCell(false);
                        var rowAttribute = int.Parse(inventoryTable.Rows[rowIndex].ItemArray[cellIndex].ToString());
                        switch (rowAttribute)
                        {
                            case 1:
                                //Header row
                                isHeaderCell.Value = true;
                                newRow.DefaultCellStyle.BackColor = ApplicationColors.HeaderRow;
                                break;
                            case 2:
                                //Member Row
                                isMemberCell.Value = true;
                                newRow.DefaultCellStyle.BackColor = ApplicationColors.MemberRow;
                                break;
                        }
                        newRow.Cells.Add(isHeaderCell);
                        newRow.Cells.Add(isMemberCell);
                        continue;
                    }
                    //Check the group it is part of if any.
                    if (cellIndex == 7)
                    {
                        if (inventoryTable.Rows[rowIndex].ItemArray[cellIndex].ToString() != "0" && adSpecialIndex == -1)
                        {
                            var databaseTracker = new DatabaseTracker();
                            var databaseReader = new DatabaseReader();
                            var groupName =
                                databaseReader.ReturnGroupNameFromGroupId(
                                    inventoryTable.Rows[rowIndex].ItemArray[cellIndex].ToString(),
                                    databaseTracker.DatabaseConnectionString);
                            var adSpecialRow = new DataGridViewRow();
                            inventoryDataGridView.Rows.Add(adSpecialRow);
                            inventoryDataGridView.Rows[rowIndex].Cells[1].Value = groupName;
                            inventoryDataGridView.Rows[rowIndex].DefaultCellStyle.BackColor = ApplicationColors.AdSpecial;
                            adSpecialIndex = rowIndex;
                        }
                    }
                }
               inventoryDataGridView.Rows.Add(newRow);
            }
            //Re-enable the events
            inventoryDataGridView.CellEnter += StoreBeginningCellValue;
            inventoryDataGridView.RowLeave += UpdateUsedAdItemCollectionOnRowLeave;
            inventoryDataGridView.CellValidating += ValidateInventoryCellContents;
            inventoryDataGridView.RowValidating += ValidateInventoryRow;
        }

        public void LoadActualSales(DataTable actualSales)
        {
            //Assuming all the tables are correctly aligned.
            //Disable the relevant events in the DataGridViews
            actualSalesDataGridView.CellEnter -= StoreBeginningCellValue;
            actualSalesDataGridView.RowLeave -= UpdateUsedAdItemCollectionOnRowLeave;
            actualSalesDataGridView.CellValidating -= ValidateSalesDataGridViewCellContents;
            actualSalesDataGridView.RowValidating -= ValidateActualSalesRow;
            //Create a local ad special index since Projections should have filled the ad special index in for the class.
            var adSpecialIndex = -1;

            for (var rowIndex = 0; rowIndex < actualSales.Rows.Count; rowIndex++)
            {
                var newRow = new DataGridViewRow();
                for (var cellIndex = 0; cellIndex < actualSales.Rows[rowIndex].ItemArray.Length; cellIndex++)
                {
                    //ID and Ad Item.
                    if (cellIndex <= 1)
                    {
                        var cell = new DataGridViewTextBoxCell
                        {
                            Value = actualSales.Rows[rowIndex].ItemArray[cellIndex].ToString()
                        };
                        newRow.Cells.Add(cell);
                        continue;
                    }
                    //Everything in between the ad item cell and the row attribute cells.
                    if (cellIndex > 1 && cellIndex <= 7)
                    {
                        if (actualSales.Rows[rowIndex].ItemArray[cellIndex].ToString() == "0")
                        {
                            var cell = new DataGridViewTextBoxCell { Value = "" };
                            newRow.Cells.Add(cell);
                        }
                        else
                        {
                            var cell = new DataGridViewTextBoxCell { Value = actualSales.Rows[rowIndex].ItemArray[cellIndex].ToString() };
                            newRow.Cells.Add(cell);
                        }
                        continue;
                    }
                    //Check the attribute cell.
                    if (cellIndex == 8)
                    {
                        var isHeaderCell = new DataGridViewCheckBoxCell(false);
                        var isMemberCell = new DataGridViewCheckBoxCell(false);
                        var rowAttribute = int.Parse(actualSales.Rows[rowIndex].ItemArray[cellIndex].ToString());
                        switch (rowAttribute)
                        {
                            case 1:
                                //Header row
                                isHeaderCell.Value = true;
                                newRow.DefaultCellStyle.BackColor = ApplicationColors.HeaderRow;
                                break;
                            case 2:
                                //Member Row
                                isMemberCell.Value = true;
                                newRow.DefaultCellStyle.BackColor = ApplicationColors.MemberRow;
                                break;
                        }
                        newRow.Cells.Add(isHeaderCell);
                        newRow.Cells.Add(isMemberCell);
                        continue;
                    }
                    //Check the group it is part of if any.
                    if (cellIndex == 9)
                    {
                        if (actualSales.Rows[rowIndex].ItemArray[cellIndex].ToString() != "0" && adSpecialIndex == -1)
                        {
                            var databaseTracker = new DatabaseTracker();
                            var databaseReader = new DatabaseReader();
                            var groupName =
                                databaseReader.ReturnGroupNameFromGroupId(
                                    actualSales.Rows[rowIndex].ItemArray[cellIndex].ToString(),
                                    databaseTracker.DatabaseConnectionString);
                            var adSpecialRow = new DataGridViewRow();
                            actualSalesDataGridView.Rows.Add(adSpecialRow);
                            actualSalesDataGridView.Rows[rowIndex].Cells[1].Value = groupName;
                            actualSalesDataGridView.Rows[rowIndex].DefaultCellStyle.BackColor = ApplicationColors.AdSpecial;
                            adSpecialIndex = rowIndex;
                        }
                    }
                }
                actualSalesDataGridView.Rows.Add(newRow);
            }
            //Re-enable the events
            actualSalesDataGridView.CellEnter += StoreBeginningCellValue;
            actualSalesDataGridView.RowLeave += UpdateUsedAdItemCollectionOnRowLeave;
            actualSalesDataGridView.CellValidating += ValidateSalesDataGridViewCellContents;
            actualSalesDataGridView.RowValidating += ValidateActualSalesRow;
        }

        private void LoadInvoices(DataTable invoices)
        {
            for (var rowIndex = 0; rowIndex < invoices.Rows.Count; rowIndex++)
            {
                var row = new DataGridViewRow();
                for (var cellIndex = 0; cellIndex < invoices.Rows[rowIndex].ItemArray.Length; cellIndex++)
                {
                    //Get the 
                    //Format the invoice date.
                    if (cellIndex == 1)
                    {
                        var date = DateTime.Parse(invoices.Rows[rowIndex].ItemArray[cellIndex].ToString());
                        var cell = new DataGridViewTextBoxCell
                        {
                            Value = date.ToString("d")
                        };
                        row.Cells.Add(cell);
                        continue;
                    }
                    if (invoices.Rows[rowIndex].ItemArray[cellIndex].ToString() != "0")
                    {
                        var cell = new DataGridViewTextBoxCell
                        {
                            Value = invoices.Rows[rowIndex].ItemArray[cellIndex].ToString()
                        };
                        row.Cells.Add(cell);
                    }
                    else
                    {
                        var cell = new DataGridViewTextBoxCell
                        {
                            Value = ""
                        };
                        row.Cells.Add(cell);
                    }
                }
                invoicesDataGridView.Rows.Add(row);
            }
        }

        private void LoadComments(int id, string comments)
        {
            //commentsTextBox.TextChanged -= DisplayRemainingCommentCharacterCount;
            commentsTextBox.Enter -= StoreBeginningTextBoxValue;
            commentsTextBox.KeyDown -= CheckForKeyCommand;
            commentsTextBox.Leave -= CheckForTextChangeOnLeave;

            isCommentDirtyCheckBox.Text = @"isCommentsDirty (" + id + @")";
            isCommentDirtyCheckBox.Tag = id;

            commentsTextBox.Text = comments;

            //commentsGroupBox.Text = @"Comments (Characters Remaining: " + commentsTextBox.MaxLength + @")";
            //commentsTextBox.TextChanged += DisplayRemainingCommentCharacterCount;
            commentsTextBox.Enter += StoreBeginningTextBoxValue;
            commentsTextBox.KeyDown += CheckForKeyCommand;
            commentsTextBox.Leave += CheckForTextChangeOnLeave;
        }

        private void LoadWeeklySales(DataTable weeklySales)
        {
            sundayWeeklySalesTextBox.Enter -= StoreBeginningTextBoxValue;
            sundayWeeklySalesTextBox.Validating -= ValidateWeeklySales;
            mondayWeeklySalesTextBox.Enter -= StoreBeginningTextBoxValue;
            mondayWeeklySalesTextBox.Validating -= ValidateWeeklySales;
            tuesdayWeeklySalesTextBox.Enter -= StoreBeginningTextBoxValue;
            tuesdayWeeklySalesTextBox.Validating -= ValidateWeeklySales;
            wednesdayWeeklySalesTextBox.Enter -= StoreBeginningTextBoxValue;
            wednesdayWeeklySalesTextBox.Validating -= ValidateWeeklySales;
            thursdayWeeklySalesTextBox.Enter -= StoreBeginningTextBoxValue;
            thursdayWeeklySalesTextBox.Validating -= ValidateWeeklySales;
            fridayWeeklySalesTextBox.Enter -= StoreBeginningTextBoxValue;
            fridayWeeklySalesTextBox.Validating -= ValidateWeeklySales;
            saturdayWeeklySalesTextBox.Enter -= StoreBeginningTextBoxValue;
            saturdayWeeklySalesTextBox.Validating -= ValidateWeeklySales;
            totalWeeklySalesTextBox.Enter -= StoreBeginningTextBoxValue;
            totalWeeklySalesTextBox.Validating -= ValidateWeeklySales;

            //Spin through the only row in the weekly sales table. Item in item 
            //array index zero (0) is the ID number of the weekly sales.
            for (var cellIndex = 0; cellIndex < weeklySales.Rows[0].ItemArray.Length; cellIndex++)
            {
                if (cellIndex == 0)
                {
                    //ID number
                    var id = int.Parse(weeklySales.Rows[0].ItemArray[cellIndex].ToString());
                    isWeeklySalesDirtyCheckBox.Tag = id;
                    isWeeklySalesDirtyCheckBox.Text = @"IsWeeklySalesDirty (" + id + @")";
                    continue;
                }
                string formattedNumber;
                switch (cellIndex)
                {
                    case 1: //Sunday
                        formattedNumber = Math.Round(double.Parse(weeklySales.Rows[0].ItemArray[cellIndex].ToString()), 2).ToString("N", new CultureInfo("en-US"));
                        if (formattedNumber != "0.00")
                        {
                            sundayWeeklySalesTextBox.Text = formattedNumber;
                        }
                        break;
                    case 2: //Monday
                        formattedNumber = Math.Round(double.Parse(weeklySales.Rows[0].ItemArray[cellIndex].ToString()), 2).ToString("N", new CultureInfo("en-US"));
                        if (formattedNumber != "0.00")
                        {
                            mondayWeeklySalesTextBox.Text = formattedNumber;
                        }
                        break;
                    case 3: //Tuesday
                        formattedNumber = Math.Round(double.Parse(weeklySales.Rows[0].ItemArray[cellIndex].ToString()), 2).ToString("N", new CultureInfo("en-US"));
                        if (formattedNumber != "0.00")
                        {
                            tuesdayWeeklySalesTextBox.Text = formattedNumber;
                        }
                        break;
                    case 4: //Wednesday
                        formattedNumber = Math.Round(double.Parse(weeklySales.Rows[0].ItemArray[cellIndex].ToString()), 2).ToString("N", new CultureInfo("en-US"));
                        if (formattedNumber != "0.00")
                        {
                            wednesdayWeeklySalesTextBox.Text = formattedNumber;
                        }
                        break;
                    case 5: //Thursday
                        formattedNumber = Math.Round(double.Parse(weeklySales.Rows[0].ItemArray[cellIndex].ToString()), 2).ToString("N", new CultureInfo("en-US"));
                        if (formattedNumber != "0.00")
                        {
                            thursdayWeeklySalesTextBox.Text = formattedNumber;
                        }
                        break;
                    case 6: //Friday
                        formattedNumber = Math.Round(double.Parse(weeklySales.Rows[0].ItemArray[cellIndex].ToString()), 2).ToString("N", new CultureInfo("en-US"));
                        if (formattedNumber != "0.00")
                        {
                            fridayWeeklySalesTextBox.Text = formattedNumber;
                        }
                        break;
                    case 7: //Saturday
                        formattedNumber = Math.Round(double.Parse(weeklySales.Rows[0].ItemArray[cellIndex].ToString()), 2).ToString("N", new CultureInfo("en-US"));
                        if (formattedNumber != "0.00")
                        {
                            saturdayWeeklySalesTextBox.Text = formattedNumber;
                        }
                        break;
                    case 8: //Total Sales
                        formattedNumber = Math.Round(double.Parse(weeklySales.Rows[0].ItemArray[cellIndex].ToString()), 2).ToString("N", new CultureInfo("en-US"));
                        if (formattedNumber != "0.00")
                        {
                            totalWeeklySalesTextBox.Text = formattedNumber;
                        }
                        break;
                }
            }

            sundayWeeklySalesTextBox.Enter += StoreBeginningTextBoxValue;
            sundayWeeklySalesTextBox.Validating += ValidateWeeklySales;
            mondayWeeklySalesTextBox.Enter += StoreBeginningTextBoxValue;
            mondayWeeklySalesTextBox.Validating += ValidateWeeklySales;
            tuesdayWeeklySalesTextBox.Enter += StoreBeginningTextBoxValue;
            tuesdayWeeklySalesTextBox.Validating += ValidateWeeklySales;
            wednesdayWeeklySalesTextBox.Enter += StoreBeginningTextBoxValue;
            wednesdayWeeklySalesTextBox.Validating += ValidateWeeklySales;
            thursdayWeeklySalesTextBox.Enter += StoreBeginningTextBoxValue;
            thursdayWeeklySalesTextBox.Validating += ValidateWeeklySales;
            fridayWeeklySalesTextBox.Enter += StoreBeginningTextBoxValue;
            fridayWeeklySalesTextBox.Validating += ValidateWeeklySales;
            saturdayWeeklySalesTextBox.Enter += StoreBeginningTextBoxValue;
            saturdayWeeklySalesTextBox.Validating += ValidateWeeklySales;
            totalWeeklySalesTextBox.Enter += StoreBeginningTextBoxValue;
            totalWeeklySalesTextBox.Validating += ValidateWeeklySales;
        }

        private void LoadTaxable(DataTable taxable)
        {
            sundayTaxableTextBox.Enter -= StoreBeginningTextBoxValue;
            sundayTaxableTextBox.Validating -= ValidateTaxableFields;
            mondayTaxableTextBox.Enter -= StoreBeginningTextBoxValue;
            mondayTaxableTextBox.Validating -= ValidateTaxableFields;
            tuesdayTaxableTextBox.Enter -= StoreBeginningTextBoxValue;
            tuesdayTaxableTextBox.Validating -= ValidateTaxableFields;
            wednesdayTaxableTextBox.Enter -= StoreBeginningTextBoxValue;
            wednesdayTaxableTextBox.Validating -= ValidateTaxableFields;
            thursdayTaxableTextBox.Enter -= StoreBeginningTextBoxValue;
            thursdayTaxableTextBox.Validating -= ValidateTaxableFields;
            fridayTaxableTextBox.Enter -= StoreBeginningTextBoxValue;
            fridayTaxableTextBox.Validating -= ValidateTaxableFields;
            saturdayTaxableTextBox.Enter -= StoreBeginningTextBoxValue;
            saturdayTaxableTextBox.Validating -= ValidateTaxableFields;
            totalTaxableTextBox.Enter -= StoreBeginningTextBoxValue;
            totalTaxableTextBox.Validating -= ValidateTaxableFields;
            //Spin through the only row in the taxable table. Item in item 
            //array index zero (0) is the ID number of the weekly sales.
            for (var cellIndex = 0; cellIndex < taxable.Rows[0].ItemArray.Length; cellIndex++)
            {
                if (cellIndex == 0)
                {
                    //ID number
                    var id = int.Parse(taxable.Rows[0].ItemArray[cellIndex].ToString());
                    isTaxableDirtyCheckBox.Tag = id;
                    isTaxableDirtyCheckBox.Text = @"IsTaxableDirty (" + id + @")";
                    continue;
                }
                string formattedNumber;
                switch (cellIndex)
                {
                    case 1: //Sunday
                        formattedNumber = Math.Round(double.Parse(taxable.Rows[0].ItemArray[cellIndex].ToString()), 2).ToString("N", new CultureInfo("en-US"));
                        if (formattedNumber != "0.00")
                        {
                            sundayTaxableTextBox.Text = formattedNumber;
                        }
                        break;
                    case 2: //Monday
                        formattedNumber = Math.Round(double.Parse(taxable.Rows[0].ItemArray[cellIndex].ToString()), 2).ToString("N", new CultureInfo("en-US"));
                        if (formattedNumber != "0.00")
                        {
                            mondayTaxableTextBox.Text = formattedNumber;
                        }
                        break;
                    case 3: //Tuesday
                        formattedNumber = Math.Round(double.Parse(taxable.Rows[0].ItemArray[cellIndex].ToString()), 2).ToString("N", new CultureInfo("en-US"));
                        if (formattedNumber != "0.00")
                        {
                            tuesdayTaxableTextBox.Text = formattedNumber;
                        }
                        break;
                    case 4: //Wednesday
                        formattedNumber = Math.Round(double.Parse(taxable.Rows[0].ItemArray[cellIndex].ToString()), 2).ToString("N", new CultureInfo("en-US"));
                        if (formattedNumber != "0.00")
                        {
                            wednesdayTaxableTextBox.Text = formattedNumber;
                        }
                        break;
                    case 5: //Thursday
                        formattedNumber = Math.Round(double.Parse(taxable.Rows[0].ItemArray[cellIndex].ToString()), 2).ToString("N", new CultureInfo("en-US"));
                        if (formattedNumber != "0.00")
                        {
                            thursdayTaxableTextBox.Text = formattedNumber;
                        }
                        break;
                    case 6: //Friday
                        formattedNumber = Math.Round(double.Parse(taxable.Rows[0].ItemArray[cellIndex].ToString()), 2).ToString("N", new CultureInfo("en-US"));
                        if (formattedNumber != "0.00")
                        {
                            fridayTaxableTextBox.Text = formattedNumber;
                        }
                        break;
                    case 7: //Saturday
                        formattedNumber = Math.Round(double.Parse(taxable.Rows[0].ItemArray[cellIndex].ToString()), 2).ToString("N", new CultureInfo("en-US"));
                        if (formattedNumber != "0.00")
                        {
                            saturdayTaxableTextBox.Text = formattedNumber;
                        }
                        break;
                    case 8: //Total Taxable
                        formattedNumber = Math.Round(double.Parse(taxable.Rows[0].ItemArray[cellIndex].ToString()), 2).ToString("N", new CultureInfo("en-US"));
                        if (formattedNumber != "0.00")
                        {
                            totalTaxableTextBox.Text = formattedNumber;
                        }
                        break;
                }
            }
            sundayTaxableTextBox.Enter += StoreBeginningTextBoxValue;
            sundayTaxableTextBox.Validating += ValidateTaxableFields;
            mondayTaxableTextBox.Enter += StoreBeginningTextBoxValue;
            mondayTaxableTextBox.Validating += ValidateTaxableFields;
            tuesdayTaxableTextBox.Enter += StoreBeginningTextBoxValue;
            tuesdayTaxableTextBox.Validating += ValidateTaxableFields;
            wednesdayTaxableTextBox.Enter += StoreBeginningTextBoxValue;
            wednesdayTaxableTextBox.Validating += ValidateTaxableFields;
            thursdayTaxableTextBox.Enter += StoreBeginningTextBoxValue;
            thursdayTaxableTextBox.Validating += ValidateTaxableFields;
            fridayTaxableTextBox.Enter += StoreBeginningTextBoxValue;
            fridayTaxableTextBox.Validating += ValidateTaxableFields;
            saturdayTaxableTextBox.Enter += StoreBeginningTextBoxValue;
            saturdayTaxableTextBox.Validating += ValidateTaxableFields;
            totalTaxableTextBox.Enter += StoreBeginningTextBoxValue;
            totalTaxableTextBox.Validating += ValidateTaxableFields;
        }

        private void LoadCostAnalysis(DataTable costAnalysis)
        {
            salesPerManHourTextBox.Enter -= StoreBeginningTextBoxValue;
            salesPerManHourTextBox.Validating -= ValidateCostAnalysisValues;
            salaryPercentageTextBox.Enter -= StoreBeginningTextBoxValue;
            salaryPercentageTextBox.Validating -= ValidateCostAnalysisValues;
            salaryDollarsTextBox.Enter -= StoreBeginningTextBoxValue;
            salaryDollarsTextBox.Validating -= ValidateCostAnalysisValues;
            suppliesTextBox.Enter -= StoreBeginningTextBoxValue;
            suppliesTextBox.Validating -= ValidateCostAnalysisValues;
            //Spin through the only row in the taxable table. Item in item 
            //array index zero (0) is the ID number of the weekly sales.
            for (var cellIndex = 0; cellIndex < costAnalysis.Rows[0].ItemArray.Length; cellIndex++)
            {
                if (cellIndex == 0)
                {
                    //ID number
                    var id = int.Parse(costAnalysis.Rows[0].ItemArray[cellIndex].ToString());
                    isCostAnalysisDirtyCheckBox.Tag = id;
                    isCostAnalysisDirtyCheckBox.Text = @"IsCostAnalysisDirty (" + id + @")";
                    continue;
                }
                string formattedNumber;
                switch (cellIndex)
                {
                    case 1: //Sales per man hour
                        formattedNumber = Math.Round(double.Parse(costAnalysis.Rows[0].ItemArray[cellIndex].ToString()), 2).ToString("N", new CultureInfo("en-US"));
                        if (formattedNumber != "0.00")
                        {
                            salesPerManHourTextBox.Text = formattedNumber;
                        }
                        break;
                    case 2: //Salary Percentage
                        formattedNumber = Math.Round(double.Parse(costAnalysis.Rows[0].ItemArray[cellIndex].ToString()), 2).ToString("N", new CultureInfo("en-US"));
                        if (formattedNumber != "0.00")
                        {
                            salaryPercentageTextBox.Text = formattedNumber;
                        }
                        break;
                    case 3: //Salary Dollars
                        formattedNumber = Math.Round(double.Parse(costAnalysis.Rows[0].ItemArray[cellIndex].ToString()), 2).ToString("N", new CultureInfo("en-US"));
                        if (formattedNumber != "0.00")
                        {
                            salaryDollarsTextBox.Text = formattedNumber;
                        }
                        break;
                    case 4: //Supplies
                        formattedNumber = Math.Round(double.Parse(costAnalysis.Rows[0].ItemArray[cellIndex].ToString()), 2).ToString("N", new CultureInfo("en-US"));
                        if (formattedNumber != "0.00")
                        {
                            suppliesTextBox.Text = formattedNumber;
                        }
                        break;
                }
            }
            salesPerManHourTextBox.Enter += StoreBeginningTextBoxValue;
            salesPerManHourTextBox.Validating += ValidateCostAnalysisValues;
            salaryPercentageTextBox.Enter += StoreBeginningTextBoxValue;
            salaryPercentageTextBox.Validating += ValidateCostAnalysisValues;
            salaryDollarsTextBox.Enter += StoreBeginningTextBoxValue;
            salaryDollarsTextBox.Validating += ValidateCostAnalysisValues;
            suppliesTextBox.Enter += StoreBeginningTextBoxValue;
            suppliesTextBox.Validating += ValidateCostAnalysisValues;
        }

        #endregion

        //private void NormalizeApcTables(DataTable projections, DataTable inventory, DataTable actualSales, string dateId)
        //{
            
        //}
    }
}
