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;
            }
        }
//-------------------------------------------------------------------------------------------
    private void PlaceOrder()
    {
        if (Page.IsValid)
        {
            using (WeavverEntityContainer data = new WeavverEntityContainer())
            {
                Communication_MessageTemplates orderPlacedTemplate = (from x in data.Communication_MessageTemplates
                                                                      where x.Id == new Guid("f6df7db7-5efb-475d-8e32-3dd7e293ce3b")
                                                                      select x).First();
                string msgBody         = orderPlacedTemplate.Body.Replace("{cart}", ShoppingCart.ToString());
                string placedat        = DateTime.Now.ToString("MM/dd/yy"); // (ShoppingCart.CreatedAt.HasValue) ? ShoppingCart.CreatedAt.Value.ToString("MM/dd/yy") : "unknown";
                string orderee         = PrimaryContact.FirstName.Text + " " + PrimaryContact.LastName.Text;
                string mPrimaryAddress = PrimaryContact.AddressLine1.Text + "\r\n" + PrimaryContact.AddressLine2.Text;
                string mBillingAddress = BillingContact.AddressLine1.Text + "\r\n" + BillingContact.AddressLine2.Text;
                msgBody = msgBody.Replace("{name}", orderee);
                msgBody = msgBody.Replace("{placed}", placedat);
                string primarycontact = "Name: " + orderee + "\r\n";
                primarycontact += "Organization: " + PrimaryContact.Organization.Text + "\r\n";
                primarycontact += "Address: " + mPrimaryAddress.Trim() + "\r\n";
                primarycontact += "Zip Code: " + PrimaryContact.ZipCode.Text;
                msgBody         = msgBody.Replace("{primary_contact}", primarycontact.Trim());
                string billingcontact = "Name: " + BillingContact.FirstName.Text + " " + BillingContact.LastName.Text + "\r\n";
                billingcontact += "Organization: " + BillingContact.Organization.Text + "\r\n";
                billingcontact += "Address: " + mBillingAddress.Trim() + "\r\n";
                billingcontact += "Zip Code: " + BillingContact.ZipCode.Text;
                msgBody         = msgBody.Replace("{billing_contact}", billingcontact.Trim());

                Logistics_Addresses primaryAddress = new Logistics_Addresses();
                primaryAddress.OrganizationId = SelectedOrganization.Id;
                primaryAddress.Id             = Guid.NewGuid();
                primaryAddress.Name           = "Primary Address";
                primaryAddress.Line1          = PrimaryContact.AddressLine1.Text;
                primaryAddress.Line2          = PrimaryContact.AddressLine2.Text;
                primaryAddress.City           = "";
                primaryAddress.State          = "";
                primaryAddress.ZipCode        = PrimaryContact.ZipCode.Text;
                data.Logistics_Addresses.AddObject(primaryAddress);

                //   DatabaseHelper.Link(newOrder, primaryAddress);
                // newOrder.PrimaryAddress = primaryAddress;

                Logistics_Addresses billingAddress = new Logistics_Addresses();
                billingAddress.OrganizationId = SelectedOrganization.Id;
                billingAddress.Id             = Guid.NewGuid();
                billingAddress.Name           = "Billing Address";
                billingAddress.Line1          = BillingContact.AddressLine1.Text;
                billingAddress.Line2          = BillingContact.AddressLine2.Text;
                billingAddress.City           = "";
                billingAddress.State          = "";
                billingAddress.ZipCode        = BillingContact.ZipCode.Text;
                data.Logistics_Addresses.AddObject(billingAddress);

                //   DatabaseHelper.Link(newOrder, billingAddress);
                //   newOrder.BillingAddress = billingAddress;

                Sales_Orders newOrder = new Sales_Orders();
                newOrder.Id             = Guid.NewGuid();
                newOrder.OrganizationId = SelectedOrganization.Id;
                if (LoggedInUser != null)
                {
                    newOrder.Orderee = LoggedInUser.OrganizationId;
                }
                newOrder.Cart   = msgBody;
                newOrder.Status = "Placed";
                newOrder.Total  = ShoppingCart.Total;
                newOrder.PrimaryContactEmail        = PrimaryContact.EmailAddress.Text;
                newOrder.PrimaryContactNameFirst    = PrimaryContact.FirstName.Text;
                newOrder.PrimaryContactNameLast     = PrimaryContact.LastName.Text;
                newOrder.PrimaryContactOrganization = PrimaryContact.Organization.Text;
                newOrder.PrimaryContactPhoneNum     = PrimaryContact.PhoneNumber.Text;
                newOrder.PrimaryContactPhoneExt     = PrimaryContact.PhoneExtension.Text;
                newOrder.PrimaryContactAddress      = primaryAddress.Id;
                newOrder.BillingContactEmail        = BillingContact.EmailAddress.Text;
                newOrder.BillingContactNameFirst    = BillingContact.FirstName.Text;
                newOrder.BillingContactNameLast     = BillingContact.LastName.Text;
                newOrder.BillingContactOrganization = BillingContact.Organization.Text;
                newOrder.BillingContactPhoneNum     = BillingContact.PhoneNumber.Text;
                newOrder.BillingContactPhoneExt     = BillingContact.PhoneExtension.Text;
                newOrder.BillingContactAddress      = billingAddress.Id;
                newOrder.Notes = SpecialInstructions.Text;
                data.Sales_Orders.AddObject(newOrder);

                Accounting_CreditCards card = new Accounting_CreditCards();
                card.Id              = Guid.NewGuid();
                card.OrganizationId  = SelectedOrganization.Id;
                card.Number          = PaymentMethod1.CardNumber.Text;
                card.SecurityCode    = PaymentMethod1.SecCode.Text;
                card.ExpirationMonth = Int32.Parse(PaymentMethod1.ExpMonth.SelectedValue);
                card.ExpirationYear  = Int32.Parse(PaymentMethod1.ExpYear.SelectedValue);
                data.Accounting_CreditCards.AddObject(card);
                //   DatabaseHelper.Link(newOrder, card);

                foreach (Sales_ShoppingCartItems item in ShoppingCart.Items)
                {
                    item.SessionId = null;
                    item.OrderId   = newOrder.Id;
                    data.Sales_ShoppingCartItems.Attach(item);

                    if (item.Monthly > 0m && item.Quantity > 0)
                    {
                        // Set up the ARB process
                        Accounting_RecurringBillables rBillable = new Accounting_RecurringBillables();
                        rBillable.Id               = Guid.NewGuid();
                        rBillable.OrganizationId   = SelectedOrganization.Id;
                        rBillable.Service          = item.Id;
                        rBillable.BillingDirection = "Pre-Bill";
                        rBillable.BillingPeriod    = BillingPeriodType.Monthly.ToString();
                        rBillable.Memo             = item.Name + ", %timespan%\r\n" + item.Notes;
                        rBillable.StartAt          = DateTime.UtcNow;
                        rBillable.Status           = RecurringBillableStatus.Enabled.ToString();
                        rBillable.Position         = DateTime.UtcNow.AddMonths(1);
                        rBillable.AccountFrom      = LoggedInUser.OrganizationId;
                        rBillable.AccountTo        = SelectedOrganization.Id;
                        rBillable.Amount           = item.Monthly;
                        data.Accounting_RecurringBillables.AddObject(rBillable);
                        //DatabaseHelper.Link(newOrder, rBillable);
                    }
                    for (int i = 0; i < item.Quantity; i++)
                    {
                        // Insert the initial ledger items
                        Accounting_LedgerItems ledgerItemDebit = new Accounting_LedgerItems();
                        ledgerItemDebit.OrganizationId = SelectedOrganization.Id;
                        ledgerItemDebit.Id             = Guid.NewGuid();
                        ledgerItemDebit.TransactionId  = newOrder.Id;
                        ledgerItemDebit.PostAt         = DateTime.UtcNow;
                        ledgerItemDebit.AccountId      = newOrder.Id;
                        ledgerItemDebit.LedgerType     = LedgerType.Receivable.ToString();
                        ledgerItemDebit.Code           = CodeType.Sale.ToString();
                        ledgerItemDebit.Memo           = item.Name + "\r\n" + item.Notes;
                        ledgerItemDebit.Amount         = Math.Abs(item.UnitCost) * -1.0m;
                        data.Accounting_LedgerItems.AddObject(ledgerItemDebit);

                        // It is unnecessary to link these since we provide a link to the Receivable ledger.
                        //// DatabaseHelper.Link(newOrder, ledgerItemDebit);
                    }
                }

                AuthorizeNet.IGatewayResponse resp = card.Bill(data, newOrder, primaryAddress, billingAddress);
                if (resp.Approved)
                {
                    // Accounting.ProcessCommision(newOrder, SelectedOrganization.ReferredBy);

                    if (LoggedInUser != null && !LoggedInUser.Activated)
                    {
                        data.System_Users.Attach(LoggedInUser);
                        LoggedInUser.Activated = true;
                    }
                    data.SaveChanges();
                    ShoppingCart.Items.Clear();

                    // Send receipt
                    MailMessage msg = new MailMessage("Weavver Sales <*****@*****.**>", PrimaryContact.EmailAddress.Text);
                    msg.Subject = orderPlacedTemplate.Subject;
                    msg.Body    = msgBody;
                    SmtpClient sClient = new SmtpClient(ConfigurationManager.AppSettings["smtp_server"]);
                    try
                    {
                        sClient.Send(msg);

                        var type  = typeof(IOrderEvents);
                        var types = AppDomain.CurrentDomain.GetAssemblies().ToList()
                                    .Where(y => y.FullName.Contains("WeavverExtension"))
                                    .SelectMany(s => s.GetTypes())
                                    .Where(p => type.IsAssignableFrom(p) && p.IsClass);

                        foreach (var interfacedClassType in types)
                        {
                            foreach (Sales_ShoppingCartItems purchasedItem in ShoppingCart.Items)
                            {
                                if (purchasedItem.Quantity > 0)
                                {
                                    object o           = Activator.CreateInstance(interfacedClassType);
                                    var    orderEvents = o as IOrderEvents;
                                    orderEvents.Provision(newOrder, purchasedItem);
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Weavver.Utilities.ErrorHandling.LogError(Request, "/workflows/sales_orderplace", ex);
                        ShowError("Your order was placed but a receipt could not be sent due to a system error. Please contact customer service for further assistance.");
                        return;
                    }

                    Response.Redirect("~/CMS_Pages/Details.aspx?id=071c0768-84ed-4770-9519-a98806a87c68&OrderId=" + newOrder.Id.ToString());
                }
                else
                {
                    ShowError("Your card did not go through because '" + resp.Message + "'. Please check the card number and try again.");
                    return;
                }
            }
        }
    }