public JsonResult CreateActivity(ActivityModel model)
        {
            if (!ModelState.IsValid)
            {
                return Json(new
                {
                    Result = "ERROR",
                    Message = "Form is not valid! " +
                    "Please correct it and try again."
                });
            }

            try
            {
                JourListDMContainer dm = new JourListDMContainer();

                Activity newActivity = new Activity();
                newActivity.Points = model.Points;
                newActivity.Description = model.Description;
                newActivity.Unit = dm.Units.Single(z => z.Id == model.UnitId);
                newActivity.Quantity = model.Quantity;
                dm.AddToActivities(newActivity);
                dm.SaveChanges();

                model.Id = newActivity.Id;

                return Json(new { Result = "OK", Record = model });
            }
            catch (Exception e)
            {
                return Json(new { Result = "ERROR", Message = e.Message });
            }
        }
        public JsonResult CreateActivityLog(ActivityLogModel model)
        {
            var dm = new JourListDMContainer();
            var log = new ActivityLog();
            var member = dm.Members.SingleOrDefault(z => z.Name == User.Identity.Name);
            if (member == null)
                return JsonError("You don't exist");

            var journal = member.Journals.Single(z => z.Id == model.JourId);
            if (journal == null)
                return JsonError("This journal doesn't belong to you");

            log.Activity = dm.Activities.Single(z => z.Id == model.ActId);
            log.Quantity = model.Quantity;
            // TODO: Hyperlink & Notes should be updated to default to an
            //       empty string in the databaseif the value are null,
            //       the EM has been updated, but the database needs to
            //       be updated to reflect the default value of "".
            log.Notes = model.Notes;
            log.Hyperlink = model.Hyperlink;
            log.Unit = dm.Units.Single(z => z.Id == model.UnitId);
            log.Journal = journal;
            dm.ActivityLogs.AddObject(log);
            dm.SaveChanges();
            //            model.Points = log.Activity.Points;
            //            model.TotalPoints = (int)Math.Round(log.Activity.Points * log.Quantity);
            model.LogId = log.Id;
            //            return Json(model);
            return Json(new { Result = "OK", Record = model });
            //            return JsonError("Not Done");
        }
        public JsonResult DeleteActivityLog(long LogId)
        {
            JourListDMContainer dm = new JourListDMContainer();

            if (User.Identity.IsAuthenticated != true)
                return JsonError("Please log in");

            var member = dm.Members.SingleOrDefault(z => z.Name == User.Identity.Name);
            if (member == null)
                return JsonError("You do not exist");

            var log = dm.ActivityLogs.SingleOrDefault(z => z.Id == LogId);
            if (log == null)
                return JsonError("That log does not exist");

            if (log.Journal.Member != member)
                return JsonError("This log does not belong to you");

            dm.ActivityLogs.DeleteObject(log);

            dm.SaveChanges();

            return JsonOk("Deleted");
        }
        public JsonResult DeleteItem(int id)
        {
            if (!User.Identity.IsAuthenticated)
            {
                return Json(new
                {
                    Result = "ERROR",
                    Message = "You need to log in to delete an item."
                });
            }

            if (!User.IsInRole("Officer"))
            {
                return Json(new
                {
                    Result = "ERROR",
                    Message = "You do not have the authority to delete an item."
                });
            }

            try
            {
                JourListDMContainer dm = new JourListDMContainer();

                // Grab the item
                Item item = dm.Items.OfType<StandardItem>().Single(z => z.Id == id);

                if (item == null)
                {
                    return Json(new
                    {
                        Result = "ERROR",
                        Message = "The item for deletion does not exist!"
                    });
                }

                // Delete the object only if there are no references
                if (item.Inventories.Count < 1)
                    dm.Items.DeleteObject(item);

                // Otherwise just deactivate so we don't break any historical records
                else
                    item.Active = false;

                // Save the changes
                dm.SaveChanges();

                return Json(new { Result = "OK" });
            }
            catch (Exception e)
            {
                return Json(new { Result = "ERROR", Message = e.Message });
            }
        }
        public JsonResult DeleteItem(int id)
        {
            if (!User.Identity.IsAuthenticated)
                return JsonError("You need to log in to add modify personal items.");

            try
            {
                JourListDMContainer dm = new JourListDMContainer();
                var member = dm.Members.SingleOrDefault(z => z.Name == User.Identity.Name);

                // Grab item's inventory
                var inv = member.Inventories.SingleOrDefault(z => z.Item.Id == id);

                Item item;

                // If the inventory doesn't exist
                if (inv == null)
                {
                    // and if the item is a personal item of the user
                    if ((item = member.PersonalItems.SingleOrDefault(z => z.Id == id)) == null)
                        return JsonError("The item for deletion is not yours to delete!");

                    // If it is, and they had no inventory of it, delete the item entirely
                    else
                    {
                        foreach (var info in item.ItemInfoes)
                            dm.ItemInfoes.DeleteObject(info);

                        dm.Items.DeleteObject(item);
                    }
                }

                // If there is a current inventory of the item being deleted
                else
                {
                    // Delete the object only if there are no references on the log
                    if (inv.InventoryLogs.Count < 1)
                    {

                        // Get associated item information
                        if (inv.Item is PersonalItem)
                            foreach (var info in inv.Item.ItemInfoes)
                                dm.ItemInfoes.DeleteObject(info);

                            // Get the actual item
                            dm.Items.DeleteObject(inv.Item);

                        // Get the inventory entries
                        dm.Inventories.DeleteObject(inv);

                    }
                    // Otherwise just deactivate so we don't break any historical records
                    else
                    {
                        // Deactivate the item if it's personally owned
                        if (inv.Item is PersonalItem)
                            inv.Item.Active = false;

                        // Always deactivate the item's inventory
                        inv.Active = false;
                    }
                }

                // Save the changes
                dm.SaveChanges();

                return Json(new { Result = "OK" });
            }
            catch (Exception e)
            {
                return JsonError(e.Message);
            }
        }
        public JsonResult UpdateActivityLog(ActivityLogModel model)
        {
            JourListDMContainer dm = new JourListDMContainer();
            if (User.Identity.IsAuthenticated != true)
                return JsonError("Please log in");

            var member = dm.Members.SingleOrDefault(z => z.Name == User.Identity.Name);
            if ( member == null)
                return JsonError("You do not exist");

            var log = dm.ActivityLogs.SingleOrDefault(z => z.Id == model.LogId);
            if ( log == null )
                return JsonError("That log does not exist");

            if (log.Journal.Member != member)
                return JsonError("This log does not belong to you");

            var unit = dm.Units.SingleOrDefault(z => z.Id == model.UnitId);
            if (unit == null)
                return JsonError("A unit by that ID does not exist");
            if (unit.UnitType != log.Activity.Unit.UnitType)
                return JsonError("Your unit is not the same type as the activity's");

            log.Unit = unit;
            log.Hyperlink = model.Hyperlink;
            log.Notes = model.Notes;
            log.Quantity = model.Quantity;

            dm.SaveChanges();

            return JsonOk(model);
        }
        public JsonResult UpdateItem(ItemModel model)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return Json(new
                    {
                        Result = "ERROR",
                        Message = "Form is not valid! " +
                          "Please correct it and try again."
                    });
                }

                if (!User.Identity.IsAuthenticated)
                {
                    return Json(new
                    {
                        Result = "ERROR",
                        Message = "You need to log in to add update an item."
                    });
                }

                if (!User.IsInRole("Officer"))
                {
                    return Json(new
                    {
                        Result = "ERROR",
                        Message = "You do not have the authority to create a new inventory item."
                    });
                }

                JourListDMContainer dm = new JourListDMContainer();

                Item item = dm.Items.OfType<StandardItem>().Single(z => z.Id == model.Id);

                if (item == null)
                {
                    return Json(new
                    {
                        Result = "ERROR",
                        Message = "The item was not modified since it does not exist."
                    });
                }

                item.Description = model.Description;
                //if (model.Hyperlink != null) item.Hyperlink = model.Hyperlink;
                //if (model.Barcode != null) item.Barcode = model.Barcode;
                item.ItemCategory = dm.ItemCategories.Single(z => z.Id == model.CategoryId);
                item.UnitType = dm.UnitTypes.Single(z => z.Id == model.UnitTypeId);
                item.Active = model.Active;

                dm.SaveChanges(); dm.SaveChanges();

                return Json(new { Result = "OK" });
            }
            catch (Exception e)
            {
                return Json(new { Result = "ERROR", Message = e.Message });
            }
        }
        public JsonResult DeleteUnit(int id)
        {
            if (!User.IsInRole("Officer"))
            {
                return Json(new
                {
                    Result = "ERROR",
                    Message = "You do not have the authority to delete this unit."
                });
            }

            try
            {
                JourListDMContainer dm = new JourListDMContainer();

                // Grab the goal
                Unit u = dm.Units.Single(z => z.Id == id);

                if (u.UnitType.DefaultUnit == u)
                {
                    u.UnitType.DefaultUnit = null;
                }

                // Delete the object only if there are no references
                if (u.ActivityLogs.Count < 1 &&  u.UnitType.DefaultUnit != u && u.Inventories.Count < 1)
                    dm.Units.DeleteObject(u);

                // Otherwise just deactivate so we don't break any historical records
                else
                    u.Active = false;

                // Save the changes
                dm.SaveChanges();

                return Json(new { Result = "OK" });
            }
            catch (Exception e)
            {
                return Json(new { Result = "ERROR", Message = e.Message });
            }
        }
        protected void LoadDefaultData()
        {
            JourList.Models.JourListDMContainer dm = new Models.JourListDMContainer();
            MembershipUser muc;

            if (   dm.Members.SingleOrDefault(z => z.Name == "TeamBrett") == null
                && (muc = Membership.GetUser("TeamBrett"))                != null)
            {

                mod.Member m = new mod.Member();
                m.UserId = (Guid)muc.ProviderUserKey;
                m.Name = muc.UserName;
                dm.AddToMembers(m);
                dm.SaveChanges();
            }

            // Recurrence Intervals
            if (dm.RecurrenceIntervals.Count() == 0)
            {
                mod.RecurrenceInterval rid = new Models.RecurrenceInterval();
                rid.Description = "Daily";
                dm.AddToRecurrenceIntervals(rid);

                mod.RecurrenceInterval riw = new Models.RecurrenceInterval();
                riw.Description = "Weekly";
                dm.AddToRecurrenceIntervals(riw);

                mod.RecurrenceInterval rim = new Models.RecurrenceInterval();
                rim.Description = "Monthly";
                dm.AddToRecurrenceIntervals(rim);

                mod.RecurrenceInterval riy = new Models.RecurrenceInterval();
                riy.Description = "Yearly";
                dm.AddToRecurrenceIntervals(riy);

                mod.RecurrenceInterval rin = new Models.RecurrenceInterval();
                rin.Description = "Never";
                dm.AddToRecurrenceIntervals(rin);

                dm.SaveChanges();

            }

            // Unit Types
            if (dm.UnitTypes.Count() == 0)
            {
                string[] icDescriptions = new string[] { "Other", "Volume", "Distance", "Weight", "Time", "Temperature", "None" };

                // Can't just insert the same object with changes over and over, so we need a list of unique item categories
                List<mod.UnitType> ic = new List<mod.UnitType>(icDescriptions.Length);

                // Populate the item category descriptions with our list
                for (int i = 0; i < icDescriptions.Length; i++)
                {
                    ic.Add(new mod.UnitType());
                    ic[i].Description = icDescriptions[i];
                    dm.AddToUnitTypes(ic[i]);
                }
                dm.SaveChanges();
            }

            // Inventory Actions
            if (dm.InventoryActions.Count() == 0)
            {
                string[] icDescriptions = Enum.GetNames(typeof(mod.StockUpdateEnum)); ;

                // Can't just insert the same object with changes over and over, so we need a list of unique item categories
                List<mod.InventoryAction> ic = new List<mod.InventoryAction>(icDescriptions.Length);

                // Populate the item category descriptions with our list
                for (int i = 0; i < icDescriptions.Length; i++)
                {
                    ic.Add(new mod.InventoryAction());
                    ic[i].Description = icDescriptions[i];
                    dm.AddToInventoryActions(ic[i]);
                }
                dm.SaveChanges();
            }

            // Recurrence Interval
            if (dm.RecurrenceIntervals.Count() == 0)
            {
                string[] Descriptions = new string[] { "Minute", "Hour", "Day", "Week", "Month", "Year" };
                long[]   Minutes =      new long[]   { 1,        60,     1440,  10080,  0,       525600 };

                // Can't just insert the same object with changes over and over, so we need a list of unique item categories
                List<mod.RecurrenceInterval> ic = new List<mod.RecurrenceInterval>(Descriptions.Length);

                // Populate the item category descriptions with our list
                for (int i = 0; i < Descriptions.Length; i++)
                {
                    ic.Add(new mod.RecurrenceInterval());

                    ic[i].Description = Descriptions[i];
                    ic[i].Minutes = Minutes[i];

                    dm.AddToRecurrenceIntervals(ic[i]);
                }
                dm.SaveChanges();
            }

            // Units
            if (dm.Units.Count() == 0)
            {
                object[,] values = {
                                         {"Gram",       "gm",   1.0,           "Weight"}
                                        ,{"Pound",      "lb",   453.59237,     "Weight"}
                                        ,{"Ounces",     "oz",   28.3495231,    "Weight"}

                                        ,{"Liter",      "l" ,   1.0,           "Volume"}
                                        ,{"Fluid Once", "fl oz",0.02395735296, "Volume"}
                                        ,{"Gallon",     "gal",  3.78541178,    "Volume"}
                                        ,{"Cubic Feet", "ft3",  28.3168466,    "Volume"}
                                        ,{"Cubic Meter","m3",   1000.0,        "Volume"}
                                        ,{"Cubic Inch", "in3",  0.016387064,   "Volume"}
                                        ,{"Cubic Yards","yd3",  28.3495231,    "Volume"}
                                        ,{"Ounces",     "oz",   764.554858,    "Weight"}

                                        ,{"Mile",       "m",    1609.344,    "Distance"}
                                        ,{"Inch",       "in",   0.0254,      "Distance"}
                                        ,{"Yard",       "yd",   0.9144,      "Distance"}
                                        ,{"Foot",       "ft",   0.3048,      "Distance"}
                                        ,{"Kilometer",  "km",   1000.0,      "Distance"}
                                        ,{"Meter",      "m",    1.0,         "Distance"}
                                        ,{"Centimeter", "cm",   .01,         "Distance"}

                                        ,{"Second",     "s",    0.016666666666,  "Time"}
                                        ,{"Hour",       "h",    60.0,            "Time"}
                                        ,{"Minute",     "m",    1.0,             "Time"}
                                        ,{"Day",        "d",    1440.0,          "Time"}

                                        ,{"Celsius",    "C",    1.0,      "Temperature"}

                                        ,{"Unit",       "u",    1.0,            "Other"}
                                    };

                for (int i = 0; i < values.Length/4; i++)
                {
                    int j = 0;
                    var u = new mod.Unit();
                    u.Description = (string)values[i, j++];
                    u.Abbreviation = (string)values[i, j++];
                    u.ConversionFactor = (double)values[i, j++];
                    string utDesc = (string)values[i, j];
                    u.UnitType = dm.UnitTypes.Single(z => z.Description == utDesc);
                    dm.AddToUnits(u);
                }

                foreach (var type in dm.UnitTypes)
                    type.DefaultUnit = type.Units.FirstOrDefault(z => z.ConversionFactor == 1);

                dm.SaveChanges();
            }
            foreach (var type in dm.UnitTypes)
                type.DefaultUnit = type.Units.FirstOrDefault(z => z.ConversionFactor == 1);
            dm.SaveChanges();
            // Item Categories
            if (dm.ItemCategories.Count() == 0)
            {
                string[] icDescriptions = new string[] {"Food","Clothes","Appliances","Bath","Electronics"};

                // Can't just insert the same object with changes over and over, so we need a list of unique item categories
                List<mod.ItemCategory> ic = new List<mod.ItemCategory>(icDescriptions.Length);

                // Populate the item category descriptions with our list
                for (int i = 0; i < icDescriptions.Length; i++)
                {
                    ic.Add(new mod.ItemCategory());
                    ic[i].Description = icDescriptions[i];
                    dm.AddToItemCategories(ic[i]);
                }
                dm.SaveChanges();
            }
            dm.Dispose();
        }
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                MembershipCreateStatus createStatus;
                Membership.CreateUser(model.UserName, model.Password, model.Email, null, null, true, null, out createStatus);

                if (createStatus == MembershipCreateStatus.Success)
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */);
                    JourListDMContainer dm = new JourListDMContainer();

                    try
                    {
                        Member m = new Member();
                        m.UserId = (Guid)Membership.GetUser().ProviderUserKey;
                        m.Name = Membership.GetUser().ProviderName;
                        dm.AddToMembers(m);
                        dm.SaveChanges();
                        return RedirectToAction("Index", "Home");
                    }
                    catch (Exception)
                    {
                        Membership.DeleteUser(Membership.GetUser().ProviderName);
                        ModelState.AddModelError("", "Could not add user to JourList DB");
                    }
                }
                else
                {
                    ModelState.AddModelError("", ErrorCodeToString(createStatus));
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
        //(StockUpdateEnum action, double quantity, double size, long itemId, Unit units, double cost)
        /// <summary>
        /// Updates the inventory entry for the item
        /// Calls to update shopping list
        /// Creates a transaction log entry
        /// </summary>
        /// <param name="action">ADD/REMOVE/CURRENT</param>
        /// <param name="quantity">Count Multiplier</param>
        /// <param name="size">Size of each Item</param>
        /// <param name="itemId">ID of the item we're updating</param>
        /// <param name="units">Units of quantity coming in</param>
        /// <returns></returns>
        private InventoryLog UpdateStock(TransactionModel model)
        {
            #region Setup objects

            JourListDMContainer dm = new JourListDMContainer();
            InventoryLog log = new InventoryLog();

            var member = dm.Members.SingleOrDefault(z => z.Name == User.Identity.Name);
            if (member == null) return null;

            var inv = member.Inventories.FirstOrDefault(z => z.Id == model.InvId);
            if (inv == null) return null;

            // Update the inventory numbers
            var action = dm.InventoryActions.Single(z => z.Id == model.ActionId).Description;
            var uaction = (StockUpdateEnum)Enum.Parse(typeof(StockUpdateEnum), action);

            #endregion

            #region Update inventory values
            var units = dm.Units.Single(z => z.Id == model.UnitId);
            double size;
            try
            {
                size = Tools.Tools.ConvertUnits(model.Size, units, inv.Unit);
            }
            catch (Exception e)
            {
                throw e;
            }

            double total = size * model.Quantity;

            switch (uaction)
            {
                case StockUpdateEnum.ADD:
                    inv.OnHand += total;
                    log.Cost =  model.Cost;
                    break;
                case StockUpdateEnum.REMOVE:
                    model.Quantity *= -1;
                    inv.OnHand -= total;
                    model.Cost = 0;
                    break;
                case StockUpdateEnum.ADJUST:
                    if (inv.OnHand > total)
                    {
                        model.Quantity *= -1;
                        model.Size = -1 * (inv.OnHand - total);
                    }
                    else // if inv.onhand < total
                        model.Size = total - inv.OnHand;
                    inv.OnHand = total;
                    model.Cost = 0;
                    break;
                default:
                    break;
            }
            #endregion

            dm.SaveChanges();

            #region Make a transaction log

            // Create an inventory transaction
            log.Quantity = model.Quantity;
            log.Inventory = inv;
            log.TransactionDate = DateTime.Now;
            log.InventoryAction = dm.InventoryActions.Single(z => z.Id == model.ActionId);
            log.Size = model.Size;
            log.Quantity = model.Quantity;
            log.Unit = dm.Units.Single(z => z.Id == model.UnitId);
            log.Cost = model.Cost;
            dm.SaveChanges();

            model.TransId = log.Id;

            #endregion

            // With any inventory update, it's possible the item need to be included/excluded from the shopping list.
            UpdateShoppingList(inv);

            // Success
            return log;
        }
        private void UpdateShoppingList(Inventory inventory)
        {
            JourListDMContainer dm = new JourListDMContainer();
            var inv = dm.Inventories.Single(z=>z.Id == inventory.Id);
            bool needmore, needlist;
            // deal with shopping list if necessary
            needmore = inv.OnHand < inv.RestockThreshold;
            needlist = inv.ShoppingList == null;
            if (needmore)
            {
                if (needlist)
                {
                    // Createlist
                    ShoppingList list = new ShoppingList();

                    do { list.Id = Guid.NewGuid(); }
                    while (dm.ShoppingLists.Count(z => z.Id == list.Id) > 0);
                    dm.AddToShoppingLists(list);
                    inv.ShoppingList = list;
                }
                var log = inv.InventoryLogs.Where(z => z.UnitId == inv.Unit.Id);
                if (log.Count() > 0)
                {
                    double sze = (from a in log group a by a.Size into s orderby s.Count() descending select s).First().First().Size;
                    inv.ShoppingList.SizeNeeded = sze;
                    inv.ShoppingList.QuantityNeeded = Math.Round((inv.RequiredQuantity - inv.OnHand) / sze, MidpointRounding.AwayFromZero);
                }
                else
                {
                    inv.ShoppingList.SizeNeeded = (inv.RequiredQuantity - inv.OnHand);
                    inv.ShoppingList.QuantityNeeded = 1;
                }
            }
            else if (!needlist)
                // Remove the item from the shoppinglist
                dm.ShoppingLists.DeleteObject(dm.Inventories.First(z => z.ShoppingList.Id == inv.ShoppingList.Id).ShoppingList);

            dm.SaveChanges();
        }
        /// <summary>
        /// Add an inventory item given an item model if it doesn't exist
        /// Reactivates it if deactivated
        /// </summary>
        /// <param name="model"></param>
        /// <returns>The manipulated/created inventory entry</returns>
        private Inventory AddToInventory(ItemModel model)
        {
            JourListDMContainer dm = new JourListDMContainer();
            var member = dm.Members.SingleOrDefault(z => z.Name == User.Identity.Name);

            if (member == null) return null;

            // If inventory already exists but is inactive, reactivate
            // If it exists and is active, then just return the inventory item, do nothing
            Inventory inv;
            if ((inv = member.Inventories.FirstOrDefault(z=>z.Item.Id == model.Id)) != null)
            {
                if (inv.Active == false)
                    inv.Active = true;
                else return inv;
            }

            // Add an inventory listing if it doesn't exist.
            else
            {
                inv = new Inventory();
                inv.Item = dm.Items.Single(z=>z.Id == model.Id);
                inv.RestockThreshold = model.RestockThreshold;
                inv.OnHand = model.OnHand;
                inv.RequiredQuantity = model.RequiredQuantity;
                inv.Unit = dm.Units.Single(z => z.Id == model.UnitId);
                inv.Member = member;
                dm.AddToInventories(inv);
            }

            dm.SaveChanges();

            return inv;
        }
        public JsonResult UpdateItem(ItemModel model)
        {
            try
            {
                if (!ModelState.IsValid) return JsonError("Form is not valid! Please correct it and try again.");

                if (!User.Identity.IsAuthenticated) return JsonError("You need to log in to add modify personal items.");

                JourListDMContainer dm = new JourListDMContainer();

                Inventory inv = dm.Members.SingleOrDefault(z=>z.Name == User.Identity.Name)
                                  .Inventories.FirstOrDefault(z => z.Item.Id == model.Id);

                if (inv == null) return JsonError("The item was not modified since it does not exist in your inventory.");

                // Allow the update of fundamental properties if it's personal
                if (inv.Item is PersonalItem)
                {
                    inv.Item.Description = model.Description;
                    //if (model.Hyperlink != null) inv.Item.Hyperlink = model.Hyperlink;
                    //if (model.Barcode != null) inv.Item.Barcode = model.Barcode;
                    inv.Item.ItemCategory = dm.ItemCategories.Single(z => z.Id == model.CategoryId);
                    inv.Item.UnitType = dm.UnitTypes.Single(z => z.Id == model.UnitTypeId);
                    inv.Active = model.Active;
                }
                // Otherwise fix the model that will be resent and displayed
                else
                {
                    // TODO: Provide some message to the user that they can't update thse
                    model.Description = inv.Item.Description;
                    model.CategoryId = inv.Item.ItemCategory.Id;
                    model.UnitTypeId = inv.Item.UnitType.Id;
                    model.Active = inv.Active;
                }

                // TODO: Create unit test to ensure unit manipulation happens after we've confirmed Unit Type changes
                Unit unit = dm.Units.Single(z => z.Id == model.UnitId);

                // Ensure the new unit is of the correct type
                if (unit.UnitType.Id != inv.Unit.UnitType.Id)
                    return JsonError("The new unit must be of type " + inv.Unit.UnitType.Description + "!");

                // If the standard unit is changing, convert the stock level values.
                if (inv.Unit.Id != model.UnitId)
                {
                    try
                    {
                        inv.OnHand = Tools.Tools.ConvertUnits(inv.OnHand, inv.Unit, unit);
                        inv.RestockThreshold = Tools.Tools.ConvertUnits(inv.RestockThreshold, inv.Unit, unit);
                        inv.RequiredQuantity = Tools.Tools.ConvertUnits(inv.RequiredQuantity, inv.Unit, unit);
                    }
                    catch (Exception e)
                    {
                        return JsonError(e.Message);
                    }
                }

                // Assign converted values
                inv.RestockThreshold = model.RestockThreshold;
                inv.RequiredQuantity = model.RequiredQuantity;
                inv.Unit = unit;

                dm.SaveChanges();

                TransactionModel cm = new TransactionModel();
                cm.InvId = inv.Id;
                cm.ActionId = dm.InventoryActions.Single(z => z.Description == "ADJUST").Id;
                cm.UnitId = unit.Id;
                cm.Quantity = 1;
                cm.Size = model.OnHand;
                cm.Cost = 0;
            //                cm.IsTotalCost = true;

                if (UpdateStock(cm) == null)
                    return JsonError("Your inventory could not be updated.");

                return Json(new { Result = "OK" });
            }
            catch (Exception e)
            {
                return JsonError(e.Message);
            }
        }
        public JsonResult UpdateCart(FormCollection collection)
        {
            JourListDMContainer dm = new JourListDMContainer();

            // Get the ID of the item we're handling
            long id;
            if (!long.TryParse(collection["InvId"], out id))
                return JsonError("Malformed ID.");

            // Verify the member
            Member member = dm.Members.SingleOrDefault(z => z.Name == User.Identity.Name);
            if (!User.Identity.IsAuthenticated || member == null)
                return JsonError("You need to log in to use the shopping cart.");

            try
            {
                // Get the shopping list item
                var list = member.Inventories.SingleOrDefault(z => id == z.Id).ShoppingList;

                // Toggle the switch
                list.InCart = !list.InCart;

                dm.SaveChanges();

                return Json(new { Result = "OK" });
            }
            catch (Exception e)
            {
                return JsonError(e.Message);
            }
        }
        public JsonResult DeleteRecurrenceInterval(int id)
        {
            if (!User.IsInRole("Officer"))
            {
                return Json(new
                {
                    Result = "ERROR",
                    Message = "You do not have the authority delete this interval."
                });
            }

            try
            {
                JourListDMContainer dm = new JourListDMContainer();

                // Grab the item
                RecurrenceInterval item = dm.RecurrenceIntervals.Single(z => z.Id == id);

                // Delete the object only if there are no references
                if (item.Goals.Count < 1)
                    dm.RecurrenceIntervals.DeleteObject(item);

                // Otherwise just deactivate so we don't break any historical records
                else
                    item.Active = false;

                // Save the changes
                dm.SaveChanges();

                return Json(new { Result = "OK" });
            }
            catch (Exception e)
            {
                return Json(new { Result = "ERROR", Message = e.Message });
            }
        }
        public JsonResult DeleteTypeUnit(int id)
        {
            if (!User.IsInRole("Officer"))
            {
                return Json(new
                {
                    Result = "ERROR",
                    Message = "You do not have the authority to delete this unit type."
                });
            }

            try
            {
                JourListDMContainer dm = new JourListDMContainer();

                // Grab the unit object
                UnitType t = dm.UnitTypes.Single(z => z.Id == id);

                // Delete the object only if there are no references
                if (t.Units.Count < 1 )
                    dm.UnitTypes.DeleteObject(t);

                // Otherwise just deactivate so we don't break any historical records
                else
                    t.Active = false;

                // Save the changes
                dm.SaveChanges();

                return Json(new { Result = "OK" });
            }
            catch (Exception e)
            {
                return Json(new { Result = "ERROR", Message = e.Message });
            }
        }
        public JsonResult CreateItem(ItemModel model)
        {
            if (!ModelState.IsValid)
            {
                return Json(new
                {
                    Result = "ERROR",
                    Message = "Form is not valid! " +
                    "Please correct it and try again."
                });
            }

            if (!User.Identity.IsAuthenticated)
            {
                return Json(new
                {
                    Result = "ERROR",
                    Message = "You need to log in to add an item."
                });
            }

            if (!User.IsInRole("Officer"))
            {
                return Json(new
                {
                    Result = "ERROR",
                    Message = "You do not have the authority to create a new inventory item."
                });
            }
            try
            {
                JourListDMContainer dm = new JourListDMContainer();

                StandardItem item = new StandardItem();

                item.Description = model.Description;
                //if (model.Hyperlink != null) item.Hyperlink = model.Hyperlink;
                //if (model.Barcode != null) item.Barcode = model.Barcode;
                item.ItemCategory = dm.ItemCategories.Single(z => z.Id == model.CategoryId);
                item.UnitType = dm.UnitTypes.Single(z => z.Id == model.UnitTypeId);

                dm.AddToItems(item);
                dm.SaveChanges();

                model.Id = item.Id;

                return Json(new { Result = "OK", Record = model });
            }
            catch (Exception e)
            {
                return Json(new { Result = "ERROR", Message = e.Message });
            }
        }
        public JsonResult CreateInventoryAction(InventoryActionModel model)
        {
            if (!ModelState.IsValid)
            {
                return Json(new
                {
                    Result = "ERROR",
                    Message = "Form is not valid! " +
                    "Please correct it and try again."
                });
            }

            if (!User.IsInRole("Officer"))
            {
                return Json(new
                {
                    Result = "ERROR",
                    Message = "You do not have the authority to create a new inventory action."
                });
            }

            try
            {
                JourListDMContainer dm = new JourListDMContainer();

                InventoryAction item = new InventoryAction();
                item.Description = model.Description;
                dm.AddToInventoryActions(item);
                dm.SaveChanges();

                model.Id = item.Id;

                return Json(new { Result = "OK", Record = model });
            }
            catch (Exception e)
            {
                return Json(new { Result = "ERROR", Message = e.Message });
            }
        }
        public JsonResult CreateReccurenceInterval(RecurrenceIntervalModel model)
        {
            if (!ModelState.IsValid)
            {
                return Json(new
                {
                    Result = "ERROR",
                    Message = "Form is not valid! " +
                    "Please correct it and try again."
                });
            }

            if (!User.IsInRole("Officer"))
            {
                return Json(new
                {
                    Result = "ERROR",
                    Message = "You do not have the authority to create a new interval."
                });
            }

            try
            {
                JourListDMContainer dm = new JourListDMContainer();

                RecurrenceInterval item = new RecurrenceInterval();
                item.Description = model.Description;
                item.Minutes = model.Minutes;
                dm.AddToRecurrenceIntervals(item);
                dm.SaveChanges();

                model.Id = item.Id;

                return Json(new { Result = "OK", Record = model });
            }
            catch (Exception e)
            {
                return Json(new { Result = "ERROR", Message = e.Message });
            }
        }
        public JsonResult UpdateItemCategory(ItemCategoryModel model)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return Json(new
                    {
                        Result = "ERROR",
                        Message = "Form is not valid! " +
                          "Please correct it and try again."
                    });
                }

                if (!User.IsInRole("Officer"))
                {
                    return Json(new
                    {
                        Result = "ERROR",
                        Message = "You do not have the authority to update this item category."
                    });
                }

                JourListDMContainer dm = new JourListDMContainer();

                ItemCategory item = dm.ItemCategories.Single(z => z.Id == model.Id);
                item.Description = model.Description;
                item.Active = model.Active;
                dm.SaveChanges();

                return Json(new { Result = "OK" });
            }
            catch (Exception e)
            {
                return Json(new { Result = "ERROR", Message = e.Message });
            }
        }
        public JsonResult CreateUnit(UnitModel model)
        {
            if (!ModelState.IsValid)
            {
                return Json(new
                {
                    Result = "ERROR",
                    Message = "Form is not valid! " +
                    "Please correct it and try again."
                });
            }

            if (!User.IsInRole("Officer"))
            {
                return Json(new
                {
                    Result = "ERROR",
                    Message = "You do not have the authority to create a new unit."
                });
            }

            try
            {
                JourListDMContainer dm = new JourListDMContainer();

                Unit unit = new Unit();

                unit.UnitType = dm.UnitTypes.Single(z => z.Id == model.UnitTypeId);
                unit.Description = model.Description;
                unit.ConversionFactor = model.ConversionFactor;
                unit.Abbreviation = model.Abbreviation;

                if (model.ConversionFactor == 1)
                {
                    if (unit.UnitType.DefaultUnit != null && unit.UnitType.DefaultUnit.Active)
                        return Json(new
                        {
                            Result = "ERROR",
                            Message = "A default unit with conversion factor of 1 already exists."
                        });

                    dm.AddToUnits(unit);
                    dm.SaveChanges();

                    unit.UnitType.DefaultUnit = unit;
                }
                else
                {
                    dm.AddToUnits(unit);
                }

                dm.SaveChanges();

                model.Id = unit.Id;

                return Json(new { Result = "OK", Record = model });
            }
            catch (Exception e)
            {
                return Json(new { Result = "ERROR", Message = e.Message });
            }
        }
        public JsonResult Save(JournalModel model)
        {
            if (User.Identity.IsAuthenticated == false)
                return JsonError("You are not authenticated");
            JourListDMContainer dm = new JourListDMContainer();

            var member = dm.Members.SingleOrDefault(z => z.Name == User.Identity.Name);
            if(member == null)
                return JsonError("You are not registered in the system");

            var journal = member.Journals.SingleOrDefault(z => z.Id == model.JourId);
            if (journal == null)
                return JsonError("You can't save a journal that doesn't exist. Or at least, technically you could by creating a new one... but that should have already been done.  If it hasn't already been done then you're working outside the system.");

            journal.Weight = model.Weight;
            journal.HeartRate = model.HeartRate;
            journal.Story = model.Story;
            journal.Encrypted = model.Encrypted;

            dm.SaveChanges();
            model.JourId = journal.Id;
            return JsonOk(model);
        }
        public JsonResult CreateUnitType(UnitTypeModel model)
        {
            if (!ModelState.IsValid)
            {
                return Json(new
                {
                    Result = "ERROR",
                    Message = "Form is not valid! " +
                    "Please correct it and try again."
                });
            }

            if (!User.IsInRole("Officer"))
            {
                return Json(new
                {
                    Result = "ERROR",
                    Message = "You do not have the authority to create a new unit type."
                });
            }

            try
            {
                JourListDMContainer dm = new JourListDMContainer();

                UnitType newUnitType = new UnitType();
                newUnitType.Description = model.Description;
                dm.AddToUnitTypes(newUnitType);
                dm.SaveChanges();

                model.Id = newUnitType.Id;

                return Json(new { Result = "OK", Record = model });
            }
            catch (Exception e)
            {
                return Json(new { Result = "ERROR", Message = e.Message });
            }
        }
        public JsonResult DeleteActivity(int id)
        {
            try
            {
                JourListDMContainer dm = new JourListDMContainer();

                // Grab the goal
                Activity a = dm.Activities.Single(z => z.Id == id);

                // Delete the object only if there are no references
                if (a.ActivityLogs.Count < 1)
                    dm.Activities.DeleteObject(a);

                // Otherwise just deactivate so we don't break any historical records
                else
                    a.Active = false;

                // Save the changes
                dm.SaveChanges();

                return Json(new { Result = "OK" });
            }
            catch (Exception e)
            {
                return Json(new { Result = "ERROR", Message = e.Message });
            }
        }
        public JsonResult CreateItem(ItemModel model)
        {
            if (!ModelState.IsValid)
                return Json(new
                {
                    Result = "ERROR",
                    Message = "Form is not valid! " +
                    "Please correct it and try again."
                });

            if (!User.Identity.IsAuthenticated)
                return Json(new
                {
                    Result = "ERROR",
                    Message = "You need to log in to add personal items."
                });

            try
            {
                JourListDMContainer dm = new JourListDMContainer();
                var member = dm.Members.SingleOrDefault(z => z.Name == User.Identity.Name);

                // If the item exists but is inactive, just reactivate it.
                PersonalItem item;
                if ( (item = member.PersonalItems.SingleOrDefault(z => z.Description == model.Description)) != null)
                {
                    if (item.Active == false)
                        item.Active = true;
                    else
                        return Json(new
                        {
                            Result = "ERROR",
                            Message = "An active item by this description already exists"
                        });
                }
                // Otherwie create a new personal item
                else
                {
                    item = new PersonalItem();
                    item.Description = model.Description;
                    //if (model.Hyperlink != null) item.Hyperlink = model.Hyperlink;
                    //if (model.Barcode != null) item.Barcode = model.Barcode;
                    item.ItemCategory = dm.ItemCategories.Single(z => z.Id == model.CategoryId);
                    item.UnitType = dm.UnitTypes.Single(z => z.Id == model.UnitTypeId);
                    item.Member = member;
                    dm.AddToItems(item);
                    dm.SaveChanges();
                    // Hookup our model with the new jourId number
                    model.Id = item.Id;
                }

                Inventory inv;
                if ((inv = this.AddToInventory(model)) == null)
                    return Json(new
                    {
                        Result = "ERROR",
                        Message = "An active inventory for this item already exists"
                    });

                // Relevant inventory for jTable's purposes
            //                model.Id = item.Id;
                model.IsPersonal = item is PersonalItem;

                return Json(new { Result = "OK", Record = model });
            }
            catch (Exception e)
            {
                return Json(new { Result = "ERROR", Message = e.Message });
            }
        }