protected override void LoadForm()
        {
            try
            {
                hccProgramPlan plan = hccProgramPlan.GetById(this.PrimaryKeyIndex);

                if (plan != null)
                {
                    txtPlanName.Text = plan.Name;
                    txtPlanDesc.Text = plan.Description;

                    chkIsTaxEligible.Checked = plan.IsTaxEligible;
                    txtPricePerDay.Text      = plan.PricePerDay.ToString("f2");

                    BindddlPrograms();
                    BindddlNumDays();
                    BindddlNumWeeks();

                    ddlPrograms.SelectedIndex = ddlPrograms.Items.IndexOf(ddlPrograms.Items.FindByValue(plan.ProgramID.ToString()));
                    chkIsDefault.Checked      = plan.IsDefault;

                    ddlNumDays.SelectedIndex  = ddlNumDays.Items.IndexOf(ddlNumDays.Items.FindByValue(plan.NumDaysPerWeek.ToString()));
                    ddlNumWeeks.SelectedIndex = ddlNumWeeks.Items.IndexOf(ddlNumWeeks.Items.FindByValue(plan.NumWeeks.ToString()));
                }

                SetButtons();
            }
            catch { throw; }
        }
        protected override void SaveForm()
        {
            try
            {
                hccProgramPlan plan = hccProgramPlan.GetById(this.PrimaryKeyIndex);

                if (plan == null)
                {
                    plan = new hccProgramPlan {
                        IsActive = true
                    }
                }
                ;

                plan.Name           = txtPlanName.Text.Trim();
                plan.ProgramID      = int.Parse(ddlPrograms.SelectedValue);
                plan.IsDefault      = chkIsDefault.Checked;
                plan.Description    = txtPlanDesc.Text.Trim();
                plan.PricePerDay    = decimal.Parse(txtPricePerDay.Text.Trim());
                plan.NumDaysPerWeek = int.Parse(ddlNumDays.SelectedValue);
                plan.NumWeeks       = int.Parse(ddlNumWeeks.SelectedValue);
                plan.IsTaxEligible  = chkIsTaxEligible.Checked;
                plan.Save();

                this.OnSaved(new ControlSavedEventArgs(plan.PlanID));
            }
            catch
            {
                throw;
            }
        }
        protected override void SetButtons()
        {
            ShowDeactivate = false;

            if (this.PrimaryKeyIndex > 0)
            {
                ShowDeactivate = true;

                hccProgramPlan plan = hccProgramPlan.GetById(this.PrimaryKeyIndex);

                if (plan != null)
                {
                    if (plan.IsActive)
                    {
                        btnDeactivate.Text    = "Retire";
                        UseReactivateBehavior = false;
                    }
                    else
                    {
                        btnDeactivate.Text    = "Reactivate";
                        UseReactivateBehavior = true;
                    }
                }
            }

            btnDeactivate.Visible = ShowDeactivate;
        }
        void DisplayDailyPrice(object sender, EventArgs e)
        {
            if (ddlPlans.SelectedIndex > 0 && ddlOptions.SelectedIndex > 0)
            {
                hccProgramPlan   plan    = hccProgramPlan.GetById(int.Parse(ddlPlans.SelectedValue));
                hccProgram       program = hccProgram.GetById(int.Parse(ddlPrograms.SelectedValue));
                hccProgramOption option  = hccProgramOption.GetBy(program.ProgramID).SingleOrDefault(a => a.ProgramOptionID == int.Parse(ddlOptions.SelectedValue));

                if (plan != null && option != null)
                {
                    int     numDays    = plan.NumDaysPerWeek * plan.NumWeeks;
                    decimal dailyPrice = plan.PricePerDay + option.OptionValue;
                    decimal itemPrice  = numDays * dailyPrice;

                    lblPlanPrice.Text = string.Format("Daily Price: {0}; Total Price: {1}", dailyPrice.ToString("c"), itemPrice.ToString("c"));
                }
                else
                {
                    lblPlanPrice.Text = string.Empty;
                }
            }
            else
            {
                lblPlanPrice.Text = string.Empty;
            }
        }
        protected void ButtonRefresh_Click(object sender, EventArgs e)
        {
            hccProductionCalendar cal = hccProductionCalendar.GetBy(DateTime.Parse(txtStartDate.Text));

            if (cal != null)
            {
                cM.CurrentCalendarId = cal.CalendarID;
            }

            cM.CurrentCartItem = hccCartItem.GetById(int.Parse(ddlCustomers.SelectedItem.Value));

            if (cM.CurrentCartItem.Plan_PlanID != null)
            {
                hccProgramPlan plan    = hccProgramPlan.GetById(cM.CurrentCartItem.Plan_PlanID.Value);
                hccProgram     program = hccProgram.GetById(plan.ProgramID);

                if (plan != null && program != null)
                {
                    // load user profile data
                    hccUserProfile profile = cM.CurrentCartItem.UserProfile;
                    hccUserProfile parent  = hccUserProfile.GetParentProfileBy(profile.MembershipID);

                    lblOrderData.Text = string.Format("Order #{0}: {1}/{2}",
                                                      cM.CurrentCartItem.OrderNumber, program.Name, plan.Name);
                    lblCustData.Text = string.Format("For: {0}, {1} ({2})  Delivery Date: {3}",
                                                     parent.LastName, parent.FirstName, profile.ProfileName, txtStartDate.Text); //cM.CurrentCartItem.DeliveryDate.ToShortDateString()

                    defaultMenuSelections = hccProgramDefaultMenu.GetBy(cM.CurrentCalendarId, program.ProgramID);

                    days = cM.BindWeeklyGlance(defaultMenuSelections, plan.NumDaysPerWeek, int.Parse(ddlCustomers.SelectedValue));
                    lvCustomerMealReport.DataSource = days;
                    lvCustomerMealReport.DataBind();
                }
            }
        }
        protected void btnLoadCustomers_Click(object sender, EventArgs e)
        {
            try
            {
                ddlCustomers.Items.Clear();

                lstMCI = hccCartItem.Search_MealOrderTicketForWaaG(DateTime.Parse(txtStartDate.Text), (DateTime.Parse(txtStartDate.Text)));
                List <CustomerCalendarMenu> lstCMC = new List <CustomerCalendarMenu>();

                var cccValue = new CustomerCalendarMenu();

                var currentCustCalendarValues =
                    (from c in lstMCI
                     where c.CartItem.Plan_PlanID != null
                     orderby c.CustomerName
                     select c.CustomerName + "|" + c.CartItemId + "|" + c.OrderNumber + "|" + c.CartItem.Plan_PlanID).Distinct();

                foreach (string c in currentCustCalendarValues)
                {
                    hccProgramPlan plan = hccProgramPlan.GetById(int.Parse(c.Split('|')[3]));
                    hccProgram     prog = hccProgram.GetById(plan.ProgramID);

                    ListItem li = new ListItem(c.Split('|')[0] + " order # " + c.Split('|')[2] + " " + prog.Name, c.Split('|')[1]);
                    ddlCustomers.Items.Add(li);
                }
            }
            catch { }
        }
        protected void cstName_ServerValidate(object source, ServerValidateEventArgs args)
        {
            hccProgramPlan plan = hccProgramPlan.GetBy(txtPlanName.Text.Trim());

            if (plan != null && plan.PlanID != this.PrimaryKeyIndex)
            {
                args.IsValid = false;
            }
        }
        protected void btnRetire_Click(object sender, EventArgs e)
        {
            hccProgramPlan pref = hccProgramPlan.GetById(this.PrimaryKeyIndex);

            if (pref != null)
            {
                pref.Retire(!UseReactivateBehavior);
                SaveForm();
            }
        }
        void gvwPlansRetired_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                hccProgramPlan plan = (hccProgramPlan)e.Row.DataItem;

                if (plan != null)
                {
                    hccProgram prog = hccProgram.GetById(plan.ProgramID);

                    if (prog != null)
                    {
                        e.Row.Cells[4].Text = prog.Name;
                    }
                }
            }
        }
        void gvwPlansActive_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            try
            {
                int            menuItemId = int.Parse(e.Keys[0].ToString());
                hccProgramPlan del        = hccProgramPlan.GetById(menuItemId);

                if (del != null)
                {
                    del.Retire(true);
                    BindBothLists();
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
        void gvwPlansRetired_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            try
            {
                int            progId  = int.Parse(e.Keys[0].ToString());
                hccProgramPlan delItem = hccProgramPlan.GetById(progId);

                if (delItem != null)
                {
                    delItem.Retire(false);
                    BindBothLists();
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
        public string UpdateCarts(List <UpdateCartItem> carts)
        {
            try
            {
                UpdateCartItem     updatecart   = carts[0];
                hccCart            CurrentCart  = hccCart.GetById(updatecart.cartId);
                hccUserProfile     ownerProfile = CurrentCart.OwnerProfile;
                hccAddress         snapBillAddr = null;
                List <hccCartItem> cartItems    = null;
                bool      isAuthNet             = false;
                hccLedger ledger = null;
                string    retVal = string.Empty;

                if (CurrentCart != null && ownerProfile != null)
                {
                    hccAddress billAddr = null;
                    hccUserProfilePaymentProfile activePaymentProfile = ownerProfile.ActivePaymentProfile;

                    if (updatecart.updateStatus && CurrentCart.StatusID != updatecart.statusId)
                    {
                        CurrentCart.StatusID     = updatecart.statusId;
                        CurrentCart.ModifiedBy   = (Guid)Helpers.LoggedUser.ProviderUserKey;
                        CurrentCart.ModifiedDate = DateTime.Now;

                        if (updatecart.statusId == (int)Enums.CartStatus.Paid)
                        {
                            if (!CurrentCart.PurchaseBy.HasValue)
                            {
                                CurrentCart.PurchaseBy = (Guid)Helpers.LoggedUser.ProviderUserKey;
                            }

                            if (!CurrentCart.PurchaseDate.HasValue)
                            {
                                CurrentCart.PurchaseDate = DateTime.Now;
                            }
                        }
                        CurrentCart.Save();
                    }

                    if (updatecart.updateAddresses) // re-snap addresses
                    {
                        if (ownerProfile.BillingAddressID.HasValue)
                        {
                            billAddr = hccAddress.GetById(ownerProfile.BillingAddressID.Value);

                            if (billAddr != null)
                            {
                                snapBillAddr = new hccAddress
                                {
                                    Address1              = billAddr.Address1,
                                    Address2              = billAddr.Address2,
                                    AddressTypeID         = (int)Enums.AddressType.BillingSnap,
                                    City                  = billAddr.City,
                                    Country               = billAddr.Country,
                                    DefaultShippingTypeID = billAddr.DefaultShippingTypeID,
                                    FirstName             = billAddr.FirstName,
                                    IsBusiness            = billAddr.IsBusiness,
                                    LastName              = billAddr.LastName,
                                    Phone                 = billAddr.Phone,
                                    PostalCode            = billAddr.PostalCode,
                                    State                 = billAddr.State,
                                    ProfileName           = ownerProfile.ProfileName
                                };
                                snapBillAddr.Save();
                            }
                        }
                        else
                        {
                            retVal += "Profile has no billing address on record.";
                        }

                        if (cartItems == null)
                        {
                            cartItems = hccCartItem.GetBy(CurrentCart.CartID);
                        }

                        cartItems.ForEach(delegate(hccCartItem ci)
                        {
                            hccAddress shipAddr = null;

                            if (snapBillAddr != null)
                            {
                                ci.SnapBillAddrId = snapBillAddr.AddressID;
                            }

                            if (ci.UserProfile == null)
                            {
                                ci.UserProfileID = ownerProfile.UserProfileID;
                            }

                            if (ci.UserProfile.ShippingAddressID.HasValue)
                            {
                                shipAddr = hccAddress.GetById(ci.UserProfile.ShippingAddressID.Value);
                            }

                            if (shipAddr != null)
                            {
                                hccAddress snapShipAddr = new hccAddress
                                {
                                    Address1              = shipAddr.Address1,
                                    Address2              = shipAddr.Address2,
                                    AddressTypeID         = (int)Enums.AddressType.ShippingSnap,
                                    City                  = shipAddr.City,
                                    Country               = shipAddr.Country,
                                    DefaultShippingTypeID = shipAddr.DefaultShippingTypeID,
                                    FirstName             = shipAddr.FirstName,
                                    IsBusiness            = shipAddr.IsBusiness,
                                    LastName              = shipAddr.LastName,
                                    Phone                 = shipAddr.Phone,
                                    PostalCode            = shipAddr.PostalCode,
                                    State                 = shipAddr.State,
                                    ProfileName           = ci.UserProfile.ProfileName
                                };
                                snapShipAddr.Save();
                                ci.SnapShipAddrId = snapShipAddr.AddressID;
                            }

                            ci.Save();
                        });
                    }

                    if (updatecart.rerunAuthNet)
                    {
                        CurrentCart.StatusID     = (int)Enums.CartStatus.Unfinalized;
                        CurrentCart.PurchaseBy   = null;
                        CurrentCart.PurchaseDate = null;

                        if (ownerProfile != null)
                        {
                            AuthNetConfig ANConfig = new AuthNetConfig();

                            if (ANConfig.Settings.TestMode)
                            {
                                CurrentCart.IsTestOrder = true;
                            }

                            if (CurrentCart.PaymentDue > 0.00m)
                            {
                                try
                                {   // if total balance remains
                                    CustomerInformationManager cim = new CustomerInformationManager();

                                    if (activePaymentProfile != null)
                                    {
                                        AuthorizeNet.Order order = new AuthorizeNet.Order(ownerProfile.AuthNetProfileID,
                                                                                          activePaymentProfile.AuthNetPaymentProfileID, null);

                                        // charge CIM account with PaymentDue balance
                                        order.Amount        = CurrentCart.PaymentDue;
                                        order.InvoiceNumber = CurrentCart.PurchaseNumber.ToString();
                                        order.Description   = "Healthy Chef Creations Purchase #" + CurrentCart.PurchaseNumber.ToString();

                                        AuthorizeNet.IGatewayResponse rsp = cim.AuthorizeAndCapture(order);

                                        try
                                        {
                                            CurrentCart.AuthNetResponse = rsp.ResponseCode + "|" + rsp.Approved.ToString()
                                                                          + "|" + rsp.AuthorizationCode + "|" + rsp.InvoiceNumber + "|" + rsp.Message
                                                                          + "|" + rsp.TransactionID + "|" + rsp.Amount.ToString() + "|" + rsp.CardNumber;
                                        }
                                        catch (Exception) { }

                                        if (rsp.ResponseCode.StartsWith("1"))
                                        {
                                            CurrentCart.ModifiedBy       = (Guid)Helpers.LoggedUser.ProviderUserKey;
                                            CurrentCart.ModifiedDate     = DateTime.Now;
                                            CurrentCart.PurchaseBy       = (Guid)Helpers.LoggedUser.ProviderUserKey;
                                            CurrentCart.PurchaseDate     = DateTime.Now;
                                            CurrentCart.PaymentProfileID = activePaymentProfile.PaymentProfileID;
                                            CurrentCart.StatusID         = (int)Enums.CartStatus.Paid;

                                            isAuthNet = true;
                                        }
                                        CurrentCart.Save();
                                    }
                                    else
                                    {
                                        return("No active payment profile.");
                                    }
                                }
                                catch (Exception ex)
                                {
                                    if (ex is InvalidOperationException)
                                    {
                                        if (CurrentCart.IsTestOrder)
                                        {
                                            CurrentCart.ModifiedBy       = (Guid)Helpers.LoggedUser.ProviderUserKey;
                                            CurrentCart.ModifiedDate     = DateTime.Now;
                                            CurrentCart.PaymentProfileID = activePaymentProfile.PaymentProfileID;
                                            CurrentCart.AuthNetResponse  = ex.Message;
                                            CurrentCart.StatusID         = (int)Enums.CartStatus.Unfinalized;
                                            CurrentCart.Save();
                                        }
                                        else
                                        {
                                            BayshoreSolutions.WebModules.WebModulesAuditEvent.Raise(ex.Message, this, ex);
                                        }
                                    }
                                    else
                                    {
                                        throw;
                                    }
                                }
                            }
                            else
                            {      // no balance left to pay on order, set as paid
                                CurrentCart.AuthNetResponse = "Paid with account balance.";
                                CurrentCart.ModifiedBy      = (Guid)Helpers.LoggedUser.ProviderUserKey;
                                CurrentCart.ModifiedDate    = DateTime.Now;
                                CurrentCart.PurchaseBy      = (Guid)Helpers.LoggedUser.ProviderUserKey;
                                CurrentCart.PurchaseDate    = DateTime.Now;
                                CurrentCart.StatusID        = (int)Enums.CartStatus.Paid;
                                CurrentCart.Save();
                            }
                        }
                    }

                    if (updatecart.createLedgerEntry)
                    {
                        if (ledger == null)
                        {
                            ledger = hccLedger.GetBy(CurrentCart.CartID);
                        }

                        if (ledger == null)
                        {
                            SaveLedger(ledger, CurrentCart, ownerProfile);
                        }
                    }

                    if (updatecart.createNewSnapshot)
                    {
                        if (((Enums.CartStatus)CurrentCart.StatusID) == Enums.CartStatus.Paid)
                        {
                            if (ledger == null)
                            {
                                ledger = hccLedger.GetBy(CurrentCart.CartID);
                            }

                            if (ledger == null) // it still equals null
                            {
                                SaveLedger(ledger, CurrentCart, ownerProfile);
                            }

                            // create snapshot here
                            hccCartSnapshot snap = new hccCartSnapshot
                            {
                                CartId           = CurrentCart.CartID,
                                MembershipId     = ownerProfile.MembershipID,
                                LedgerId         = ledger.LedgerID,
                                AccountBalance   = ownerProfile.AccountBalance,
                                AuthNetProfileId = ownerProfile.AuthNetProfileID,
                                CreatedBy        = (Guid)Helpers.LoggedUser.ProviderUserKey,
                                CreatedDate      = DateTime.Now,
                                DefaultCouponId  = ownerProfile.DefaultCouponId,
                                Email            = ownerProfile.ASPUser.Email,
                                FirstName        = ownerProfile.FirstName,
                                LastName         = ownerProfile.LastName,
                                ProfileName      = ownerProfile.ProfileName
                            };

                            if (isAuthNet)
                            {
                                if (activePaymentProfile != null)
                                {
                                    snap.AuthNetPaymentProfileId = activePaymentProfile.AuthNetPaymentProfileID;
                                    snap.CardTypeId = activePaymentProfile.CardTypeID;
                                    snap.CCLast4    = activePaymentProfile.CCLast4;
                                    snap.ExpMon     = activePaymentProfile.ExpMon;
                                    snap.ExpYear    = activePaymentProfile.ExpYear;
                                    snap.NameOnCard = activePaymentProfile.NameOnCard;
                                }
                                else
                                {
                                    return("No active payment profile.");
                                }
                            }
                            else
                            {
                                snap.AuthNetPaymentProfileId = string.Empty;
                                snap.CardTypeId = 0;
                                snap.CCLast4    = string.Empty;
                                snap.ExpMon     = 0;
                                snap.ExpYear    = 0;
                                snap.NameOnCard = string.Empty;
                            }
                            snap.Save();

                            if (billAddr == null && ownerProfile.BillingAddressID.HasValue)
                            {
                                billAddr = hccAddress.GetById(ownerProfile.BillingAddressID.Value);
                            }

                            if (billAddr != null)
                            {
                                snapBillAddr = new hccAddress
                                {
                                    Address1              = billAddr.Address1,
                                    Address2              = billAddr.Address2,
                                    AddressTypeID         = billAddr.AddressTypeID,
                                    City                  = billAddr.City,
                                    Country               = billAddr.Country,
                                    DefaultShippingTypeID = billAddr.DefaultShippingTypeID,
                                    FirstName             = billAddr.FirstName,
                                    IsBusiness            = billAddr.IsBusiness,
                                    LastName              = billAddr.LastName,
                                    Phone                 = billAddr.Phone,
                                    PostalCode            = billAddr.PostalCode,
                                    State                 = billAddr.State,
                                    ProfileName           = ownerProfile.ProfileName
                                };
                                snapBillAddr.Save();
                            }
                            else
                            {
                                retVal += "Profile has no billing address on record.";
                            }

                            // copy and replace of all addresses for snapshot
                            if (cartItems == null)
                            {
                                cartItems = hccCartItem.GetBy(CurrentCart.CartID);
                            }

                            cartItems.ToList().ForEach(delegate(hccCartItem ci)
                            {
                                if (snapBillAddr != null)
                                {
                                    ci.SnapBillAddrId = snapBillAddr.AddressID;
                                }

                                hccAddress shipAddr = null;
                                if (ci.UserProfile.ShippingAddressID.HasValue)
                                {
                                    shipAddr = hccAddress.GetById(ci.UserProfile.ShippingAddressID.Value);
                                }

                                if (shipAddr != null)
                                {
                                    hccAddress snapShipAddr = new hccAddress
                                    {
                                        Address1              = shipAddr.Address1,
                                        Address2              = shipAddr.Address2,
                                        AddressTypeID         = shipAddr.AddressTypeID,
                                        City                  = shipAddr.City,
                                        Country               = shipAddr.Country,
                                        DefaultShippingTypeID = shipAddr.DefaultShippingTypeID,
                                        FirstName             = shipAddr.FirstName,
                                        IsBusiness            = shipAddr.IsBusiness,
                                        LastName              = shipAddr.LastName,
                                        Phone                 = shipAddr.Phone,
                                        PostalCode            = shipAddr.PostalCode,
                                        State                 = shipAddr.State,
                                        ProfileName           = ci.UserProfile.ProfileName
                                    };
                                    snapShipAddr.Save();
                                    ci.SnapShipAddrId = snapShipAddr.AddressID;
                                }
                                else
                                {
                                    retVal += "Profile has no billing address on record.";
                                }

                                ci.Save();
                            });
                        }
                    }

                    if (updatecart.sendCustomerEmail)
                    {
                        try
                        {
                            Email.EmailController ec = new Email.EmailController();
                            ec.SendMail_OrderConfirmationMerchant(ownerProfile.FirstName + " " + ownerProfile.LastName, CurrentCart.ToHtml(), CurrentCart.CartID);
                        }
                        catch (Exception ex)
                        { BayshoreSolutions.WebModules.WebModulesAuditEvent.Raise("Send Merchant Mail Failed", this, ex); }
                    }

                    if (updatecart.sendMerchantEmail)
                    {
                        try
                        {
                            Email.EmailController ec = new Email.EmailController();
                            ec.SendMail_OrderConfirmationCustomer(ownerProfile.ASPUser.Email, ownerProfile.FirstName + " " + ownerProfile.LastName, CurrentCart.ToHtml());
                        }
                        catch (Exception ex)
                        { BayshoreSolutions.WebModules.WebModulesAuditEvent.Raise("Send customer Mail Failed", this, ex); }
                    }

                    if (updatecart.repairCartCals)
                    {
                        if (cartItems == null)
                        {
                            cartItems = hccCartItem.GetBy(CurrentCart.CartID);
                        }
                        // wrap in programs

                        cartItems.ForEach(delegate(hccCartItem ci)
                        {
                            if (ci.ItemType == Enums.CartItemType.DefinedPlan)
                            {
                                hccProgramPlan cp = hccProgramPlan.GetById(ci.Plan_PlanID.Value);

                                if (cp != null)
                                {
                                    for (int i = 0; i < cp.NumWeeks; i++)
                                    {
                                        hccProductionCalendar cal;
                                        cal = hccProductionCalendar.GetBy(ci.DeliveryDate.AddDays(7 * i));

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

                    if (updatecart.reCalcItemTax)
                    {
                        try
                        {
                            if (cartItems == null)
                            {
                                cartItems = hccCartItem.GetBy(CurrentCart.CartID);
                            }

                            List <ProfileCart> CurrentProfileCarts = new List <ProfileCart>();

                            if (cartItems.Count > 0)
                            {
                                hccUserProfile parentProfile = hccUserProfile.GetParentProfileBy(CurrentCart.AspNetUserID.Value);
                                //List<hccProductionCalendar> pc = new List<hccProductionCalendar>();

                                foreach (hccCartItem cartItem in cartItems)
                                {
                                    ProfileCart profCart;
                                    int         shippingAddressId;

                                    //if (!pc.Exists(a => a.DeliveryDate == cartItem.DeliveryDate))
                                    //    pc.Add(hccProductionCalendar.GetBy(cartItem.DeliveryDate));

                                    //hccProductionCalendar cpc = pc.SingleOrDefault(a => a.DeliveryDate == cartItem.DeliveryDate);

                                    //if (cpc != null && (cpc.OrderCutOffDate.AddDays(1) >= DateTime.Now || (HttpContext.Current.Request.Url.OriginalString.Contains("Admin"))))
                                    //{
                                    if (cartItem.UserProfile != null && (cartItem.UserProfile.UseParentShipping || cartItem.UserProfile.ShippingAddressID.HasValue))
                                    {
                                        if (cartItem.UserProfile.UseParentShipping)
                                        {
                                            shippingAddressId = parentProfile.ShippingAddressID.Value;
                                        }
                                        else
                                        {
                                            shippingAddressId = cartItem.UserProfile.ShippingAddressID.Value;
                                        }

                                        profCart = CurrentProfileCarts
                                                   .SingleOrDefault(a => a.ShippingAddressId == shippingAddressId && a.DeliveryDate == cartItem.DeliveryDate);
                                    }
                                    else
                                    {
                                        profCart = CurrentProfileCarts
                                                   .SingleOrDefault(a => a.ShippingAddressId == 0 &&
                                                                    a.DeliveryDate == cartItem.DeliveryDate);

                                        shippingAddressId = 0;
                                    }

                                    if (profCart == null)
                                    {
                                        profCart = new ProfileCart(shippingAddressId, cartItem.DeliveryDate);
                                        CurrentProfileCarts.Add(profCart);
                                    }

                                    profCart.CartItems.Add(cartItem);
                                    //}
                                    //else
                                    //{
                                    //    //cartItem.Delete();
                                    //    //lblFeedbackCart.Text = "Item(s) removed from cart due to expiration of availability.";

                                    //}
                                }
                            }

                            //// display totals
                            CurrentCart.CalculateTotals(CurrentProfileCarts);
                        }
                        catch (Exception ex)
                        { BayshoreSolutions.WebModules.WebModulesAuditEvent.Raise("Attempt to recalculate taz for cart items failed.", this, ex); }
                    }
                }
                return("Cart Updated: " + DateTime.Now);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        protected override void LoadForm()
        {
            try
            {
                hccProductionCalendar cal = null;

                if (Request.QueryString["dd"] != null && !string.IsNullOrEmpty(Request.QueryString["dd"]))
                {
                    DateTime _delDate = DateTime.ParseExact(Request.QueryString["dd"].ToString(), "M/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture);
                    cal = hccProductionCalendar.GetBy(_delDate);
                    //cal = hccProductionCalendar.GetBy(DateTime.Parse(Request.QueryString["dd"].ToString()));

                    if (cal != null)
                    {
                        CurrentCalendarId = cal.CalendarID;
                    }

                    lkbBack.PostBackUrl += "?cal=" + cal.CalendarID.ToString();
                }

                hccProgramPlan plan    = hccProgramPlan.GetById(CurrentCartItem.Plan_PlanID.Value);
                hccProgram     program = hccProgram.GetById(plan.ProgramID);
                if (plan != null && program != null)
                {
                    CurrentProgramId = program.ProgramID;
                    CurrentNumOfDays = plan.NumDaysPerWeek;

                    // load user profile data
                    hccUserProfile profile = CurrentCartItem.UserProfile;
                    hccUserProfile parent  = hccUserProfile.GetParentProfileBy(profile.MembershipID);

                    lblCustomerName.Text = parent.FirstName + " " + parent.LastName;
                    lblProfileName.Text  = profile.ProfileName;
                    lblProgram.Text      = program.Name;
                    lblPlan.Text         = plan.Name;
                    lblPlanOption.Text   = hccProgramOption.GetById(CurrentCartItem.Plan_ProgramOptionID.Value).OptionText;
                    lblOrderNumber.Text  = CurrentCartItem.OrderNumber;
                    lblQuantity.Text     = CurrentCartItem.Quantity.ToString();
                    lblDeliveryDate.Text = cal.DeliveryDate.ToShortDateString();

                    hccCartItemCalendar cartCal = hccCartItemCalendar.GetBy(CurrentCartItem.CartItemID, cal.CalendarID);

                    if (cartCal != null)
                    {
                        chkIsComplete.Checked = cartCal.IsFulfilled;
                    }

                    chkIsCancelledDisplay.Checked = CurrentCartItem.IsCancelled;

                    lvwAllrgs.DataSource = profile.GetAllergens();
                    lvwAllrgs.DataBind();
                    ProfileNotesEdit_AllergenNote.CurrentUserProfileId = profile.UserProfileID;
                    ProfileNotesEdit_AllergenNote.Bind();

                    lvwPrefs.DataSource = profile.GetPreferences();
                    lvwPrefs.DataBind();
                    ProfileNotesEdit_PreferenceNote.CurrentUserProfileId = profile.UserProfileID;
                    ProfileNotesEdit_PreferenceNote.Bind();

                    defaultMenuSelections = hccProgramDefaultMenu.GetBy(CurrentCalendarId, CurrentProgramId);

                    days = BindWeeklyGlance(defaultMenuSelections, CurrentNumOfDays);

                    BindDdlDays(days);

                    BindForm();
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
        //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);

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