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 read only Dictionary<int, string> _adItemCollectionDictionary;
        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 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.
        //Structure: "SECTIONUSED":"ADITEMID" Section used means what side of the AdSpecialRow, one (1) being before and two (2) being after.
        //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.
        //The dictionary<int, int> is Dictionary<rowIndex, adItemName>.
        //private readonly List<Dictionary<int, string>> usedAdItems = new List<Dictionary<int, string>>(2);
        private readonly List<string> _usedAdItems = new List<string>(); //ADITEM:SECTIONUSED
        //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;
        //Set the starting value for temporary IDs for ad items that have yet to be added to the database.
        //private int _temporaryKey;
        private readonly AdvertisingProfitControlTableHelper _tableHelperFunctions = new AdvertisingProfitControlTableHelper();
        //Set flags to indicate whether or not a DataGridView needs to be painted.
        private bool _projectionsRequirePainting;
        //Inventory never needs to be parsed on tab page change since no data gets copied over from the other tables.
        private bool _actualSalesRequiresPainting;

        public NewAddRecord()
        {
            InitializeComponent();
            //Start by grabbing all the AdItems and putting them into memory.
            var databaseTracker = new DatabaseTracker();
            var databaseReader = new DatabaseReader();
            //Start by pulling the 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);
            //Assign the events for the comments text box and display the remaining character count for the user.
            commentsTextBox.TextChanged += DisplayRemainingCommentCharacterCount;
            commentsGroupBox.Text = @"Comments (Characters Remaining: " + commentsTextBox.MaxLength + @")";
            //Setup the events for that the Projected and Actual Sales DataGridViews will share.
            //Events are assigned with regard to which event gets triggered first and so on..
            //Hook the row add event so we can paint a row number in the header cell of the row.
            projectionsDataGridView.RowsAdded += DisplayRowNumbers;
            inventoryDataGridView.RowsAdded += DisplayRowNumbers;
            actualSalesDataGridView.RowsAdded += DisplayRowNumbers;
            //Assign all the tables to store the cell's contents on enter so changes (if any) can be detected and flagged (marked as dirty).
            projectionsDataGridView.CellEnter += StoreBeginningCellValue;
            inventoryDataGridView.CellEnter += StoreBeginningCellValue;
            actualSalesDataGridView.CellEnter += StoreBeginningCellValue;
            //Update the contents of the used as item list on row leave.
            projectionsDataGridView.RowLeave += UpdateUsedAdItemCollectionOnRowLeave;
            inventoryDataGridView.RowLeave += UpdateUsedAdItemCollectionOnRowLeave;
            actualSalesDataGridView.RowLeave += UpdateUsedAdItemCollectionOnRowLeave;
            //Validate, clean and format the contents of the cell that fires the cell validating event.
            projectionsDataGridView.CellValidating += ValidateSalesDataGridViewCellContents;
            inventoryDataGridView.CellValidating += ValidateInventoryCellContents;
            actualSalesDataGridView.CellValidating += ValidateSalesDataGridViewCellContents;
            //Validate that the row the user is trying to leave is legal (has at least an ad item entered) and prevent the user from leaving the row is its not.
            projectionsDataGridView.RowValidating += ValidateProjectedRow;
            inventoryDataGridView.RowValidating += ValidateInventoryRow;
            actualSalesDataGridView.RowValidating += ValidateActualSalesRow;
            //Update the used ad item collection by removing the contents of the ad item column when a row is deleted.
            projectionsDataGridView.UserDeletingRow += UpdateUsedAdItemCollectionOnRowRemoving;
            inventoryDataGridView.UserDeletingRow += UpdateUsedAdItemCollectionOnRowRemoving;
            actualSalesDataGridView.UserDeletingRow += UpdateUsedAdItemCollectionOnRowRemoving;
            //Once a row has been removed update the other tables keep them uniform.
            projectionsDataGridView.RowsRemoved += ProjectionRowRemoved;          
            inventoryDataGridView.RowsRemoved += InventoryRowRemoved;
            actualSalesDataGridView.RowsRemoved += ActualSalesRowRemoved;
            //Grab the underlying text box object in the ad item cell, and build an auto complete list for the user.
            projectionsDataGridView.EditingControlShowing += DisplayAutoCompleteOnEditingControlShowing;
            inventoryDataGridView.EditingControlShowing += DisplayAutoCompleteOnEditingControlShowing;
            actualSalesDataGridView.EditingControlShowing += DisplayAutoCompleteOnEditingControlShowing;
            //Setup the event to handle painting the DataGridView on tab page change.
            mainTabControl.SelectedIndexChanged += PaintDataGridViewOnTabPageChange;
            //After all events have been set, construct the DataGridVeiws for use.
            ConstructApcDataGridViews();
            ConstructInvoicesDataGridView();//No weekly sales table is nice.
        }

        private void PaintDataGridViewOnTabPageChange(object sender, EventArgs e)
        {
            var helper = new AdvertisingProfitControlTableHelper();
            switch (mainTabControl.SelectedIndex)
            {
                case 0:
                    if (_projectionsRequirePainting)
                    {
                        helper.PaintRowGroupsFromIndex(0, (DataGridView) mainTabControl.TabPages[0].Controls[0]);
                        _projectionsRequirePainting = false;
                    }
                    break;
                //There is no need to deal with the inventory table here since no data is ever copied over beyond the ad item (or ad special).
                case 2:
                    if (_actualSalesRequiresPainting)
                    {
                        helper.PaintRowGroupsFromIndex(0, (DataGridView)mainTabControl.TabPages[2].Controls[0]);
                        _actualSalesRequiresPainting = false;
                    }
                    break;
            }
        }

        #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 void DisplayRowNumbers(object sender, DataGridViewRowsAddedEventArgs e)
        {
            var table = ((DataGridView)sender);
            //Set a flag based on what tab page is currently being used to indicate whether or not a DataGridView needs painting.
            switch (mainTabControl.SelectedIndex)
            {
                case 0:
                    _projectionsRequirePainting = false;
                    _actualSalesRequiresPainting = true;
                    break;
                case 1:            
                    _projectionsRequirePainting = true;
                    _actualSalesRequiresPainting = true;
                    break;
                case 2:
                    _projectionsRequirePainting = true;
                    _actualSalesRequiresPainting = false;
                    break;
            }
            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.Contains(userInput + ":1")) return;
                _usedAdItems.Add(userInput + ":1");
                LogConsole.WriteToLog(FrmLogConsole.Level.Debug, "Adding \"" + userInput + "\" to section one (1).");
            }
            //Section two (2) detected.
            else
            {
                if (_usedAdItems.Contains(userInput + ":2")) return;
                _usedAdItems.Add(userInput + ":2");
                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)
                    {
                        var adItemString = adItem.Split(':');
                        var section = adItemString[1];
                        var adItemToRemove = adItemString[0];
                        if (section == "1")
                        {
                            customList.RemoveAll(
                                w => w.Equals(adItemToRemove, StringComparison.OrdinalIgnoreCase));
                        }
                    }
                }
                //Occurs AFTER the AdSpecial row.
                else if (dataGridView.CurrentCell.RowIndex > _adSpecialIndex)
                {
                    foreach (var adItem in _usedAdItems)
                    {
                        var adItemString = adItem.Split(':');
                        var section = adItemString[1];
                        var adItemToRemove = adItemString[0];
                        if (section == "2")
                        {
                            customList.RemoveAll(
                                w => w.Equals(adItemToRemove, 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 || currentRowIndex < _adSpecialIndex)
            {
                //If the ad item entered in the first cell is in the gUsedAdItems collection, then remove it from there.
                if (_usedAdItems.Contains(dataGridView.Rows[currentRowIndex].Cells[(int) SalesTableColumns.AdItem].EditedFormattedValue + ":1"))
                {
                    _usedAdItems.Remove(dataGridView.Rows[currentRowIndex].Cells[(int)SalesTableColumns.AdItem].EditedFormattedValue + ":1");
                }
            }
            else if (currentRowIndex > _adSpecialIndex)
            {
                //If the ad item entered in the first cell is in the gUsedAdItems collection, then remove it from there.
                if (_usedAdItems.Contains(dataGridView.Rows[currentRowIndex].Cells[(int)SalesTableColumns.AdItem].EditedFormattedValue + ":2"))
                {
                    _usedAdItems.Remove(dataGridView.Rows[currentRowIndex].Cells[(int)SalesTableColumns.AdItem].EditedFormattedValue + ":2");
                }
            }
            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.
                        if (_usedAdItems.Contains(dataGridView.Rows[currentRowIndex].Cells[(int)SalesTableColumns.AdItem].EditedFormattedValue + ":2"))
                        {
                            _usedAdItems.Remove(dataGridView.Rows[currentRowIndex].Cells[(int)SalesTableColumns.AdItem].EditedFormattedValue + ":2");
                        }
                        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)
                        {
                           projectionsDataGridView.Rows[index].Cells[(int) SalesTableColumns.IsDirty].Value = true; 
                        }
                        if (index < actualSalesDataGridView.RowCount)
                        {
                            actualSalesDataGridView.Rows[index].Cells[(int)SalesTableColumns.IsDirty].Value = true;
                        }
                        if (index < inventoryDataGridView.RowCount)
                        {
                            inventoryDataGridView.Rows[index].Cells[(int)InventoryTableColumns.IsDirty].Value = true;
                        }                       
                    }
                }
                _usedAdItems.Remove(_beginningCellValue + (_adSpecialIndex == -1 || e.RowIndex < _adSpecialIndex ? ":1" : ":2"));
                dataGridView.Rows[e.RowIndex].Cells[(int) SalesTableColumns.IsDirty].Value = true;
            }
            double parsedNumber;
            //Check to see if the current column is the ad item column.
            switch (e.ColumnIndex)
            {
                case (int)SalesTableColumns.AdItem: //Ad Item
                    //If there is text after all the whitespace has been cleared, clear the error text property regardless of whether or not it is set.
                    if (!string.IsNullOrEmpty(Regex.Replace(userInput, @"\s+", "")))
                    {
                        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);
                        //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.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"));
                    }
                    else
                    {
                        if (userInput == "")
                        {
                            return;
                        }
                        MessageBox.Show(@"Non numeric characters in column " + (e.ColumnIndex + 1) + @" are not allowed.", @"Invalid Characters Detected");
                        e.Cancel = true;
                        dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = "";
                        dataGridView.RefreshEdit();
                        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}";
                        //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"));
                    }
                    else
                    {
                        if (userInput == "")
                        {
                            return;
                        }
                        MessageBox.Show(@"Non numeric characters in column " + (e.ColumnIndex + 1) + @" are not allowed.", @"Invalid Characters Detected");
                        e.Cancel = true;
                        dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = "";
                        dataGridView.RefreshEdit();
                        return;
                    }
                    break;
                default:
                    //Purely here for protection against parsing the Boolean columns by mistake.
                    if (e.ColumnIndex >= (int) SalesTableColumns.IsAdSpecialRow) {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"));
                    }
                    else
                    {
                        if (userInput == "")
                        {
                            return;
                        }
                        MessageBox.Show(@"Non numeric characters in column " + (e.ColumnIndex + 1) + @" are not allowed.", @"Invalid Characters Detected");
                        e.Cancel = true;
                        dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = "";
                        dataGridView.RefreshEdit();
                        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+", "") == "")
            {
                MessageBox.Show(@"An ad item is required.", @"No Ad Item Specified");
                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;
            }
            //Now check to make sure there is an ad item present, otherwise throw an error and block the user from leaving the current row.
            if (projectionsDataGridView.Rows[e.RowIndex].Cells[adItemIndex].EditedFormattedValue.ToString() != "")
            {
                //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.RemoveAll(I => I.Equals(_beginningCellValue + ":1", StringComparison.OrdinalIgnoreCase));
                        }
                        else
                        {
                            _usedAdItems.RemoveAll(I => I.Equals(_beginningCellValue + ":2", 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.IsHeaderRow:
                            rowContents[i] = projectionsDataGridView.Rows[e.RowIndex].Cells[(int)SalesTableColumns.IsHeaderRow].Value;
                            break;
                        case (int)SalesTableColumns.IsMemberRow:
                            rowContents[i] = projectionsDataGridView.Rows[e.RowIndex].Cells[(int)SalesTableColumns.IsMemberRow].Value;
                            break;
                        case (int)SalesTableColumns.IsAdSpecialRow:
                            //Determine if the current row is the special row.
                            projectionsDataGridView.Rows[e.RowIndex].Cells[(int) SalesTableColumns.IsAdSpecialRow].Value =
                                e.RowIndex == _adSpecialIndex;
                            rowContents[i] = e.RowIndex == _adSpecialIndex;
                            break;
                        case (int)SalesTableColumns.IsAdSpecialMember:
                            //Check if this is a member of the ad special group.
                            if (_adSpecialIndex != -1)
                            {
                                projectionsDataGridView.Rows[e.RowIndex].Cells[(int) SalesTableColumns.IsAdSpecialMember
                                    ].Value = e.RowIndex > _adSpecialIndex;
                                rowContents[i] = e.RowIndex > _adSpecialIndex;
                            }
                            else
                            {
                                rowContents[i] = false;
                            }
                            break;
                        case (int)SalesTableColumns.IsDirty:
                            rowContents[i] = true;
                            break;
                        case (int)SalesTableColumns.IsInDatabase:
                            rowContents[i] = false;
                            break;
                        default:
                            rowContents[i] = "";
                            break;
                    }
                }
                actualSalesDataGridView.Rows.Add(rowContents);
                //Build a collection of objects for the inventory table to use.
                var inventoryNewRow = new object[inventoryDataGridView.ColumnCount];
                //Spin through the DataGridViewCells in the row and add their contents to an array.
                for (var i = 0; i < projectionsDataGridView.ColumnCount; i++)
                {
                    //Grab the Ad Item in the first cell and add it into the array.
                    switch (i)
                    {
                        case (int)SalesTableColumns.Id:
                            inventoryNewRow[(int)InventoryTableColumns.Id] = "";
                            break;
                        case (int)SalesTableColumns.AdItem:
                            inventoryNewRow[(int)InventoryTableColumns.AdItem] =
                                projectionsDataGridView.Rows[e.RowIndex].Cells[i].EditedFormattedValue.ToString();
                            break;
                        case (int)SalesTableColumns.IsHeaderRow:
                            rowContents[(int)InventoryTableColumns.IsHeaderRow] = projectionsDataGridView.Rows[e.RowIndex].Cells[(int)SalesTableColumns.IsHeaderRow].Value;
                            break;
                        case (int)SalesTableColumns.IsMemberRow:
                            rowContents[(int)InventoryTableColumns.IsMemberRow] = projectionsDataGridView.Rows[e.RowIndex].Cells[(int)SalesTableColumns.IsMemberRow].Value;
                            break;
                        case (int)SalesTableColumns.IsAdSpecialRow:
                            //Determine if the current row is the special row.
                            inventoryNewRow[(int)InventoryTableColumns.IsAdSpecialRow] = (e.RowIndex == _adSpecialIndex);
                            break;
                        case (int)SalesTableColumns.IsAdSpecialMember:
                            //Check if this is a member of the ad special group.
                            if (_adSpecialIndex != -1)
                            {
                                inventoryNewRow[(int)InventoryTableColumns.IsAdSpecialMember] = (e.RowIndex > _adSpecialIndex);
                            }
                            else
                            {
                                inventoryNewRow[(int)InventoryTableColumns.IsAdSpecialMember] = false;
                            }
                            break;
                        case (int)SalesTableColumns.IsDirty:
                            inventoryNewRow[(int)InventoryTableColumns.IsDirty] = true;
                            break;
                        case (int)SalesTableColumns.IsInDatabase:
                            inventoryNewRow[(int) InventoryTableColumns.IsInDatabase] = false;
                            break;
                        default:
                            if (i < (int) InventoryTableColumns.IsHeaderRow)
                            {
                                inventoryNewRow[i] = "";
                            }        
                            break;
                    }
                }
                inventoryDataGridView.Rows.Add(inventoryNewRow);
            }
            else
            {
                MessageBox.Show(@"An Ad Item is required.", @"Invalid Ad Item");
                projectionsDataGridView.Rows[e.RowIndex].Cells[adItemIndex].Selected = true;
                e.Cancel = true;
            }
        }

        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;
                    }
                    else
                    {
                        //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)
                            {
                                projectionsDataGridView.Rows[index].Cells[(int)SalesTableColumns.IsDirty].Value = true;
                            }
                            if (index < actualSalesDataGridView.RowCount)
                            {
                                actualSalesDataGridView.Rows[index].Cells[(int)SalesTableColumns.IsDirty].Value = true;
                            }
                            if (index < inventoryDataGridView.RowCount)
                            {
                                inventoryDataGridView.Rows[index].Cells[(int)InventoryTableColumns.IsDirty].Value = true;
                            }
                        }
                    }
                }
                dataGridView.Rows[e.RowIndex].Cells[(int) InventoryTableColumns.IsDirty].Value = true;
                _usedAdItems.Remove(_beginningCellValue + (_adSpecialIndex == -1 || e.RowIndex < _adSpecialIndex ? ":1" : ":2"));
            }
            //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);
                        //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.IsAdSpecialRow) { 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.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))
                    {
                        MessageBox.Show(
                            @"Non numeric characters in column " + (e.ColumnIndex + 1) + @" are not allowed.",
                            @"Invalid Characters Detected");
                        e.Cancel = true;
                        dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = "";
                        dataGridView.RefreshEdit();
                        return;
                    }
                    //Add the value to the cell.
                    dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = userInput;
                    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)SalesTableColumns.AdItem;
            //Do not even attempt anything since this is a new row and nothing to worry about.
            if (inventoryDataGridView.Rows[e.RowIndex].IsNewRow)
            {
                return;
            }
            //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;
            }
            //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+", "") == "")
            {
                MessageBox.Show(@"An ad item is required.", @"No Ad Item Specified");
                e.Cancel = true;
            }
            //Now check to make sure there is an ad item present, otherwise throw an error and block the user from leaving the current row.
            if (inventoryDataGridView.Rows[e.RowIndex].Cells[adItemIndex].EditedFormattedValue.ToString() != "")
            {
                //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.RemoveAll(I => I.Equals(_beginningCellValue + ":1", StringComparison.OrdinalIgnoreCase));
                        }
                        else
                        {
                            _usedAdItems.RemoveAll(I => I.Equals(_beginningCellValue + ":2", 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.IsHeaderRow:
                            rowContents[i] = inventoryDataGridView.Rows[e.RowIndex].Cells[(int)InventoryTableColumns.IsHeaderRow].Value;
                            break;
                        case (int)SalesTableColumns.IsMemberRow:
                            rowContents[i] = projectionsDataGridView.Rows[e.RowIndex].Cells[(int)InventoryTableColumns.IsMemberRow].Value;
                            break;
                        case (int)SalesTableColumns.IsAdSpecialRow:
                            //Determine if the current row is the special row.
                            inventoryDataGridView.Rows[e.RowIndex].Cells[(int)InventoryTableColumns.IsAdSpecialRow].Value =
                                e.RowIndex == _adSpecialIndex;
                            rowContents[i] = e.RowIndex == _adSpecialIndex;
                            break;
                        case (int)SalesTableColumns.IsAdSpecialMember:
                            //Check if this is a member of the ad special group.
                            if (_adSpecialIndex != -1)
                            {
                                inventoryDataGridView.Rows[e.RowIndex].Cells[(int)InventoryTableColumns.IsAdSpecialMember].Value = e.RowIndex > _adSpecialIndex;
                                rowContents[i] = e.RowIndex > _adSpecialIndex;
                            }
                            else
                            {
                                rowContents[i] = false;
                            }
                            break;
                        case (int)SalesTableColumns.IsDirty:
                            rowContents[i] = true;
                            break;
                        case (int)SalesTableColumns.IsInDatabase:
                            rowContents[i] = false;
                            break;
                        default:
                            rowContents[i] = "";
                            break;
                    }
                }
                projectionsDataGridView.Rows.Add(rowContents);
                actualSalesDataGridView.Rows.Add(rowContents);
            }
            else
            {
                MessageBox.Show(@"An Ad Item is required.", @"Invalid Ad Item");
                projectionsDataGridView.Rows[e.RowIndex].Cells[adItemIndex].Selected = true;
                e.Cancel = true;
            }
        }

        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;
            }
            //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;
            }
            //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+", "") == "")
            {
                MessageBox.Show(@"An ad item is required.", @"No Ad Item Specified");
                e.Cancel = true;
            }
            //Now check to make sure there is an ad item present, otherwise throw an error and block the user from leaving the current row.
            if (actualSalesDataGridView.Rows[e.RowIndex].Cells[adItemIndex].EditedFormattedValue.ToString() != "")
            {
                //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.RemoveAll(I => I.Equals(_beginningCellValue + ":1", StringComparison.OrdinalIgnoreCase));
                        }
                        else
                        {
                            _usedAdItems.RemoveAll(I => I.Equals(_beginningCellValue + ":2", 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.IsHeaderRow:
                            rowContents[i] = actualSalesDataGridView.Rows[e.RowIndex].Cells[(int) SalesTableColumns.IsHeaderRow].Value;
                            break;
                        case (int)SalesTableColumns.IsMemberRow:
                            rowContents[i] = actualSalesDataGridView.Rows[e.RowIndex].Cells[(int)SalesTableColumns.IsMemberRow].Value;
                            break;
                        case (int)SalesTableColumns.IsAdSpecialRow:
                            //Determine if the current row is the special row.
                            actualSalesDataGridView.Rows[e.RowIndex].Cells[(int)SalesTableColumns.IsAdSpecialRow].Value =
                                e.RowIndex == _adSpecialIndex;
                            rowContents[i] = e.RowIndex == _adSpecialIndex;
                            break;
                        case (int)SalesTableColumns.IsAdSpecialMember:
                            //Check if this is a member of the ad special group.
                            if (_adSpecialIndex != -1)
                            {
                                actualSalesDataGridView.Rows[e.RowIndex].Cells[(int)SalesTableColumns.IsAdSpecialMember
                                    ].Value = e.RowIndex > _adSpecialIndex;
                                rowContents[i] = e.RowIndex > _adSpecialIndex;
                            }
                            else
                            {
                                rowContents[i] = false;
                            }
                            break;
                        case (int)SalesTableColumns.IsDirty:
                            rowContents[i] = true;
                            break;
                        case (int)SalesTableColumns.IsInDatabase:
                            rowContents[i] = false;
                            break;
                        default:
                            rowContents[i] = "";
                            break;
                    }
                }
                projectionsDataGridView.Rows.Add(rowContents);
                //Build a collection of objects for the inventory table to use.
                var inventoryNewRow = new object[inventoryDataGridView.ColumnCount];
                //Spin through the DataGridViewCells in the row and add their contents to an array.
                for (var i = 0; i < actualSalesDataGridView.ColumnCount; i++)
                {
                    //Grab the Ad Item in the first cell and add it into the array.
                    switch (i)
                    {
                        case (int)SalesTableColumns.AdItem:
                            inventoryNewRow[(int)InventoryTableColumns.AdItem] =
                                actualSalesDataGridView.Rows[e.RowIndex].Cells[i].EditedFormattedValue.ToString();
                            break;
                        case (int)SalesTableColumns.IsHeaderRow:
                            rowContents[(int)InventoryTableColumns.IsHeaderRow] = actualSalesDataGridView.Rows[e.RowIndex].Cells[(int)SalesTableColumns.IsHeaderRow].Value;
                            break;
                        case (int)SalesTableColumns.IsMemberRow:
                            rowContents[(int)InventoryTableColumns.IsMemberRow] = actualSalesDataGridView.Rows[e.RowIndex].Cells[(int)SalesTableColumns.IsMemberRow].Value;
                            break;
                        case (int)SalesTableColumns.IsAdSpecialRow:
                            //Determine if the current row is the special row.
                            inventoryNewRow[(int)InventoryTableColumns.IsAdSpecialRow] = e.RowIndex == _adSpecialIndex;
                            break;
                        case (int)SalesTableColumns.IsAdSpecialMember:
                            //Check if this is a member of the ad special group.
                            if (_adSpecialIndex != -1)
                            {
                                inventoryNewRow[(int) InventoryTableColumns.IsAdSpecialMember] = e.RowIndex > _adSpecialIndex;
                            }
                            else
                            {
                                inventoryNewRow[(int)InventoryTableColumns.IsAdSpecialMember] = false;
                            }
                            break;
                        case (int)SalesTableColumns.IsDirty:
                            inventoryNewRow[(int)InventoryTableColumns.IsDirty] = true;
                            break;
                        case (int)SalesTableColumns.IsInDatabase:
                            inventoryNewRow[(int)InventoryTableColumns.IsInDatabase] = false;
                            break;
                        default:
                            if (i > (int)InventoryTableColumns.AdItem && i < (int)InventoryTableColumns.IsHeaderRow || i == (int)InventoryTableColumns.Id)
                            {
                                inventoryNewRow[i] = "";
                            }
                            break;
                    }
                }
                inventoryDataGridView.Rows.Add(inventoryNewRow);
            }
            else
            {
                MessageBox.Show(@"An Ad Item is required.", @"Invalid Ad Item");
                projectionsDataGridView.Rows[e.RowIndex].Cells[adItemIndex].Selected = true;
                e.Cancel = true;
            }
        }

        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", "IsAdSpecialRow", "IsAdSpecialMember", "IsDirty", "IsInDatabase"
            };
            string[] inventoryColumnNames =
            {
                "ID", "AdItem", "BeginningInventory", "Received", "Total", "EndingInventory", "IsHeader", "IsMember", "IsAdSpecialRow", "IsAdSpecialMember", "IsDirty", "IsInDatabase"
            };

            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 = { "InvoiceDate", "Supplier", "InvoiceNumber", "InvoiceNetAmountAtCost", "InvoiceNetAmount", "InvoiceNote", "IsDirty", "IsInDatabase"};

            foreach (var name in invoicesColumnNames)
            {
                var column = new DataGridViewColumn { Name = name };
                if (!name.StartsWith("Is"))
                {
                    column.HeaderText = TextFormat.AddSpacesToSentence(name, false);
                    column.ValueType = typeof(string);
                }
                else
                {
                    column.HeaderText = TextFormat.AddSpacesToSentence(name, false);
                    column.Visible = false;
                    column.ValueType = typeof(bool);
                }
                column.CellTemplate = new DataGridViewTextBoxCell();
                invoicesDataGridView.Columns.Add(column);
            }
        }

        #endregion

        #region Comments TextBox Events
        /// <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) + @")";
        }
        #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");
        }

        #endregion

        private void getCellValueDebugMainMenu_Click(object sender, EventArgs e)
        {
            var dataGridView = (DataGridView)mainTabControl.TabPages[0].Controls[0];
            MessageBox.Show(dataGridView.CurrentRow.DefaultCellStyle.BackColor.Name);
        }

        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.
            var trimmedProjectionsTable = ConstructCleanedProjectionsTable(dateId);
            //var trimmedInventoryTable = ConstructCleanedInventoryTable(dateId);
            //var trimmedActualSalesTable = ConstructCleanedActualSalesTable(dateId);
            //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
            var projectionsAdditions = dbW.InsertIntoSalesTable(trimmedProjectionsTable.ElementAt(0), dbT.DatabaseConnectionString);
            foreach (var rowIndex in projectionsAdditions)
            {
                projectionsDataGridView.Rows[rowIndex.Key - 1].Cells[(int) SalesTableColumns.Id].Value = rowIndex.Value;
                projectionsDataGridView.Rows[rowIndex.Key - 1].Cells[(int)SalesTableColumns.IsDirty].Value = false;
                projectionsDataGridView.Rows[rowIndex.Key - 1].Cells[(int)SalesTableColumns.IsInDatabase].Value = true;
            }
            //dbW.UpdateSalesTable(trimmedProjectionsTable.ElementAt(1), dbT.DatabaseConnectionString);
        }

        #region APC Table Trimming

        private IEnumerable<DataTable> ConstructCleanedProjectionsTable(int dateId)
        {
            //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
            var trimmedNewProjectionsTable = new DataTable("Projections");
            //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
            var trimmedUpdateProjectionsTable = new DataTable("Projections");
            DataTable[] trimmedTables = { trimmedNewProjectionsTable, trimmedUpdateProjectionsTable };
            //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);
                trimmedTables[0].Columns.Add(column);
            }
            foreach (var columnName in saleColumnNames)
            {
                var column = new DataColumn(columnName);
                trimmedTables[1].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).
            //Dictionary<AdItemID, TableID> The table ID is zero (0) for the new table and one (1) for the update table.
            var usedAdItems = new Dictionary<int, int>(); //Contains ad items that are used in section one, used for checking for repeats.
            //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(
                    projectionsDataGridView.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 projectionsDataGridView.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)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)
                    {
                        errorLabel.Text = @"Failed to insert new ad item.";
                        //TODO: Throw an exception, this can not be allowed.
                        //AdItemInsertionFailedException
                        trimmedTables[0].Rows.Clear(); //Work around for now
                        trimmedTables[1].Rows.Clear();
                        //throw new InvalidOperationException("Failed to add ad item.");
                        //break;
                    }
                }
                int tableIndex;
                //Check for repeated ad items in the ad special section
                if (usedAdItems.TryGetValue(adItemId, out tableIndex))
                {
                    //If the ad item is being used in section one then locate it and update it in the trimmed table.
                    var foundRow = trimmedTables[tableIndex].Select("AdItemID = '" + adItemId + "'");
                    if (foundRow.Length == 1)
                    {
                        LogConsole.WriteToLog(FrmLogConsole.Level.Info,
                            "Ad item '" + row.Cells[(int)SalesTableColumns.AdItem].EditedFormattedValue +
                            "' found in the trimmed table.");
                    }
                    else
                    {
                        //TODO: Throw an exception, this can not be allowed.
                        //InvalidTrimmedRowCountException
                        trimmedTables[0].Rows.Clear(); //Work around for now
                        trimmedTables[1].Rows.Clear();
                        break;
                    }
                    //Begin spinning through all the rows to find the one selected above.
                    for (var i = 0; i < trimmedTables[tableIndex].Rows.Count; i++)
                    {
                        //Check to see if the selected row is equal.
                        if (foundRow[0] != trimmedTables[tableIndex].Rows[i]) continue;
                        //If so then update that row index with the group ID number.
                        if (tableIndex == 0)
                        {
                            trimmedTables[0].Rows[i][8] = adSpecialId;
                        }
                        else
                        {
                            trimmedTables[1].Rows[i][9] = adSpecialId;
                        }
                    }
                    //Once ad special ID has been updated jump to the next row.
                    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;
                }
                //Since we've made it this far, add the ad item into the dictionary if we're not in the ad special group.
                if (_adSpecialIndex != -1 && row.Index > _adSpecialIndex)
                {
                    usedAdItems.Add(row.Index, adItemId);
                }
                //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;
                    trimmedTables[0].Rows.Add(newRow);
                    usedAdItems.Add(adItemId, 0);
                }
                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;
                    trimmedTables[1].Rows.Add(newRow);
                    usedAdItems.Add(adItemId, 1);
                }
                //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);
            }

            return trimmedTables;
        }

        private IEnumerable<DataTable> ConstructCleanedInventoryTable(int dateId)
        {
            //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:BeginingInventory 1:Received 2:TotalInventory 3:EndingInventory 4:AdItemID 5:RowAttribute
            //6:FK_AdSpecialGroupName (ID) 7:RowPosition (not index based) 8:DateID
            var trimmedNewInventoryTable = new DataTable("Inventory");
            //Update Sales Table Layout (Based on the Database's Physical Layout)
            //0:ID 1:BeginingInventory 2:Received 3:TotalInventory 4:EndingInventory 5:AdItemID 6:RowAttribute
            //7:FK_AdSpecialGroupName (ID) 8:RowPosition (not index based) 9:DateID
            var trimmedUpdateInventoryTable = new DataTable("Inventory");
            DataTable[] trimmedTables = { trimmedNewInventoryTable, trimmedUpdateInventoryTable };
            //Construct a list of column names for the projections/actual sales DataGridViews and the inventory DataGirdView.
            string[] saleColumnNames =
            {
                "ID", "BeginingInventory", "Received", "TotalInventory", "EndingInventory", "AdItemID", "RowAttribute", "AdSpecialID", "RowPosition", "DateID"
            };
            foreach (var columnName in saleColumnNames)
            {
                if (columnName == "ID") continue;
                var column = new DataColumn(columnName);
                trimmedTables[0].Columns.Add(column);
            }
            foreach (var columnName in saleColumnNames)
            {
                var column = new DataColumn(columnName);
                trimmedTables[1].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).
            //Dictionary<AdItemID, TableID> The table ID is zero (0) for the new table and one (1) for the update table.
            var usedAdItems = new Dictionary<int, int>(); //Contains ad items that are used in section one, used for checking for repeats.
            //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 not dirty.
                if (!(bool)row.Cells[(int)InventoryTableColumns.IsDirty].Value)
                {
                    //If so simply continue.
                    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)
                    {
                        errorLabel.Text = @"Failed to insert new ad item.";
                        //TODO: Throw an exception, this can not be allowed.
                        //AdItemInsertionFailedException
                        trimmedTables[0].Rows.Clear(); //Work around for now
                        trimmedTables[1].Rows.Clear();
                        break;
                    }
                }
                int tableIndex;
                //Check for repeated ad items in the ad special section
                if (usedAdItems.TryGetValue(adItemId, out tableIndex))
                {
                    //If the ad item is being used in section one then locate it and update it in the trimmed table.
                    var foundRow = trimmedTables[tableIndex].Select("AdItemID = '" + adItemId + "'");
                    if (foundRow.Length == 1)
                    {
                        LogConsole.WriteToLog(FrmLogConsole.Level.Info,
                            "Ad item '" + row.Cells[(int)InventoryTableColumns.AdItem].EditedFormattedValue +
                            "' found in the trimmed table.");
                    }
                    else
                    {
                        //TODO: Throw an exception, this can not be allowed.
                        //InvalidTrimmedRowCountException
                        trimmedTables[0].Rows.Clear(); //Work around for now
                        trimmedTables[1].Rows.Clear();
                        break;
                    }
                    //Begin spinning through all the rows to find the one selected above.
                    for (var i = 0; i < trimmedTables[tableIndex].Rows.Count; i++)
                    {
                        //Check to see if the selected row is equal.
                        if (foundRow[0] != trimmedTables[tableIndex].Rows[i]) continue;
                        //If so then update that row index with the group ID number.
                        if (tableIndex == 0)
                        {
                            trimmedTables[0].Rows[i][8] = adSpecialId;
                        }
                        else
                        {
                            trimmedTables[1].Rows[i][9] = adSpecialId;
                        }
                    }
                    //Once ad special ID has been updated jump to the next row.
                    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;
                }
                //Since we've made it this far, add the ad item into the dictionary if we're not in the ad special group.
                if (_adSpecialIndex != -1 && row.Index < _adSpecialIndex)
                {
                    usedAdItems.Add(row.Index, adItemId);
                }
                //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)InventoryTableColumns.BeginningInventory].EditedFormattedValue.ToString();//Sold, is string
                    newRow[1] = row.Cells[(int)InventoryTableColumns.Recieved].EditedFormattedValue.ToString();//Received, is string
                    newRow[2] = row.Cells[(int)InventoryTableColumns.Total].EditedFormattedValue.ToString();//Total, is string
                    newRow[3] = row.Cells[(int)InventoryTableColumns.EndingInventory].EditedFormattedValue.ToString();//EndingInventory, 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;
                    trimmedTables[0].Rows.Add(newRow);
                    usedAdItems.Add(adItemId, 0);
                }
                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)InventoryTableColumns.BeginningInventory].EditedFormattedValue.ToString();//Sold, is string
                    newRow[2] = row.Cells[(int)InventoryTableColumns.Recieved].EditedFormattedValue.ToString();//Received, is string
                    newRow[3] = row.Cells[(int)InventoryTableColumns.Total].EditedFormattedValue.ToString();//Total, is string
                    newRow[4] = row.Cells[(int)InventoryTableColumns.EndingInventory].EditedFormattedValue.ToString();//EndingInventory, 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;
                    trimmedTables[1].Rows.Add(newRow);
                    usedAdItems.Add(adItemId, 1);
                }
            }

            return trimmedTables;
        }

        private IEnumerable<DataTable> ConstructCleanedActualSalesTable(int dateId)
        {
            //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
            var trimmedNewProjectionsTable = new DataTable("ACtualSales");
            //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
            var trimmedUpdateProjectionsTable = new DataTable("ActualSales");
            DataTable[] trimmedTables = { trimmedNewProjectionsTable, trimmedUpdateProjectionsTable };
            //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);
                trimmedTables[0].Columns.Add(column);
            }
            foreach (var columnName in saleColumnNames)
            {
                var column = new DataColumn(columnName);
                trimmedTables[1].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).
            //Dictionary<AdItemID, TableID> The table ID is zero (0) for the new table and one (1) for the update table.
            var usedAdItems = new Dictionary<int, int>(); //Contains ad items that are used in section one, used for checking for repeats.
            //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(
                    projectionsDataGridView.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 actualSalesDataGridView.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 not dirty.
                if (!(bool)row.Cells[(int)SalesTableColumns.IsDirty].Value)
                {
                    //If so simply continue.
                    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)
                    {
                        errorLabel.Text = @"Failed to insert new ad item.";
                        //TODO: Throw an exception, this can not be allowed.
                        //AdItemInsertionFailedException
                        trimmedTables[0].Rows.Clear(); //Work around for now
                        trimmedTables[1].Rows.Clear();
                        break;
                    }
                }
                int tableIndex;
                //Check for repeated ad items in the ad special section
                if (usedAdItems.TryGetValue(adItemId, out tableIndex))
                {
                    //If the ad item is being used in section one then locate it and update it in the trimmed table.
                    var foundRow = trimmedTables[tableIndex].Select("AdItemID = '" + adItemId + "'");
                    if (foundRow.Length == 1)
                    {
                        LogConsole.WriteToLog(FrmLogConsole.Level.Info,
                            "Ad item '" + row.Cells[(int)SalesTableColumns.AdItem].EditedFormattedValue +
                            "' found in the trimmed table.");
                    }
                    else
                    {
                        //TODO: Throw an exception, this can not be allowed.
                        //InvalidTrimmedRowCountException
                        trimmedTables[0].Rows.Clear(); //Work around for now
                        trimmedTables[1].Rows.Clear();
                        break;
                    }
                    //Begin spinning through all the rows to find the one selected above.
                    for (var i = 0; i < trimmedTables[tableIndex].Rows.Count; i++)
                    {
                        //Check to see if the selected row is equal.
                        if (foundRow[0] != trimmedTables[tableIndex].Rows[i]) continue;
                        //If so then update that row index with the group ID number.
                        if (tableIndex == 0)
                        {
                            trimmedTables[0].Rows[i][8] = adSpecialId;
                        }
                        else
                        {
                            trimmedTables[1].Rows[i][9] = adSpecialId;
                        }
                    }
                    //Once ad special ID has been updated jump to the next row.
                    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;
                }
                //Since we've made it this far, add the ad item into the dictionary if we're not in the ad special group.
                if (_adSpecialIndex != -1 && row.Index < _adSpecialIndex)
                {
                    usedAdItems.Add(row.Index, adItemId);
                }
                //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;
                    trimmedTables[0].Rows.Add(newRow);
                    usedAdItems.Add(adItemId, 0);
                }
                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;
                    trimmedTables[1].Rows.Add(newRow);
                    usedAdItems.Add(adItemId, 1);
                }
                //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);
            }

            return trimmedTables;
        }

        #endregion
    }
}
