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 NewAddRecord : 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();

        public NewAddRecord()
        {
            InitializeComponent();
            //Start by grabbing all the AdItems and putting them into memory.
            var databaseTracker = new DatabaseTracker();
            var databaseReader = new DatabaseReader();
            //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 + @")";
            //Set up the event for when the masked text box looses focus.
            weekEndingMaskedTextBox.LostFocus += UpdateCalendarOnFocusLost;
            //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;
            //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;
        }

        #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("MM/dd/yyyy");
                            dataGridView.Rows[e.RowIndex].HeaderCell.Style.BackColor = ApplicationColors.PendingEdit;
                        }
                        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;
                        }
                        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;
                    }
                    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;
                    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;
                            }
                            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;
        }

        #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;           
            var currentRowIndex = dataGridView.CurrentRow.Index;
            //Remove the ad item from the gUsedAdItem collection, if it exists.
            if (_adSpecialIndex == -1)
            {
                //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 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 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 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());
                        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);
                        }
                    }
                    //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;
            }
            //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;
            }
            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+", "")))
                    {
                        var parser = new RowParsing();
                        if (parser.CheckForGroupKeyWord(userInput) != "NoGroupFound")
                        {
                            _adSpecialIndex = e.RowIndex;
                        }
                        //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);
                        dataGridView.Rows[e.RowIndex].HeaderCell.Style.BackColor = ApplicationColors.PendingEdit;
                        //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;
                        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;
                    }
                    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;
                        //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;
                    }
                    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;
                    }
                    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;
                    inventoryDataGridView.Rows[e.RowIndex].Cells[adItemIndex].Value = adItemText;
                    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;
                    default:
                        if(i >= (int)SalesTableColumns.IsHeaderRow) continue;
                        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)SalesTableColumns.IsDirty:
                        inventoryNewRow[(int)InventoryTableColumns.IsDirty] = true;
                        break;
                    default:
                        if (i < (int) InventoryTableColumns.IsHeaderRow)
                        {
                            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.
            inventoryDataGridView.Rows[e.RowIndex].HeaderCell.Style.BackColor = ApplicationColors.PendingEdit;
            actualSalesDataGridView.Rows[e.RowIndex].HeaderCell.Style.BackColor = ApplicationColors.PendingEdit;
        }

        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;
            }
            //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+", "")))
                    {
                        var parser = new RowParsing();
                        if (parser.CheckForGroupKeyWord(userInput) != "NoGroupFound")
                        {
                            _adSpecialIndex = e.RowIndex;
                        }
                        //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);
                        dataGridView.Rows[e.RowIndex].HeaderCell.Style.BackColor = ApplicationColors.PendingEdit;
                        //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;
                        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;
                        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;
                    actualSalesDataGridView.Rows[e.RowIndex].Cells[adItemIndex].Value = adItemText;
                    //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;
                    default:
                        if (i >= (int) InventoryTableColumns.IsHeaderRow)
                        {
                            continue;
                        }
                        rowContents[i] = "";
                        break;
                }
            }
            projectionsDataGridView.Rows.Add(rowContents);
            actualSalesDataGridView.Rows.Add(rowContents);
            //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;
        }

        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;
                    inventoryDataGridView.Rows[e.RowIndex].Cells[adItemIndex].Value = adItemText;
                    //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;
                    default:
                        if (i >= (int)SalesTableColumns.IsHeaderRow) continue;
                        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;
                    default:
                        if (i > (int)InventoryTableColumns.AdItem && i < (int)InventoryTableColumns.IsHeaderRow || i == (int)InventoryTableColumns.Id)
                        {
                            inventoryNewRow[i] = "";
                        }
                        break;
                }
            }
            inventoryDataGridView.Rows.Add(inventoryNewRow);
            //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;
        }

        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

        /// <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;
        }

        #region Comments TextBox Events

        /// <summary>
        /// Allows the user to select all the text in the comments text box.
        /// TODO: Fix error chime when using CNTRL+A.
        /// </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;
        }

        /// <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;
            }
        }

        #endregion

        #region Weekly Sales Events

        /// <summary>
        /// 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;
                    //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 = "";
                }
            }
            //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;
                }
                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;
                    //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 = "";
                }
            }
            //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;
                }
                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;
                    //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;
                }
            }
        }

        #endregion

        #region DateTime Events
        /// <summary>
        /// Updates the week ending masked text box with the selected date
        /// using the format (MM/DD/YYYY).
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UpdateWeekEndingMaskedTextBox(object sender, DateRangeEventArgs e)
        {
            var selectedDate = weekEndingMonthCalendar.SelectionStart;
            if (!selectedDate.ToString("D").StartsWith("Saturday"))
            {
                weekEndingMaskedTextBox.ForeColor = Color.Maroon;
                weekEndingMaskedTextBoxInstructionLabel.Text = @"... or manually enter it here: *";
                errorLabel.Text = @"* The date you selected does not appear to be a week ending date.";
            }
            else
            {
                weekEndingMaskedTextBox.ForeColor = Color.Black;
                weekEndingMaskedTextBoxInstructionLabel.Text = @"... or manually enter it here:";
                errorLabel.Text = "";
            }
            
            weekEndingMaskedTextBox.Text = selectedDate.ToString("MM-dd-yyyy");
        }

        /// <summary>
        /// Event Used: LostFocus
        /// Attempts to set the selected date of the calendar to the date that 
        /// has been entered into the masked text box.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UpdateCalendarOnFocusLost(object sender, EventArgs e)
        {
            //Replace any white space with zeros to pad out the mask.
            weekEndingMaskedTextBox.Text = weekEndingMaskedTextBox.Text.Replace("/", "");
            DateTime date;
            //Try parsing the contents of the masked text box to see if the date is valid.
            if (DateTime.TryParse(weekEndingMaskedTextBox.Text, out date))
            {
                //Update the text box's text with a nicely formatted date.
                weekEndingMaskedTextBox.Text = date.ToString("MM/dd/yyyy");
                //If it is update the calendar with the manually entered date.
                weekEndingMonthCalendar.SelectionStart = date;
            }
            else
            {
                //Otherwise throw an error to day that the date isn't valid and clear the text box.
                MessageBox.Show(@"The date entered appears to be invalid.", @"Invalid Date", MessageBoxButtons.OK, MessageBoxIcon.Error);
                weekEndingMaskedTextBox.Text = "";
            }
        }
        #endregion

        private void AddRecordsButtonClick(object sender, EventArgs e)
        {
            //Make sure the mask in the text box is completed.
            if (!weekEndingMaskedTextBox.MaskCompleted)
            {
                MessageBox.Show(@"A valid date must be specified.", @"Invalid Date", MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
                return;
            }
            //Create the database interaction objects.
            var dbT = new DatabaseTracker();
            var dbW = new DatabaseWriter(dbT.DatabaseConnectionString);
            var dbR = new DatabaseReader();
            DateTime dateTime;
            //Attempt to parse the date entered to verify it's integrity.
            if (DateTime.TryParseExact(weekEndingMaskedTextBox.Text, "MM/dd/yyyy", CultureInfo.InvariantCulture,
                DateTimeStyles.None, out dateTime))
            {
                //Check to see if the date is before the store was even founded, though I think a date range starting at 2014 would work but eh.
                if (dateTime.Year < 1958)
                {
                    var result =
                        MessageBox.Show(
                            @"Fairly certain Allen's wasn't even founded at this time... Maybe try another date or year at least?",
                            @"Let Alone Used Computers This Fast", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    if (result == DialogResult.Yes)
                    {
                        weekEndingMaskedTextBox.Focus();
                        return;
                    }
                    MessageBox.Show(@"Alright if you insist since technically this date is valid.",
                        @"Technically Correct Is The Best Correct", MessageBoxButtons.OK);
                }
            }
            else
            {
                MessageBox.Show(@"The date " + weekEndingMaskedTextBox.Text + @" is an invalid date.", @"Invalid Date", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            //Obtain the date ID.
            int dateId;
            if (
                int.TryParse(dbR.RetrieveDateIdByDateString(dateTime.ToString("MM/dd/yyyy"),
                    dbT.DatabaseConnectionString), out dateId))
            {
                //If the ID is zero (0) that means the date isn't in the database so simply insert it.
                if (dateId == 0)
                {
                    //Try inserting the date string.
                    if (dbW.InsertIntoWeekEnding(dateTime.ToString("MM/dd/yyyy")))
                    {
                        if (
                            int.TryParse(
                                dbR.RetrieveDateIdByDateString(dateTime.ToString("MM/dd/yyyy"),
                                    dbT.DatabaseConnectionString), out dateId))
                        {
                            //Now if its still zero (0) then that means something went really wrong and failed to insert.
                            if (dateId == 0)
                            {
                                MessageBox.Show(
                                    @"Failed to retrieve date ID after supposedly inserting the date into the database.",
                                    @"Failed To Get Date ID", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                return;
                            }
                        }
                        else
                        {
                            MessageBox.Show(
                                @"You really should not be able to see this message. If you are well that means something really weird happened converting text into a number, that is hard-coded to not fail on conversion. Either way I couldn't get the date ID due to some error, check the logs if you're curious.",
                                @"Well This Is Awkwardly Nested...", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                    }
                    else
                    {
                        //The above method reports that it failed to insert the date into the database.
                        MessageBox.Show(@"Failed insert the date " + weekEndingMaskedTextBox.Text + @" into the database.", @"Failed To Get Date ID", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                }
            }
            else
            {
                //Seriously don't think this will happen, but eh might as well.
                MessageBox.Show(
                    @"You really should not be able to see this message. If you are well that means something really weird happened converting text into a number, that is hard-coded to not fail on conversion. Either way I couldn't get the date ID due to some error, check the logs if you're curious.",
                    @"Well This Is Awkward...", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            //Run the row parsing engine on all the APC tables.
            //Create the cleaned table objects that will be sent to the database.
            DataTable trimmedTable;
            DataTable updateTable;
            informationLabel.Text = @"Compressing data tables..." + Environment.NewLine;
            errorLabel.Text = "";
            var operationStatus = ConstructCleanedSalesTable("Projections", dateId, out trimmedTable, out updateTable);
            if (operationStatus == TrimmingOperationResult.FailedToTrim)
            {
                errorLabel.Text = @"Failed to trim the Projections table.";
                return;
            }
            if (!ProcessTrimmingStatusResult(projectionsDataGridView, "Projections", operationStatus, trimmedTable, updateTable)) return;
            trimmedTable.Rows.Clear();
            updateTable.Rows.Clear();
            operationStatus = ConstructCleanedInventoryTable(dateId, out trimmedTable, out updateTable);
            if (operationStatus == TrimmingOperationResult.FailedToTrim)
            {
                errorLabel.Text = @"Failed to trim the Inventory table.";
                return;
            }
            if (!ProcessTrimmingStatusForInventory(operationStatus, trimmedTable, updateTable)) return;
            trimmedTable.Rows.Clear();
            updateTable.Rows.Clear();
            operationStatus = ConstructCleanedSalesTable("ActualSales", dateId, out trimmedTable, out updateTable);
            if (operationStatus == TrimmingOperationResult.FailedToTrim)
            {
                errorLabel.Text = @"Failed to trim the Actual Sales table.";
                return;
            }
            if (!ProcessTrimmingStatusResult(actualSalesDataGridView, "ActualSales", operationStatus, trimmedTable, updateTable)) return;
            //Commit the Invoice table to the database.
            var writerStatus = dbW.ProccessInvoiceTable(invoicesDataGridView, dateId, dbT.DatabaseConnectionString);
            if (writerStatus.GetWritingOperationStatus() == WritingOperationStatus.Failed)
            {
                errorLabel.Text = writerStatus.GetErrorMessage();
            }
            //TODO: If the comments are null but there is a comment ID, delete the comments from the database.
            if (isCommentDirtyCheckBox.Checked)
            {             
                if (isCommentDirtyCheckBox.Tag == null)
                {
                    informationLabel.Text += @"Inserting Comment(s).";
                    var status = dbW.ProcessComments(commentsTextBox.Text, dateId, dbT.DatabaseConnectionString);
                    if (status.Status == WritingOperationStatus.Failed)
                    {
                        errorLabel.Text = status.ErrorMessage;
                    }
                    else
                    {
                        informationLabel.Text += @"Comment(s) processed successfully.";
                        var id = status.Id;
                        isCommentDirtyCheckBox.Tag = id;
                        isCommentDirtyCheckBox.Text = @"IsCommentDirty (" + id + @")";
                        isCommentDirtyCheckBox.Checked = false;
                    }
                }
                else
                {
                    //Check for a null comment box and delete the comment ID from the database.
                    //Then if all is successful clear the Tag in the isCommentsDirty check box.
                    informationLabel.Text += @"Updating Comment(s).";
                    var status = dbW.ProcessComments(commentsTextBox.Text, dateId, dbT.DatabaseConnectionString, int.Parse(isCommentDirtyCheckBox.Tag.ToString()));
                    if (status.Status == WritingOperationStatus.Failed)
                    {
                        errorLabel.Text = status.ErrorMessage;
                    }
                    else
                    {
                        isCommentDirtyCheckBox.Checked = false;
                        informationLabel.Text += @"Comment(s) processed successfully.";
                    }
                }
            }
            //Begin checking the Weekly Sales.
            if (isWeeklySalesDirtyCheckBox.Checked)
            {
                //Parse out all the text boxes' values in the weekly sales group.
                var weeklySales = new double[8];
                weeklySales[0] = sundayWeeklySalesTextBox.Text == "" ? 0 : double.Parse(sundayWeeklySalesTextBox.Text);
                weeklySales[1] = mondayWeeklySalesTextBox.Text == "" ? 0 : double.Parse(mondayWeeklySalesTextBox.Text);
                weeklySales[2] = tuesdayWeeklySalesTextBox.Text == "" ? 0 : double.Parse(tuesdayWeeklySalesTextBox.Text);
                weeklySales[3] = wednesdayTaxableTextBox.Text == "" ? 0 : double.Parse(wednesdayWeeklySalesTextBox.Text);
                weeklySales[4] = thursdayWeeklySalesTextBox.Text == "" ? 0 : double.Parse(thursdayWeeklySalesTextBox.Text);
                weeklySales[5] = fridayWeeklySalesTextBox.Text == "" ? 0 : double.Parse(fridayWeeklySalesTextBox.Text);
                weeklySales[6] = saturdayWeeklySalesTextBox.Text == "" ? 0 : double.Parse(saturdayWeeklySalesTextBox.Text);
                weeklySales[7] = totalWeeklySalesTextBox.Text == "" ? 0 : double.Parse(totalWeeklySalesTextBox.Text);

                if (isWeeklySalesDirtyCheckBox.Tag == null)
                {
                    //Weekly sales is not in the database.
                    informationLabel.Text += @"Inserting weekly sales...";
                    var status = dbW.ProcessWeeklySales(weeklySales, dateId, dbT.DatabaseConnectionString);
                    if (status.Status == WritingOperationStatus.Failed)
                    {
                        errorLabel.Text = status.ErrorMessage;
                    }
                    else
                    {
                        informationLabel.Text += @"Weekly Sales processed successfully.";
                        isWeeklySalesDirtyCheckBox.Tag = status.Id;
                        isWeeklySalesDirtyCheckBox.Text = @"IsWeeklySalesDirty (" + status.Id + @")";
                        isWeeklySalesDirtyCheckBox.Checked = false;
                    }
                }
                else
                {
                    informationLabel.Text += @"Updating Weekly Sales.";
                    var status = dbW.ProcessWeeklySales(weeklySales, dateId, dbT.DatabaseConnectionString, int.Parse(isWeeklySalesDirtyCheckBox.Tag.ToString()));
                    if (status.Status == WritingOperationStatus.Failed)
                    {
                        errorLabel.Text = status.ErrorMessage;
                    }
                    else
                    {
                        isWeeklySalesDirtyCheckBox.Checked = false;
                        informationLabel.Text += @"Weekly Sales updated successfully.";
                    }
                }
            }
            //Begin checking the Taxable.
            if (isTaxableDirtyCheckBox.Checked)
            {
                //Parse out all the text boxes' values in the taxable group.
                var taxable = new double[8];
                taxable[0] = sundayTaxableTextBox.Text == "" ? 0 : double.Parse(sundayTaxableTextBox.Text);
                taxable[1] = mondayTaxableTextBox.Text == "" ? 0 : double.Parse(mondayTaxableTextBox.Text);
                taxable[2] = tuesdayTaxableTextBox.Text == "" ? 0 : double.Parse(tuesdayTaxableTextBox.Text);
                taxable[3] = wednesdayTaxableTextBox.Text == "" ? 0 : double.Parse(wednesdayTaxableTextBox.Text);
                taxable[4] = thursdayTaxableTextBox.Text == "" ? 0 : double.Parse(thursdayTaxableTextBox.Text);
                taxable[5] = fridayTaxableTextBox.Text == "" ? 0 : double.Parse(fridayTaxableTextBox.Text);
                taxable[6] = saturdayTaxableTextBox.Text == "" ? 0 : double.Parse(saturdayTaxableTextBox.Text);
                taxable[7] = totalTaxableTextBox.Text == "" ? 0 : double.Parse(totalTaxableTextBox.Text);

                if (isTaxableDirtyCheckBox.Tag == null)
                {
                    //Weekly sales is not in the database.
                    informationLabel.Text += @"Inserting Taxable...";
                    var status = dbW.ProcessTaxable(taxable, dateId, dbT.DatabaseConnectionString);
                    if (status.Status == WritingOperationStatus.Failed)
                    {
                        errorLabel.Text = status.ErrorMessage;
                    }
                    else
                    {
                        informationLabel.Text += @"Taxable processed successfully.";
                        isTaxableDirtyCheckBox.Tag = status.Id;
                        isTaxableDirtyCheckBox.Text = @"IsTaxableDirty (" + status.Id + @")";
                        isTaxableDirtyCheckBox.Checked = false;
                    }
                }
                else
                {
                    informationLabel.Text += @"Updating Taxable.";
                    var status = dbW.ProcessTaxable(taxable, dateId, dbT.DatabaseConnectionString, int.Parse(isTaxableDirtyCheckBox.Tag.ToString()));
                    if (status.Status == WritingOperationStatus.Failed)
                    {
                        errorLabel.Text = status.ErrorMessage;
                    }
                    else
                    {
                        isTaxableDirtyCheckBox.Checked = false;
                        informationLabel.Text += @"Taxable updated successfully.";
                    }
                }
            }
            //Begin checking cost analysis.
            if (isCostAnalysisDirtyCheckBox.Checked)
            {
                //Parse out the cost analysis group values.
                var costAnalysis = new double[4];
                costAnalysis[0] = salesPerManHourTextBox.Text == "" ? 0 : double.Parse(salesPerManHourTextBox.Text);
                costAnalysis[1] = salaryPercentageTextBox.Text == "" ? 0 : double.Parse(salaryPercentageTextBox.Text);
                costAnalysis[2] = salaryDollarsTextBox.Text == "" ? 0 : double.Parse(salaryDollarsTextBox.Text);
                costAnalysis[3] = suppliesTextBox.Text == "" ? 0 : double.Parse(suppliesTextBox.Text);

                if (isCostAnalysisDirtyCheckBox.Tag == null)
                {
                    //Weekly sales is not in the database.
                    informationLabel.Text += @"Inserting Cost Analysis...";
                    var status = dbW.ProcessCostAnalysis(costAnalysis, dateId, dbT.DatabaseConnectionString);
                    if (status.Status == WritingOperationStatus.Failed)
                    {
                        errorLabel.Text = status.ErrorMessage;
                    }
                    else
                    {
                        informationLabel.Text += @"Costs analysis processed successfully.";
                        isCostAnalysisDirtyCheckBox.Tag = status.Id;
                        isCostAnalysisDirtyCheckBox.Text = @"IsCostAnalysisDirty (" + status.Id + @")";
                        isCostAnalysisDirtyCheckBox.Checked = false;
                    }
                }
                else
                {
                    informationLabel.Text += @"Updating cost analysis.";
                    var status = dbW.ProcessCostAnalysis(costAnalysis, dateId, dbT.DatabaseConnectionString, int.Parse(isCostAnalysisDirtyCheckBox.Tag.ToString()));
                    if (status.Status == WritingOperationStatus.Failed)
                    {
                        errorLabel.Text = status.ErrorMessage;
                    }
                    else
                    {
                        isCostAnalysisDirtyCheckBox.Checked = false;
                        informationLabel.Text += @"Cost analysis updated successfully.";
                    }
                }
            }
            //Create the transaction scope.
            //By default the TransactionScopeOption is "Required", so if an ambient transaction does not
            //exist then the new transaction that is made (in the first method) becomes the root transaction.
            //Transaction Scope: https://msdn.microsoft.com/en-us/library/ms172152.aspx
        }

        #region Table Trimming Operations

        private TrimmingOperationResult ConstructCleanedSalesTable(string tableName, int dateId, out DataTable insertNewTable, out DataTable updateExistingTable)
        {
            //Create two DataTables one for the new items to be added to the database
            //and one for items that have to be updated.
            //New Sales Table Layout (Based on the Database's Physical Layout)
            //0:Sold 1:SalePrice 2:TotalSales 3:cost 4:ProfitReturn 5:TotalProfitReturn
            //6:FK_AdItemID 7:RowAttribute 8:FK_AdSpecialGroupName (ID) 9:RowPosition (not index based)
            //10:FK_DateID
            insertNewTable = new DataTable(tableName);
            //Update Sales Table Layout (Based on the Database's Physical Layout)
            //0:ID 1:Sold 2:SalePrice 3:TotalSales 4:cost 5:ProfitReturn 6:TotalProfitReturn
            //7:FK_AdItemID 8:RowAttribute 9:FK_AdSpecialGroupName (ID) 10:RowPosition (not index based)
            //11:FK_DateID
            updateExistingTable = new DataTable(tableName);
            //Create a reference to the DataGridView that will be used (either Projections or Actual Sales).
            var dataGridView = tableName == "Projections" ? projectionsDataGridView : actualSalesDataGridView;
            //Construct a list of column names for the projections/actual sales DataGridViews and the inventory DataGirdView.
            string[] saleColumnNames =
            {
                "ID", "Sold", "SalePrice", "TotalSales", "Cost", "ProfitReturn",
                "TotalProfitReturn", "AdItemID", "RowAttribute", "AdSpecialID", "RowPosition", "DateID"
            };
            foreach (var columnName in saleColumnNames)
            {
                if (columnName == "ID") continue;
                var column = new DataColumn(columnName);
                insertNewTable.Columns.Add(column);
            }
            foreach (var columnName in saleColumnNames)
            {
                var column = new DataColumn(columnName);
                updateExistingTable.Columns.Add(column);
            }
            //Create the database interaction objects.
            var databaseTracker = new DatabaseTracker();
            var databaseReader = new DatabaseReader();
            var databaseWriter = new DatabaseWriter(databaseTracker.DatabaseConnectionString);
            var adSpecialId = 0; //Entries in the database are not allowed to be zero (unique ID wise that is).
            //Grab the ad special ID, assuming there is one.
            if (_adSpecialIndex != -1)
            {
                //An ad special does exist so grab its ID from the database.
                int.TryParse(databaseReader.RetrieveGroupIdByString(
                    dataGridView.Rows[_adSpecialIndex].Cells[(int)SalesTableColumns.AdItem]
                        .EditedFormattedValue.ToString(), databaseTracker.DatabaseConnectionString), out adSpecialId);
            }
            //Begin spinning through all the rows in the projections table.
            foreach (DataGridViewRow row in dataGridView.Rows)
            {
                //Always check for new row.
                if (row.IsNewRow) break;
                //Check to see if the current row is the ad special row.
                if (row.Index == _adSpecialIndex)
                {
                    continue;
                }
                //Check to see if the row is dirty.
                if (!(bool)row.Cells[(int)SalesTableColumns.IsDirty].Value)
                {
                    //If it is not then continue on to the next row.
                    continue;
                }
                //Try grabbing the row's ID number (the number that it is in the database).
                var rowIdNumber = row.Cells[(int)SalesTableColumns.Id].EditedFormattedValue.ToString() == "" ? 0 : int.Parse(row.Cells[(int)SalesTableColumns.Id].EditedFormattedValue.ToString());
                //Grab the ad item ID.
                var adItemId = int.Parse(databaseReader.RetrieveAdItemId(row.Cells[(int)SalesTableColumns.AdItem].EditedFormattedValue.ToString(), databaseTracker.DatabaseConnectionString));
                //If the return value is zero (0) then the ad item is not in the database so try to add it.
                if (adItemId == 0)
                {
                    //Add the item to the database.
                    adItemId = databaseWriter.InsertNewAdItem(row.Cells[(int)SalesTableColumns.AdItem].EditedFormattedValue.ToString());
                    if (adItemId == 0)
                    {
                        //TODO: Throw an exception, this can not be allowed.
                        //AdItemInsertionFailedException
                        insertNewTable.Rows.Clear(); //Work around for now
                        updateExistingTable.Rows.Clear();
                        errorLabel.Text = @"Failed to ad item to database.";
                        return TrimmingOperationResult.FailedToTrim;
                    }
                }
                //Check for repeated ad items in the ad special section
                if (_adSpecialIndex != -1 && row.Index > _adSpecialIndex)
                {
                    //Attempt to grab the index of an ad item, if it is not found then the return value is -1.
                    var repeatedItemIndex = _usedAdItems[0].FindIndex(x => x == row.Cells[(int)SalesTableColumns.AdItem].EditedFormattedValue.ToString());
                    //Skip checking this row if an index is found, and use the values in the row at the previous index found.
                    if (repeatedItemIndex != -1)
                    {
                        //Add the values to their respective data table.
                        if (rowIdNumber == 0)
                        {
                            //This table is full of data not in the database so the ID column isn't needed.
                            var newRow = new object[11];
                            newRow[0] = dataGridView.Rows[repeatedItemIndex].Cells[(int)SalesTableColumns.Sold].EditedFormattedValue.ToString();//Sold, is string
                            newRow[1] = dataGridView.Rows[repeatedItemIndex].Cells[(int)SalesTableColumns.SalePrice].EditedFormattedValue.ToString();//SalePrice, is string
                            newRow[2] = dataGridView.Rows[repeatedItemIndex].Cells[(int)SalesTableColumns.TotalSales].EditedFormattedValue.ToString() == "" ? 0 : double.Parse(dataGridView.Rows[repeatedItemIndex].Cells[(int)SalesTableColumns.TotalSales].EditedFormattedValue.ToString());//TotalSales, must be a number
                            newRow[3] = dataGridView.Rows[repeatedItemIndex].Cells[(int)SalesTableColumns.Cost].EditedFormattedValue.ToString() == "" ? 0 : double.Parse(dataGridView.Rows[repeatedItemIndex].Cells[(int)SalesTableColumns.Cost].EditedFormattedValue.ToString());//Cost, must be a number
                            newRow[4] = dataGridView.Rows[repeatedItemIndex].Cells[(int)SalesTableColumns.ProfitReturn].EditedFormattedValue.ToString() == "" ? 0 : double.Parse(dataGridView.Rows[repeatedItemIndex].Cells[(int)SalesTableColumns.ProfitReturn].EditedFormattedValue.ToString());//ProfitReturn, must be a number
                            newRow[5] = dataGridView.Rows[repeatedItemIndex].Cells[(int)SalesTableColumns.TotalProfitReturn].EditedFormattedValue.ToString() == "" ? 0 : double.Parse(dataGridView.Rows[repeatedItemIndex].Cells[(int)SalesTableColumns.TotalProfitReturn].EditedFormattedValue.ToString());//TotalProfitReturn, must be a number
                            newRow[6] = adItemId;
                            if ((bool)dataGridView.Rows[repeatedItemIndex].Cells[(int) SalesTableColumns.IsHeaderRow].Value)
                            {
                                newRow[7] = 1;
                            }
                            else if ((bool)dataGridView.Rows[repeatedItemIndex].Cells[(int) SalesTableColumns.IsMemberRow].Value)
                            {
                                newRow[7] = 2;
                            }
                            else
                            {
                                newRow[7] = 0;
                            }
                            newRow[8] = adSpecialId;
                            newRow[9] = row.Index; //"Subtract" one since we don't need to acknowledge the Ad Special Row's existence.
                            newRow[10] = dateId;
                            insertNewTable.Rows.Add(newRow);
                            continue;
                        }
                        else
                        {
                            //This table is full of data that is already in the database.
                            var newRow = new object[11];
                            newRow[0] = rowIdNumber;
                            newRow[1] = dataGridView.Rows[repeatedItemIndex].Cells[(int)SalesTableColumns.Sold].EditedFormattedValue.ToString();//Sold, is string
                            newRow[2] = dataGridView.Rows[repeatedItemIndex].Cells[(int)SalesTableColumns.SalePrice].EditedFormattedValue.ToString();//SalePrice, is string
                            newRow[3] = dataGridView.Rows[repeatedItemIndex].Cells[(int)SalesTableColumns.TotalSales].EditedFormattedValue.ToString() == "" ? 0 : double.Parse(dataGridView.Rows[repeatedItemIndex].Cells[(int)SalesTableColumns.TotalSales].EditedFormattedValue.ToString());//TotalSales, must be a number
                            newRow[4] = dataGridView.Rows[repeatedItemIndex].Cells[(int)SalesTableColumns.Cost].EditedFormattedValue.ToString() == "" ? 0 : double.Parse(dataGridView.Rows[repeatedItemIndex].Cells[(int)SalesTableColumns.Cost].EditedFormattedValue.ToString());//Cost, must be a number
                            newRow[5] = dataGridView.Rows[repeatedItemIndex].Cells[(int)SalesTableColumns.ProfitReturn].EditedFormattedValue.ToString() == "" ? 0 : double.Parse(dataGridView.Rows[repeatedItemIndex].Cells[(int)SalesTableColumns.ProfitReturn].EditedFormattedValue.ToString());//ProfitReturn, must be a number
                            newRow[6] = dataGridView.Rows[repeatedItemIndex].Cells[(int)SalesTableColumns.TotalProfitReturn].EditedFormattedValue.ToString() == "" ? 0 : double.Parse(dataGridView.Rows[repeatedItemIndex].Cells[(int)SalesTableColumns.TotalProfitReturn].EditedFormattedValue.ToString());//TotalProfitReturn, must be a number
                            newRow[7] = adItemId;
                            if ((bool)dataGridView.Rows[repeatedItemIndex].Cells[(int)SalesTableColumns.IsHeaderRow].Value)
                            {
                                newRow[8] = 1;
                            }
                            else if ((bool)dataGridView.Rows[repeatedItemIndex].Cells[(int)SalesTableColumns.IsMemberRow].Value)
                            {
                                newRow[8] = 2;
                            }
                            else
                            {
                                newRow[8] = 0;
                            }
                            newRow[9] = adSpecialId;
                            newRow[10] = row.Index; //"Subtract" one since we don't need to acknowledge the Ad Special Row's existence.
                            newRow[11] = dateId;
                            insertNewTable.Rows.Add(newRow);
                            continue;
                        }
                    }
                }
                //Determine the row's attribute.
                var rowAttribute = 0; //Zero (0) means no grouping, its not a header nor a member.
                if ((bool)row.Cells[(int)SalesTableColumns.IsHeaderRow].Value && !(bool)row.Cells[(int)SalesTableColumns.IsMemberRow].Value)
                {
                    rowAttribute = 1;
                }
                else if ((bool)row.Cells[(int)SalesTableColumns.IsMemberRow].Value && !(bool)row.Cells[(int)SalesTableColumns.IsHeaderRow].Value)
                {
                    rowAttribute = 2;
                }
                //Add the values to their respective data table.
                if (rowIdNumber == 0)
                {
                    //This table is full of data not in the database so the ID column isn't needed.
                    var newRow = new object[11];
                    newRow[0] = row.Cells[(int)SalesTableColumns.Sold].EditedFormattedValue.ToString();//Sold, is string
                    newRow[1] = row.Cells[(int)SalesTableColumns.SalePrice].EditedFormattedValue.ToString();//SalePrice, is string
                    newRow[2] = row.Cells[(int)SalesTableColumns.TotalSales].EditedFormattedValue.ToString() == "" ? 0 : double.Parse(row.Cells[(int)SalesTableColumns.TotalSales].EditedFormattedValue.ToString());//TotalSales, must be a number
                    newRow[3] = row.Cells[(int)SalesTableColumns.Cost].EditedFormattedValue.ToString() == "" ? 0 : double.Parse(row.Cells[(int)SalesTableColumns.Cost].EditedFormattedValue.ToString());//Cost, must be a number
                    newRow[4] = row.Cells[(int)SalesTableColumns.ProfitReturn].EditedFormattedValue.ToString() == "" ? 0 : double.Parse(row.Cells[(int)SalesTableColumns.ProfitReturn].EditedFormattedValue.ToString());//ProfitReturn, must be a number
                    newRow[5] = row.Cells[(int)SalesTableColumns.TotalProfitReturn].EditedFormattedValue.ToString() == "" ? 0 : double.Parse(row.Cells[(int)SalesTableColumns.TotalProfitReturn].EditedFormattedValue.ToString());//TotalProfitReturn, must be a number
                    newRow[6] = adItemId;
                    newRow[7] = rowAttribute;
                    if (_adSpecialIndex != -1 && row.Index > _adSpecialIndex)
                    {
                        newRow[8] = adSpecialId;
                        newRow[9] = row.Index; //"Subtract" one since we don't need to acknowledge the Ad Special Row's existence.
                    }
                    else
                    {
                        newRow[8] = 0;
                        newRow[9] = row.Index + 1;
                    }
                    newRow[10] = dateId;
                    insertNewTable.Rows.Add(newRow);
                }
                else
                {
                    //This table is full of data that is already in the database.
                    var newRow = new object[12];
                    newRow[0] = rowIdNumber;
                    newRow[1] = row.Cells[(int)SalesTableColumns.Sold].EditedFormattedValue.ToString();//Sold, is string
                    newRow[2] = row.Cells[(int)SalesTableColumns.SalePrice].EditedFormattedValue.ToString();//SalePrice, is string
                    newRow[3] = row.Cells[(int)SalesTableColumns.TotalSales].EditedFormattedValue.ToString() == "" ? 0 : double.Parse(row.Cells[(int)SalesTableColumns.TotalSales].EditedFormattedValue.ToString());//TotalSales, must be a number
                    newRow[4] = row.Cells[(int)SalesTableColumns.Cost].EditedFormattedValue.ToString() == "" ? 0 : double.Parse(row.Cells[(int)SalesTableColumns.Cost].EditedFormattedValue.ToString());//Cost, must be a number
                    newRow[5] = row.Cells[(int)SalesTableColumns.ProfitReturn].EditedFormattedValue.ToString() == "" ? 0 : double.Parse(row.Cells[(int)SalesTableColumns.ProfitReturn].EditedFormattedValue.ToString());//ProfitReturn, must be a number
                    newRow[6] = row.Cells[(int)SalesTableColumns.TotalProfitReturn].EditedFormattedValue.ToString() == "" ? 0 : double.Parse(row.Cells[(int)SalesTableColumns.TotalProfitReturn].EditedFormattedValue.ToString());//TotalProfitReturn, must be a number
                    newRow[7] = adItemId;
                    newRow[8] = rowAttribute;
                    if (_adSpecialIndex != -1 && row.Index > _adSpecialIndex)
                    {
                        newRow[9] = adSpecialId;
                        newRow[10] = row.Index; //"Subtract" one since we don't need to acknowledge the Ad Special Row's existence.
                    }
                    else
                    {
                        newRow[9] = 0;
                        newRow[10] = row.Index + 1;
                    }
                    newRow[11] = dateId;
                    updateExistingTable.Rows.Add(newRow);
                }
                //LogConsole.WriteToLog(FrmLogConsole.Level.Verbose, "Row Dump for row number " + (row.Index + 1) + ".");
                //LogConsole.WriteToLog(FrmLogConsole.Level.Verbose, "ID : " + rowIdNumber + " Sold: " + row.Cells[(int)SalesTableColumns.Sold].EditedFormattedValue);
                //LogConsole.WriteToLog(FrmLogConsole.Level.Verbose, "Sale Price : " + row.Cells[(int)SalesTableColumns.SalePrice].EditedFormattedValue + " Total Sales: " + row.Cells[(int)SalesTableColumns.TotalSales].EditedFormattedValue);
                //LogConsole.WriteToLog(FrmLogConsole.Level.Verbose, "Cost: " + row.Cells[(int)SalesTableColumns.Cost].EditedFormattedValue + " Profit Return: " + row.Cells[(int)SalesTableColumns.ProfitReturn].EditedFormattedValue);
                //LogConsole.WriteToLog(FrmLogConsole.Level.Verbose, "Total Profit Return: " + row.Cells[(int)SalesTableColumns.TotalProfitReturn].EditedFormattedValue + " Ad Item ID: " + adItemId);
                //LogConsole.WriteToLog(FrmLogConsole.Level.Verbose, "Row Attribute: " + rowAttribute + " Ad Special ID: " + adSpecialId);
                //LogConsole.WriteToLog(FrmLogConsole.Level.Verbose, "Row Position: " + row.Index + (_adSpecialIndex != -1 && row.Index > _adSpecialIndex ? 1 : 0) + " Date ID: " + dateId);
            }

            if (insertNewTable.Rows.Count == 0 && updateExistingTable.Rows.Count == 0)
            {
                return TrimmingOperationResult.NoChangesRequired;
            }
            if (insertNewTable.Rows.Count > 0 && updateExistingTable.Rows.Count == 0)
            {
                return TrimmingOperationResult.CreatedNewInsertionTable;
            }
            if (insertNewTable.Rows.Count == 0 && updateExistingTable.Rows.Count > 0)
            {
                return TrimmingOperationResult.CreatedUpdateTable;
            }
            return TrimmingOperationResult.CreatedNewInsertionAndUpdateTables;
        }

        private TrimmingOperationResult ConstructCleanedInventoryTable(int dateId, out DataTable insertNewTable, out DataTable updateExistingTable)
        {
            //Create two DataTables one for the new items to be added to the database
            //and one for items that have to be updated.
            //New inventory Table Layout (Based on the Database's Physical Layout)
            //0:Beginning Inventory 1:Received 2:Total Inventory 3:Ending Inventory
            //4:AdItemID 5:RowAttribute 6:GroupID 7:RowPosition 8:DateID
            insertNewTable = new DataTable("Inventory");
            //Update Sales Table Layout (Based on the Database's Physical Layout)
            //0:ID 1:BeginningInventory 2:Received 3:TotalInventory 4:EndingInventory
            //5:AdItemID 6:RowAttribute 7:GroupID 8:RowPosition 9:DateID
            updateExistingTable = new DataTable("Inventory");
            //Construct a list of column names for the projections/actual sales DataGridViews and the inventory DataGirdView.
            string[] saleColumnNames =
            {
                "ID", "Sold", "SalePrice", "TotalSales", "Cost", "ProfitReturn",
                "TotalProfitReturn", "AdItemID", "RowAttribute", "AdSpecialID", "RowPosition", "DateID"
            };
            foreach (var columnName in saleColumnNames)
            {
                if (columnName == "ID") continue;
                var column = new DataColumn(columnName);
                insertNewTable.Columns.Add(column);
            }
            foreach (var columnName in saleColumnNames)
            {
                var column = new DataColumn(columnName);
                updateExistingTable.Columns.Add(column);
            }
            //Create the database interaction objects.
            var databaseTracker = new DatabaseTracker();
            var databaseReader = new DatabaseReader();
            var databaseWriter = new DatabaseWriter(databaseTracker.DatabaseConnectionString);
            var adSpecialId = 0; //Entries in the database are not allowed to be zero (unique ID wise that is).
            //Grab the ad special ID, assuming there is one.
            if (_adSpecialIndex != -1)
            {
                //An ad special does exist so grab its ID from the database.
                int.TryParse(databaseReader.RetrieveGroupIdByString(
                    inventoryDataGridView.Rows[_adSpecialIndex].Cells[(int)InventoryTableColumns.AdItem]
                        .EditedFormattedValue.ToString(), databaseTracker.DatabaseConnectionString), out adSpecialId);
            }
            //Begin spinning through all the rows in the projections table.
            foreach (DataGridViewRow row in inventoryDataGridView.Rows)
            {
                //Always check for new row.
                if (row.IsNewRow) break;
                //Check to see if the current row is the ad special row.
                if (row.Index == _adSpecialIndex)
                {
                    //LogConsole.WriteToLog(FrmLogConsole.Level.Verbose, "Ad Special Row found at index " + row.Index + ".");
                    continue;
                }
                //Check to see if the row is dirty.
                if (!(bool)row.Cells[(int)InventoryTableColumns.IsDirty].Value)
                {
                    //If it is not then continue on to the next row.
                    continue;
                }
                //Try grabbing the row's ID number (the number that it is in the database).
                var rowIdNumber = row.Cells[(int)InventoryTableColumns.Id].EditedFormattedValue.ToString() == "" ? 0 : int.Parse(row.Cells[(int)InventoryTableColumns.Id].EditedFormattedValue.ToString());
                //Grab the ad item ID.
                var adItemId = int.Parse(databaseReader.RetrieveAdItemId(row.Cells[(int)InventoryTableColumns.AdItem].EditedFormattedValue.ToString(), databaseTracker.DatabaseConnectionString));
                //If the return value is zero (0) then the ad item is not in the database so try to add it.
                if (adItemId == 0)
                {
                    //Add the item to the database.
                    adItemId = databaseWriter.InsertNewAdItem(row.Cells[(int)InventoryTableColumns.AdItem].EditedFormattedValue.ToString());
                    if (adItemId == 0)
                    {
                        //TODO: Throw an exception, this can not be allowed.
                        //AdItemInsertionFailedException
                        insertNewTable.Rows.Clear(); //Work around for now
                        updateExistingTable.Rows.Clear();
                        return TrimmingOperationResult.FailedToTrim;
                    }
                }
                //Check for repeated ad items in the ad special section
                if (_adSpecialIndex != -1 && row.Index > _adSpecialIndex)
                {
                    //Attempt to grab the index of an ad item, if it is not found then the return value is -1.
                    var repeatedItemIndex =
                        _usedAdItems[0].FindIndex(x => x == row.Cells[(int)InventoryTableColumns.AdItem].EditedFormattedValue.ToString());
                    //Skip checking this row if an index is found, and use the values in the row at the previous index found.
                    if (repeatedItemIndex != -1)
                    {
                        //Add the values to their respective data table.
                        if (rowIdNumber == 0)
                        {
                            //This table is full of data not in the database so the ID column isn't needed.
                            //0:Beginning Inventory 1:Received 2:Total Inventory 3:Ending Inventory
                            //4:AdItemID 5:RowAttribute 6:GroupID 7:RowPosition 8:DateID
                            var newRow = new object[9];
                            newRow[0] = inventoryDataGridView.Rows[repeatedItemIndex].Cells[(int)InventoryTableColumns.BeginningInventory].EditedFormattedValue.ToString();//Sold, is string
                            newRow[1] = inventoryDataGridView.Rows[repeatedItemIndex].Cells[(int)InventoryTableColumns.Recieved].EditedFormattedValue.ToString();//SalePrice, is string
                            newRow[2] = inventoryDataGridView.Rows[repeatedItemIndex].Cells[(int) InventoryTableColumns.Total].EditedFormattedValue.ToString(); //Total Inventory is string
                            newRow[3] = inventoryDataGridView.Rows[repeatedItemIndex].Cells[(int)InventoryTableColumns.EndingInventory].EditedFormattedValue.ToString();//Ending Inventory, is string
                            newRow[4] = adItemId;
                            if ((bool)inventoryDataGridView.Rows[repeatedItemIndex].Cells[(int)InventoryTableColumns.IsHeaderRow].Value)
                            {
                                newRow[5] = 1;
                            }
                            else if ((bool)inventoryDataGridView.Rows[repeatedItemIndex].Cells[(int)InventoryTableColumns.IsMemberRow].Value)
                            {
                                newRow[5] = 2;
                            }
                            else
                            {
                                newRow[5] = 0;
                            }
                            newRow[6] = adSpecialId;
                            newRow[7] = row.Index; //"Subtract" one since we don't need to acknowledge the Ad Special Row's existence.
                            newRow[8] = dateId;
                            insertNewTable.Rows.Add(newRow);
                            continue;
                        }
                        else
                        {
                            //This table is full of data that is already in the database.
                            //0:ID 1:BeginningInventory 2:Received 3:TotalInventory 4:EndingInventory
                            //5:AdItemID 6:RowAttribute 7:GroupID 8:RowPosition 9:DateID
                            var newRow = new object[10];
                            newRow[0] = rowIdNumber;
                            newRow[1] = inventoryDataGridView.Rows[repeatedItemIndex].Cells[(int)InventoryTableColumns.BeginningInventory].EditedFormattedValue.ToString();//Sold, is string
                            newRow[2] = inventoryDataGridView.Rows[repeatedItemIndex].Cells[(int)InventoryTableColumns.Recieved].EditedFormattedValue.ToString();//SalePrice, is string
                            newRow[3] = inventoryDataGridView.Rows[repeatedItemIndex].Cells[(int)InventoryTableColumns.Total].EditedFormattedValue.ToString(); //Total Inventory is string
                            newRow[4] = inventoryDataGridView.Rows[repeatedItemIndex].Cells[(int)InventoryTableColumns.EndingInventory].EditedFormattedValue.ToString();//Ending Inventory, is string
                            newRow[5] = adItemId;
                            if ((bool)inventoryDataGridView.Rows[repeatedItemIndex].Cells[(int)InventoryTableColumns.IsHeaderRow].Value)
                            {
                                newRow[6] = 1;
                            }
                            else if ((bool)inventoryDataGridView.Rows[repeatedItemIndex].Cells[(int)InventoryTableColumns.IsMemberRow].Value)
                            {
                                newRow[6] = 2;
                            }
                            else
                            {
                                newRow[6] = 0;
                            }
                            newRow[7] = adSpecialId;
                            newRow[8] = row.Index; //"Subtract" one since we don't need to acknowledge the Ad Special Row's existence.
                            newRow[9] = dateId;
                            continue;
                        }
                    }
                }
                //Determine the row's attribute.
                var rowAttribute = 0; //Zero (0) means no grouping, its not a header nor a member.
                if ((bool)row.Cells[(int)InventoryTableColumns.IsHeaderRow].Value && !(bool)row.Cells[(int)InventoryTableColumns.IsMemberRow].Value)
                {
                    rowAttribute = 1;
                }
                else if ((bool)row.Cells[(int)InventoryTableColumns.IsMemberRow].Value && !(bool)row.Cells[(int)InventoryTableColumns.IsHeaderRow].Value)
                {
                    rowAttribute = 2;
                }
                //Add the values to their respective data table.
                if (rowIdNumber == 0)
                {
                    //This table is full of data not in the database so the ID column isn't needed.
                    var newRow = new object[9];
                    newRow[0] = row.Cells[(int)InventoryTableColumns.BeginningInventory].EditedFormattedValue.ToString();//Beginning inventory, is string
                    newRow[1] = row.Cells[(int)InventoryTableColumns.Recieved].EditedFormattedValue.ToString();//Received, is string
                    newRow[2] = row.Cells[(int)InventoryTableColumns.Total].EditedFormattedValue.ToString();//Total inventory. is string
                    newRow[3] = row.Cells[(int)InventoryTableColumns.EndingInventory].EditedFormattedValue.ToString(); //Ending inventory, is string
                    newRow[4] = adItemId;
                    newRow[5] = rowAttribute;
                    if (_adSpecialIndex != -1 && row.Index > _adSpecialIndex)
                    {
                        newRow[6] = adSpecialId;
                        newRow[7] = row.Index; //"Subtract" one since we don't need to acknowledge the Ad Special Row's existence.
                    }
                    else
                    {
                        newRow[6] = 0;
                        newRow[7] = row.Index + 1;
                    }
                    newRow[8] = dateId;
                    insertNewTable.Rows.Add(newRow);
                }
                else
                {
                    //This table is full of data that is already in the database.
                    var newRow = new object[10];
                    newRow[0] = rowIdNumber;
                    newRow[1] = row.Cells[(int)InventoryTableColumns.BeginningInventory].EditedFormattedValue.ToString();//Beginning inventory, is string
                    newRow[2] = row.Cells[(int)InventoryTableColumns.Recieved].EditedFormattedValue.ToString();//Received, is string
                    newRow[3] = row.Cells[(int)InventoryTableColumns.Total].EditedFormattedValue.ToString();//Total inventory. is string
                    newRow[4] = row.Cells[(int)InventoryTableColumns.EndingInventory].EditedFormattedValue.ToString(); //Ending inventory, is string
                    newRow[5] = adItemId;
                    newRow[6] = rowAttribute;
                    if (_adSpecialIndex != -1 && row.Index > _adSpecialIndex)
                    {
                        newRow[7] = adSpecialId;
                        newRow[8] = row.Index; //"Subtract" one since we don't need to acknowledge the Ad Special Row's existence.
                    }
                    else
                    {
                        newRow[7] = 0;
                        newRow[8] = row.Index + 1;
                    }
                    newRow[9] = dateId;
                    updateExistingTable.Rows.Add(newRow);
                }
            }

            if (insertNewTable.Rows.Count == 0 && updateExistingTable.Rows.Count == 0)
            {
                return TrimmingOperationResult.NoChangesRequired;
            }
            if (insertNewTable.Rows.Count > 0 && updateExistingTable.Rows.Count == 0)
            {
                return TrimmingOperationResult.CreatedNewInsertionTable;
            }
            if (insertNewTable.Rows.Count == 0 && updateExistingTable.Rows.Count > 0)
            {
                return TrimmingOperationResult.CreatedUpdateTable;
            }
            return TrimmingOperationResult.CreatedNewInsertionAndUpdateTables;
        }

        private bool ProcessTrimmingStatusResult(DataGridView dataGridView, string tableName, TrimmingOperationResult operationStatus, DataTable trimmedTable, DataTable updateTable)
        {
            //Create the database interaction objects.
            var dbT = new DatabaseTracker();
            var dbW = new DatabaseWriter(dbT.DatabaseConnectionString);
            DbTableWriterStatus dbWriterStatus;
            var successful = false;
            switch (operationStatus)
            {
                case TrimmingOperationResult.NoChangesRequired:
                    informationLabel.Text += Environment.NewLine + @"No changes to the " + TextFormat.AddSpacesToSentence(tableName, false) + @" table detected.";
                    successful = true;
                    break;
                case TrimmingOperationResult.CreatedNewInsertionTable:
                    informationLabel.Text += Environment.NewLine + @"Inserting new changes to the " + TextFormat.AddSpacesToSentence(tableName, false) + @" table.";
                    dbWriterStatus = dbW.InsertIntoSalesTable(trimmedTable, dbT.DatabaseConnectionString);
                    if (dbWriterStatus.GetErrorMessage() == string.Empty)
                    {
                        //Spin through the collection and update the affected rows.
                        foreach (var rowIndex in dbWriterStatus.GetRowCollection())
                        {
                            dataGridView.Rows[rowIndex.Key - 1].Cells[(int) SalesTableColumns.Id].Value = rowIndex.Value;
                            dataGridView.Rows[rowIndex.Key - 1].Cells[(int) SalesTableColumns.IsDirty].Value = false;
                        }
                        informationLabel.Text += Environment.NewLine + TextFormat.AddSpacesToSentence(tableName, false) + @" table successfully added to the database.";
                        successful = true;
                    }
                    else
                    {
                        errorLabel.Text = @"Failed to insert " + trimmedTable + @" into the database.";
                    }
                    break;
                case TrimmingOperationResult.CreatedUpdateTable:
                    informationLabel.Text += Environment.NewLine + @"Updating changes made to the " + TextFormat.AddSpacesToSentence(tableName, false) + @" table.";
                    dbWriterStatus = dbW.UpdateSalesTable(updateTable, dbT.DatabaseConnectionString);
                    if (dbWriterStatus.GetErrorMessage() == string.Empty)
                    {
                        //Spin through the collection and update the affected rows.
                        foreach (var rowIndex in dbWriterStatus.GetRowCollection())
                        {
                            //Only reset the IsDirty value to false since the updates when through.
                            dataGridView.Rows[rowIndex.Key - 1].Cells[(int)SalesTableColumns.IsDirty].Value = false;
                        }
                        informationLabel.Text += Environment.NewLine + TextFormat.AddSpacesToSentence(tableName, false) + @" table successfully updated.";
                        successful = true;
                    }
                    else
                    {
                        errorLabel.Text = @"Failed to update the " + trimmedTable + @" table.";
                    }
                    break;
                case TrimmingOperationResult.CreatedNewInsertionAndUpdateTables:
                    //Insert the new values...
                    informationLabel.Text += Environment.NewLine + @"Inserting new changes to the " + TextFormat.AddSpacesToSentence(tableName, false) + @" table.";
                    dbWriterStatus = dbW.InsertIntoSalesTable(trimmedTable, dbT.DatabaseConnectionString);
                    if (dbWriterStatus.GetErrorMessage() == string.Empty)
                    {
                        //Spin through the collection and update the affected rows.
                        foreach (var rowIndex in dbWriterStatus.GetRowCollection())
                        {
                            dataGridView.Rows[rowIndex.Key - 1].Cells[(int)SalesTableColumns.Id].Value = rowIndex.Value;
                            dataGridView.Rows[rowIndex.Key - 1].Cells[(int)SalesTableColumns.IsDirty].Value = false;
                        }
                        informationLabel.Text += Environment.NewLine + TextFormat.AddSpacesToSentence(tableName, false) + @" table successfully added to the database.";
                    }
                    else
                    {
                        errorLabel.Text = @"Failed to insert " + trimmedTable + @" into the database.";
                    }
                    //... and update the existing values.
                    informationLabel.Text += Environment.NewLine + @"Updating changes made to the " + TextFormat.AddSpacesToSentence(tableName, false) + @" table.";
                    dbWriterStatus = dbW.UpdateSalesTable(updateTable, dbT.DatabaseConnectionString);
                    if (dbWriterStatus.GetErrorMessage() == string.Empty)
                    {
                        //Spin through the collection and update the affected rows.
                        foreach (var rowIndex in dbWriterStatus.GetRowCollection())
                        {
                            //Only reset the IsDirty value to false since the updates when through.
                            dataGridView.Rows[rowIndex.Key - 1].Cells[(int)SalesTableColumns.IsDirty].Value = false;
                        }
                        informationLabel.Text += Environment.NewLine + TextFormat.AddSpacesToSentence(tableName, false) + @" table successfully updated.";
                        successful = true;
                    }
                    else
                    {
                        errorLabel.Text = @"Failed to update the " + trimmedTable + @" table.";
                    }
                    break;
            }
            dataGridView.RefreshEdit();
            return successful;
        }

        private bool ProcessTrimmingStatusForInventory(TrimmingOperationResult operationStatus, DataTable trimmedTable, DataTable updateTable)
        {
            //Create the database interaction objects.
            var dbT = new DatabaseTracker();
            var dbW = new DatabaseWriter(dbT.DatabaseConnectionString);
            DbTableWriterStatus dbWriterStatus;
            var successful = false;
            switch (operationStatus)
            {
                case TrimmingOperationResult.NoChangesRequired:
                    informationLabel.Text += Environment.NewLine + @"No changes to the Inventory table detected.";
                    successful = true;
                    break;
                case TrimmingOperationResult.CreatedNewInsertionTable:
                    informationLabel.Text += Environment.NewLine + @"Inserting new changes to the Inventory table.";
                    dbWriterStatus = dbW.InsertIntoInventoryTable(trimmedTable, dbT.DatabaseConnectionString);
                    if (dbWriterStatus.GetErrorMessage() == string.Empty)
                    {
                        //Spin through the collection and update the affected rows.
                        foreach (var rowIndex in dbWriterStatus.GetRowCollection())
                        {
                            inventoryDataGridView.Rows[rowIndex.Key - 1].Cells[(int)InventoryTableColumns.Id].Value = rowIndex.Value;
                            inventoryDataGridView.Rows[rowIndex.Key - 1].Cells[(int)InventoryTableColumns.IsDirty].Value = false;
                        }
                        informationLabel.Text += Environment.NewLine + @"Inventory table successfully added to the database.";
                        successful = true;
                    }
                    else
                    {
                        errorLabel.Text = @"Failed to insert Inventory table into the database.";
                    }
                    break;
                case TrimmingOperationResult.CreatedUpdateTable:
                    informationLabel.Text += Environment.NewLine + @"Updating changes made to the Inventory table.";
                    dbWriterStatus = dbW.UpdateInventoryTable(updateTable, dbT.DatabaseConnectionString);
                    if (dbWriterStatus.GetErrorMessage() == string.Empty)
                    {
                        //Spin through the collection and update the affected rows.
                        foreach (var rowIndex in dbWriterStatus.GetRowCollection())
                        {
                            //Only reset the IsDirty value to false since the updates when through.
                            inventoryDataGridView.Rows[rowIndex.Key - 1].Cells[(int)InventoryTableColumns.IsDirty].Value = false;
                        }
                        informationLabel.Text += Environment.NewLine + @"Inventory table successfully updated.";
                        successful = true;
                    }
                    else
                    {
                        errorLabel.Text = @"Failed to update the changes in the Inventory table.";
                    }
                    break;
                case TrimmingOperationResult.CreatedNewInsertionAndUpdateTables:
                    //Insert the new values...
                    informationLabel.Text += Environment.NewLine + @"Inserting new changes to the Inventory table.";
                    dbWriterStatus = dbW.InsertIntoInventoryTable(trimmedTable, dbT.DatabaseConnectionString);
                    if (dbWriterStatus.GetErrorMessage() == string.Empty)
                    {
                        //Spin through the collection and update the affected rows.
                        foreach (var rowIndex in dbWriterStatus.GetRowCollection())
                        {
                            inventoryDataGridView.Rows[rowIndex.Key - 1].Cells[(int)InventoryTableColumns.Id].Value = rowIndex.Value;
                            inventoryDataGridView.Rows[rowIndex.Key - 1].Cells[(int)InventoryTableColumns.IsDirty].Value = false;
                        }
                        informationLabel.Text += Environment.NewLine + @"Inventory table successfully added to the database.";
                        successful = true;
                    }
                    else
                    {
                        errorLabel.Text = @"Failed to insert Inventory table into the database.";
                    }
                    dbWriterStatus = dbW.UpdateInventoryTable(updateTable, dbT.DatabaseConnectionString);
                    if (dbWriterStatus.GetErrorMessage() == string.Empty)
                    {
                        //Spin through the collection and update the affected rows.
                        foreach (var rowIndex in dbWriterStatus.GetRowCollection())
                        {
                            //Only reset the IsDirty value to false since the updates when through.
                            inventoryDataGridView.Rows[rowIndex.Key - 1].Cells[(int) InventoryTableColumns.IsDirty]
                                .Value = false;
                        }
                        informationLabel.Text += Environment.NewLine + @"Inventory table successfully updated.";
                        successful = true;
                    }
                    else
                    {
                        errorLabel.Text = @"Failed to update the changes in the Inventory table.";
                    }
                    break;
            }
            inventoryDataGridView.RefreshEdit();
            return successful;
        }

        #endregion

        #region Debug Operations


        private void idButton_Click(object sender, EventArgs e)
        {
            if (isCommentDirtyCheckBox.Tag == null)
            {
                var ran = new Random();
                isCommentDirtyCheckBox.Tag = ran.Next();
                MessageBox.Show(@"Comment ID is now " + isCommentDirtyCheckBox.Tag, @"Debug ID Test");
            }
            else
            {
                isCommentDirtyCheckBox.Tag = null;
                MessageBox.Show(@"ID cleared from comments.", @"Clear ID Debug");
            }
        }

        private void generateWeeklySalesIdButton_Click(object sender, EventArgs e)
        {
            if (isWeeklySalesDirtyCheckBox.Tag == null)
            {
                var ran = new Random();
                isWeeklySalesDirtyCheckBox.Tag = ran.Next();
                MessageBox.Show(@"Weekly Sales ID is now " + isWeeklySalesDirtyCheckBox.Tag, @"Debug ID Test");
            }
            else
            {
                isWeeklySalesDirtyCheckBox.Tag = null;
                MessageBox.Show(@"ID cleared from Weekly Sales.", @"Clear ID Debug");
            }
        }

        private void generateTaxableIdButton_Click(object sender, EventArgs e)
        {
            if (isTaxableDirtyCheckBox.Tag == null)
            {
                var ran = new Random();
                isTaxableDirtyCheckBox.Tag = ran.Next();
                MessageBox.Show(@"Taxable ID is now " + isTaxableDirtyCheckBox.Tag, @"Debug ID Test");
            }
            else
            {
                isTaxableDirtyCheckBox.Tag = null;
                MessageBox.Show(@"ID cleared from Taxable.", @"Clear ID Debug");
            }
        }

        private void generateCostAnalysisIdButton_Click(object sender, EventArgs e)
        {
            if (isCostAnalysisDirtyCheckBox.Tag == null)
            {
                var ran = new Random();
                isCostAnalysisDirtyCheckBox.Tag = ran.Next();
                MessageBox.Show(@"Cost Analysis ID is now " + isCostAnalysisDirtyCheckBox.Tag, @"Debug ID Test");
            }
            else
            {
                isCostAnalysisDirtyCheckBox.Tag = null;
                MessageBox.Show(@"ID cleared from Cost Analysis.", @"Clear ID Debug");
            }
        }

        #endregion
    }
}
