//public string GetProgramImage(string programName)
        //{
        //    var fileName = "/userfiles/images/programs/" + programName.Replace(" ", "-") + ".jpg";

        //    if (!File.Exists(Server.MapPath(fileName)))
        //        return "";

        //    return "<img width='150' height='126' alt='' src='/userfiles/images/programs/" + programName.Replace(" ", "-") + ".jpg' class='left' />";
        //}

        protected void btn_add_to_cart_Click(object sender, EventArgs e)
        {
            try
            {
                Page.Validate("AddToCartGroup");

                if (Page.IsValid)
                {
                    hccCart userCart = hccCart.GetCurrentCart();

                    //Define form variables
                    int itemId   = Convert.ToInt32(Request.Form["plan_type"]);
                    int optionId = ((Request.Form["plan_option"] == null) ? 0 : Convert.ToInt32(Request.Form["plan_option"]));

                    //Select chosen Program Plan
                    hccProgramPlan plan = hccProgramPlan.GetById(itemId);
                    if (plan == null)
                    {
                        throw new Exception("ProgramPlan not found: " + itemId.ToString());
                    }

                    hccProgram       prog   = hccProgram.GetById(plan.ProgramID);
                    hccProgramOption option = hccProgramOption.GetBy(plan.ProgramID).Where(a => a.ProgramOptionID == optionId).SingleOrDefault();

                    int      numDays      = plan.NumDaysPerWeek * plan.NumWeeks;
                    int      numMeals     = numDays * plan.MealsPerDay;
                    decimal  dailyPrice   = plan.PricePerDay + option.OptionValue;
                    decimal  itemPrice    = numDays * dailyPrice;
                    DateTime deliveryDate = DateTime.Parse(ddl_delivery_date.SelectedValue);

                    MembershipUser user = Helpers.LoggedUser;

                    hccCartItem newItem = new hccCartItem
                    {
                        CartID        = userCart.CartID,
                        CreatedBy     = (user == null ? Guid.Empty : (Guid)user.ProviderUserKey),
                        CreatedDate   = DateTime.Now,
                        IsTaxable     = plan.IsTaxEligible,
                        ItemDesc      = plan.Description,
                        NumberOfMeals = numMeals,
                        //ItemName = string.Format("{0} - {1} - {2} - {3} & {4}", (prog == null ? string.Empty : prog.Name), plan.Name, option.OptionText, deliveryDate.ToShortDateString(), numMeals),
                        ItemName             = string.Format("{0} - {1} - {2} - {3}", (prog == null ? string.Empty : prog.Name), plan.Name, option.OptionText, deliveryDate.ToShortDateString()),
                        ItemPrice            = itemPrice,
                        ItemTypeID           = (int)Enums.CartItemType.DefinedPlan,
                        Plan_IsAutoRenew     = false, //chx_renew.Checked,
                        Plan_PlanID          = itemId,
                        Plan_ProgramOptionID = optionId,
                        DeliveryDate         = deliveryDate,
                        Quantity             = int.Parse(txt_quantity.Text),
                        UserProfileID        = ((ddlProfiles.Items.Count == 0) ? 0 : Convert.ToInt32(ddlProfiles.SelectedValue)),
                        IsCompleted          = false
                    };
                    Meals obj = new Meals();
                    obj.CartID    = newItem.CartID;
                    obj.MealCount = newItem.NumberOfMeals;
                    obj.NoOfWeeks = plan.NumWeeks;

                    var ID    = obj.CartID;
                    var Meal  = obj.MealCount;
                    var Weeks = obj.NoOfWeeks;

                    HealthyChef.Templates.HealthyChef.Controls.TopHeader header =
                        (HealthyChef.Templates.HealthyChef.Controls.TopHeader) this.Page.Master.FindControl("TopHeader1");
                    if (header != null)
                    {
                        header.MealsCountVal(ID, Meal);
                    }

                    newItem.GetOrderNumber(userCart);
                    int profileId = 0;
                    if (divProfiles.Visible)
                    {
                        profileId = int.Parse(ddlProfiles.SelectedValue);
                    }
                    else
                    {
                        if (CartUserASPNetId != Guid.Empty)
                        {
                            profileId = hccUserProfile.GetParentProfileBy(CartUserASPNetId).UserProfileID;
                        }
                    }

                    if (profileId > 0)
                    {
                        newItem.UserProfileID = profileId;
                    }

                    hccCartItem existItem = hccCartItem.GetBy(userCart.CartID, newItem.ItemName, profileId);

                    if (existItem == null)
                    {
                        newItem.Save();

                        hccProductionCalendar cal;

                        for (int i = 0; i < plan.NumWeeks; i++)
                        {
                            cal = hccProductionCalendar.GetBy(newItem.DeliveryDate.AddDays(7 * i));

                            if (cal != null)
                            {
                                hccCartItemCalendar cartCal = new hccCartItemCalendar {
                                    CalendarID = cal.CalendarID, CartItemID = newItem.CartItemID
                                };
                                cartCal.Save();
                            }
                            else
                            {
                                BayshoreSolutions.WebModules.WebModulesAuditEvent.Raise(
                                    "No production calendar found for Delivery Date: " + newItem.DeliveryDate.AddDays(7 * i).ToShortDateString(), this);
                            }
                        }
                    }
                    else
                    {
                        existItem.AdjustQuantity(existItem.Quantity + newItem.Quantity);
                    }

                    //Recurring Order Record
                    if (cbxRecurring.Checked)
                    {
                        List <hccRecurringOrder> lstRo = null;
                        if (Session["autorenew"] != null)
                        {
                            lstRo = ((List <hccRecurringOrder>)Session["autorenew"]);
                        }
                        else
                        {
                            lstRo = new List <hccRecurringOrder>();
                        }

                        //var filter = cartItemsRecurring.Where(ci => ci.ItemType == Enums.CartItemType.DefinedPlan);

                        //for(var i = 0; i < int.Parse(txt_quantity.Text); i++)
                        //{
                        lstRo.Add(new hccRecurringOrder
                        {
                            CartID         = userCart.CartID,
                            CartItemID     = newItem.CartItemID,
                            UserProfileID  = newItem.UserProfileID,
                            AspNetUserID   = userCart.AspNetUserID,
                            PurchaseNumber = userCart.PurchaseNumber,
                            TotalAmount    = newItem.ItemPrice
                        });
                        Session["autorenew"] = lstRo;
                        //}
                    }

                    HealthyChef.Templates.HealthyChef.Controls.TopHeader header1 =
                        (HealthyChef.Templates.HealthyChef.Controls.TopHeader) this.Page.Master.FindControl("TopHeader1");

                    if (header1 != null)
                    {
                        header.SetCartCount();
                    }

                    //Redirect user to Program Selection screen
                    Response.Redirect("~/meal-programs.aspx");
                    //multi_programs.ActiveViewIndex = 0;
                    //litMessage.Text = "Your Meal Program has been added to your cart.";
                }
                else
                {
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        protected override void SaveForm()
        {
            try
            {
                hccCart        userCart      = hccCart.GetById(this.PrimaryKeyIndex);
                MembershipUser user          = Membership.GetUser(userCart.AspNetUserID);
                bool           isFamilyStyle = false;

                if (user != null)
                {
                    hccMenuItem menuItem = hccMenuItem.GetById(int.Parse(ddlMenuItems.SelectedValue));
                    var         itemSize = (Enums.CartItemSize)(int.Parse(ddlOptions.SelectedValue));
                    if (chkFamilyStyle.Checked)
                    {
                        isFamilyStyle = true;
                    }
                    int profileId = 0;
                    if (divProfiles.Visible)
                    {
                        profileId = int.Parse(ddlProfiles.SelectedValue);
                    }
                    else
                    {
                        profileId = hccUserProfile.GetParentProfileBy(userCart.AspNetUserID.Value).UserProfileID;
                    }

                    if (userCart != null)
                    {
                        hccCartItem cartItem = new hccCartItem
                        {
                            CreatedBy         = (Guid)Helpers.LoggedUser.ProviderUserKey,
                            CreatedDate       = DateTime.Now,
                            IsTaxable         = menuItem.IsTaxEligible,
                            ItemDesc          = menuItem.Description,
                            ItemPrice         = hccMenuItem.GetItemPriceBySize(menuItem, (int)itemSize),
                            ItemTypeID        = (int)Enums.CartItemType.AlaCarte,
                            DeliveryDate      = DateTime.Parse(ddlDeliveryDates.SelectedItem.Text),
                            Meal_MealSizeID   = (int)itemSize,
                            Meal_MenuItemID   = menuItem.MenuItemID,
                            Meal_ShippingCost = hccDeliverySetting.GetBy(menuItem.MealType).ShipCost,
                            UserProfileID     = profileId,
                            Quantity          = int.Parse(txtQuantity.Text.Trim()),
                            Plan_IsAutoRenew  = isFamilyStyle,
                            IsCompleted       = false
                        };

                        cartItem.GetOrderNumber(userCart);

                        List <hccCartItemMealPreference> prefsList = new List <hccCartItemMealPreference>();

                        foreach (ListItem item in cblPreferences.Items)
                        {
                            if (item.Selected)
                            {
                                hccCartItemMealPreference pref =
                                    new hccCartItemMealPreference {
                                    CartItemID = cartItem.CartItemID, PreferenceID = int.Parse(item.Value)
                                };
                                prefsList.Add(pref);
                            }
                        }

                        var prefsString = string.Empty;

                        if (prefsList.Count > 0)
                        {
                            prefsString = prefsList
                                          .Select(a => hccPreference.GetById(a.PreferenceID))
                                          .Select(a => a.Name).DefaultIfEmpty(string.Empty).Aggregate((a, b) => a + ", " + b);
                        }

                        cartItem.ItemName = hccCartItem.BuildCartItemName(menuItem.MealType, itemSize, menuItem.Name, GetMealSides(menuItem.MealType), prefsString, cartItem.DeliveryDate);//,cartItem.Quantity

                        hccCartItem existItem = hccCartItem.GetBy(userCart.CartID, cartItem.ItemName, profileId);

                        if (existItem == null)
                        {
                            cartItem.CartID = userCart.CartID;
                            cartItem.Save();

                            if (cartItem.CartItemID > 0)
                            {
                                prefsList.ForEach(delegate(hccCartItemMealPreference cartPref)
                                {
                                    cartPref.CartItemID = cartItem.CartItemID;
                                    cartPref.Save();
                                });
                            }

                            AddUpdateCartALCMenuItem(cartItem);
                            OnSaved(new ControlSavedEventArgs(cartItem.CartItemID));
                            chkFamilyStyle.Checked = false;
                        }
                        else
                        {
                            existItem.Quantity += cartItem.Quantity;
                            if (existItem.AdjustQuantity(existItem.Quantity))
                            {
                                AddUpdateCartALCMenuItem(existItem);
                                OnSaved(new ControlSavedEventArgs(existItem.CartItemID));
                                chkFamilyStyle.Checked = false;
                            }
                        }
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
        protected void txtQuantity_TextChanged(object sender, EventArgs e)
        {
            Page.Validate("QuantityGroup");

            if (Page.IsValid)
            {
                TextBox txtQuantity = (TextBox)sender;
                //CheckBox chk = (CheckBox)sender;
                if (txtQuantity != null)
                {
                    int newQty            = int.Parse(txtQuantity.Text);
                    ListViewDataItem item = (ListViewDataItem)txtQuantity.Parent;

                    int         cartItemId = int.Parse(lvwCartItems.DataKeys[item.DataItemIndex].Value.ToString());
                    hccCartItem cartItem   = hccCartItem.GetById(cartItemId);

                    if (cartItem != null)
                    {
                        if (cartItem.ItemTypeID == 2)
                        {
                            if (newQty > 0)
                            {
                                List <hccCartItem> cartItems = hccCartItem.GetWithoutSideItemsBy(cartItem.CartID);

                                if (cartItem.AdjustQuantity(newQty))
                                {
                                    #region recurringitems adjust
                                    // If the adjusted cart item is a recurring item(s),
                                    // check the quantity of the cartitemId in the Session
                                    // Recurring order object, if greater than new quantity,
                                    // adjust the recurring values accordingly.
                                    //if (Session["autorenew"] != null)
                                    //{
                                    //    var lstRo = ((List<hccRecurringOrder>)Session["autorenew"]);
                                    //    while (lstRo.Count(x => x.CartItemID == cartItemId) > newQty)
                                    //    {
                                    //        lstRo.Remove(lstRo.Find(x => x.CartItemID == cartItemId));
                                    //    }
                                    //}
                                    #endregion

                                    OnCartItemListItemUpdated();
                                }
                            }
                            else
                            {
                                cartItem.Delete(((List <hccRecurringOrder>)Session["autorenew"]));
                                OnCartItemListItemUpdated();
                            }
                        }
                        else
                        {
                            if (newQty == 1)
                            {
                                cartItem.AdjustQuantity(newQty);
                                hccCartItem hcccartItem = new hccCartItem();
                                hcccartItem.RemoveFamilyStyle(cartItemId);
                                OnCartItemListItemUpdated();
                            }
                            else
                            {
                                cartItem.AdjustQuantity(newQty);
                                OnCartItemListItemUpdated();
                            }
                        }
                    }
                }
            }
        }
        protected void btnAddToCartClick(object sender, EventArgs e)
        {
            bool itemAdded = false;

            try
            {
                Button           btnAddToCart = (Button)sender;
                ListViewDataItem dataItem     = (ListViewDataItem)btnAddToCart.Parent;
                int            menuItemId     = int.Parse(lvwMealItems.DataKeys[dataItem.DataItemIndex].Value.ToString());
                hccMenuItem    menuItem       = hccMenuItem.GetById(menuItemId);
                hccCart        userCart       = hccCart.GetCurrentCart();
                MembershipUser user           = Helpers.LoggedUser;
                int            profileId      = GetProfileId(dataItem);
                int            sizeId         = GetSizeId(btnAddToCart);

                hccCartItem newItem = new hccCartItem
                {
                    CartID            = userCart.CartID,
                    CreatedBy         = (user == null ? Guid.Empty : (Guid)user.ProviderUserKey),
                    CreatedDate       = DateTime.Now,
                    IsTaxable         = menuItem.IsTaxEligible,
                    ItemDesc          = menuItem.Description,
                    ItemPrice         = hccMenuItem.GetItemPriceBySize(menuItem, sizeId),
                    ItemTypeID        = (int)Enums.CartItemType.AlaCarte,
                    DeliveryDate      = CurrentDeliveryDate,
                    Meal_MenuItemID   = menuItem.MenuItemID,
                    Meal_MealSizeID   = sizeId,
                    Meal_ShippingCost = hccDeliverySetting.GetBy(menuItem.MealType).ShipCost,
                    UserProfileID     = profileId,
                    Quantity          = GetQuantity(dataItem),
                    IsCompleted       = false
                };

                newItem.GetOrderNumber(userCart);

                List <CheckBox>     prefChks = new List <CheckBox>();
                List <RepeaterItem> rptPrefs = dataItem.FindControl("rptMealPrefs").Controls.OfType <RepeaterItem>().ToList();
                rptPrefs.ForEach(delegate(RepeaterItem ri) { prefChks.AddRange(ri.Controls.OfType <CheckBox>().Where(a => a.Checked)); });
                string prefsString = string.Empty;
                List <hccCartItemMealPreference> cartPrefs = new List <hccCartItemMealPreference>();

                foreach (CheckBox chkPref in prefChks)
                {
                    int           prefId = int.Parse(chkPref.Attributes["value"]);
                    hccPreference pref   = hccPreference.GetById(prefId);

                    if (pref != null)
                    {
                        if (string.IsNullOrWhiteSpace(prefsString))
                        {
                            prefsString += pref.Name;
                        }
                        else
                        {
                            prefsString += ", " + pref.Name;
                        }

                        cartPrefs.Add(new hccCartItemMealPreference {
                            CartItemID = newItem.CartItemID, PreferenceID = prefId
                        });
                    }
                }

                //newItem.ItemName = hccCartItem.BuildCartItemName(menuItem.MealType, (Enums.CartItemSize)sizeId, menuItem.Name, GetMealSides(dataItem), prefsString, newItem.DeliveryDate, newItem.Quantity);
                newItem.ItemName = hccCartItem.BuildCartItemName(menuItem.MealType, (Enums.CartItemSize)sizeId, menuItem.Name, GetMealSides(dataItem), prefsString, newItem.DeliveryDate);//, newItem.Quantity

                hccCartItem existItem = hccCartItem.GetBy(userCart.CartID, newItem.ItemName, profileId);

                if (existItem == null)
                {
                    newItem.Save();
                    cartPrefs.ForEach(delegate(hccCartItemMealPreference cartPref) { cartPref.CartItemID = newItem.CartItemID; cartPref.Save(); });
                }
                else
                {
                    existItem.Quantity += newItem.Quantity;
                    existItem.AdjustQuantity(existItem.Quantity);
                }

                AddCartALCMenuItem(dataItem, existItem ?? newItem, menuItem.MealTypeID);

                itemAdded = true;
            }
            catch (Exception ex)
            {
                throw ex;
            }

            if (itemAdded)
            {
                HealthyChef.Templates.HealthyChef.Controls.TopHeader header =
                    (HealthyChef.Templates.HealthyChef.Controls.TopHeader) this.Page.Master.FindControl("TopHeader1");

                if (header != null)
                {
                    header.SetCartCount();
                }
            }
        }
        protected override void SaveForm()
        {
            try
            {
                hccCart        userCart = hccCart.GetById(this.PrimaryKeyIndex);
                MembershipUser user     = Membership.GetUser(userCart.AspNetUserID);

                if (user != null)
                {
                    hccProgramPlan selPlan = hccProgramPlan.GetById(int.Parse(ddlPlans.SelectedValue));

                    if (selPlan != null)
                    {
                        List <hccProgramOption> progOptions = hccProgramOption.GetBy(selPlan.ProgramID);
                        hccProgramOption        option      = progOptions.Where(a => a.ProgramOptionID == (int.Parse(ddlOptions.SelectedValue))).SingleOrDefault();
                        hccProgram prog = hccProgram.GetById(selPlan.ProgramID);

                        int     numDays    = selPlan.NumDaysPerWeek * selPlan.NumWeeks;
                        decimal dailyPrice = selPlan.PricePerDay + option.OptionValue;
                        decimal itemPrice  = numDays * dailyPrice;
                        int     profileId  = 0;
                        //bool autoRenew = chkAutoRenew.Checked;
                        string   itemFullName = string.Empty;
                        DateTime startDate    = DateTime.Parse(ddlStartDates.SelectedItem.Text);

                        itemFullName = string.Format("{0} - {1} - {2} - {3}",
                                                     prog == null ? string.Empty : prog.Name, selPlan.Name, option.OptionText, startDate.ToShortDateString());

                        if (divProfiles.Visible)
                        {
                            profileId = int.Parse(ddlProfiles.SelectedValue);
                        }
                        else
                        {
                            profileId = hccUserProfile.GetParentProfileBy(userCart.AspNetUserID.Value).UserProfileID;
                        }

                        if (userCart != null && selPlan != null)
                        {
                            int         currentQty = int.Parse(txtQuantity.Text.Trim());
                            hccCartItem existItem  = hccCartItem.GetBy(userCart.CartID, itemFullName, profileId);

                            if (existItem == null)
                            {
                                hccCartItem planItem = new hccCartItem
                                {
                                    CartID               = userCart.CartID,
                                    CreatedBy            = (Guid)Membership.GetUser().ProviderUserKey,
                                    CreatedDate          = DateTime.Now,
                                    IsTaxable            = selPlan.IsTaxEligible,
                                    ItemDesc             = selPlan.Description,
                                    ItemName             = itemFullName,
                                    ItemPrice            = itemPrice,
                                    ItemTypeID           = (int)Enums.CartItemType.DefinedPlan,
                                    Plan_IsAutoRenew     = false, //autoRenew,
                                    Plan_PlanID          = selPlan.PlanID,
                                    Plan_ProgramOptionID = option.ProgramOptionID,
                                    DeliveryDate         = startDate,
                                    UserProfileID        = profileId,
                                    Quantity             = currentQty,
                                    IsCompleted          = false
                                };

                                planItem.GetOrderNumber(userCart);
                                planItem.Save();

                                hccProductionCalendar cal;

                                for (int i = 0; i < selPlan.NumWeeks; i++)
                                {
                                    cal = hccProductionCalendar.GetBy(planItem.DeliveryDate.AddDays(7 * i));

                                    if (cal != null)
                                    {
                                        hccCartItemCalendar cartCal = new hccCartItemCalendar {
                                            CalendarID = cal.CalendarID, CartItemID = planItem.CartItemID, IsFulfilled = false
                                        };
                                        cartCal.Save();
                                    }
                                    else
                                    {
                                        BayshoreSolutions.WebModules.WebModulesAuditEvent.Raise(
                                            "No production calendar found for Delivery Date: " + planItem.DeliveryDate.AddDays(7 * i).ToShortDateString(), this);
                                    }
                                }


                                if (cbxRecurring.Checked)
                                {
                                    var cartItemsRecurring = hccCartItem.GetBy(userCart.CartID);
                                    var filter             = cartItemsRecurring.Where(ci => ci.ItemType == Enums.CartItemType.DefinedPlan);
                                    var roItem             = new hccRecurringOrder();
                                    roItem.CartID         = planItem.CartID;
                                    roItem.CartItemID     = planItem.CartItemID;
                                    roItem.UserProfileID  = planItem.UserProfileID;
                                    roItem.AspNetUserID   = userCart.AspNetUserID;
                                    roItem.PurchaseNumber = userCart.PurchaseNumber;
                                    roItem.TotalAmount    = Math.Round(Convert.ToDecimal(Convert.ToDouble(planItem.ItemPrice) - Convert.ToDouble(planItem.ItemPrice) * 0.05), 2);
                                    roItem.Save();
                                    if (planItem != null)

                                    {
                                        planItem.Plan_IsAutoRenew = true;
                                        planItem.Save();
                                    }

                                    //foreach (var recurringOrder in filter.Select(item => new hccRecurringOrder
                                    //{
                                    //    CartID = item.CartID,
                                    //    CartItemID = item.CartItemID,
                                    //    UserProfileID = item.UserProfileID,
                                    //    AspNetUserID = userCart.AspNetUserID,
                                    //    PurchaseNumber = userCart.PurchaseNumber,
                                    //    TotalAmount = userCart.TotalAmount
                                    //}))
                                    //{
                                    //    recurringOrder.Save();
                                    //}
                                }
                                OnSaved(new ControlSavedEventArgs(planItem.CartItemID));
                                cbxRecurring.Checked = false;
                            }
                            else
                            {
                                if (existItem.AdjustQuantity(existItem.Quantity + currentQty))
                                {
                                    OnSaved(new ControlSavedEventArgs(existItem.CartItemID));
                                }
                                cbxRecurring.Checked = false;
                            }
                        }
                    }
                }
                //Page.Response.Redirect(Page.Request.Url.ToString()+ "#tabs9", true);
            }
            catch (Exception)
            {
                throw;
            }
        }