private void LoadOrder(CheckoutViewModel model)
        {
            Order result = SessionManager.CurrentShoppingCart(MTApp.OrderServices, MTApp.CurrentStore);
            if (result == null) Response.Redirect("~/cart");           
            model.CurrentOrder = result;

            if (result.Items.Count == 0)
            {
                Response.Redirect("~/cart");
            }

            // Email
            model.IsLoggedIn = false;
            if (SessionManager.IsUserAuthenticated(this.MTApp))
            {
                model.IsLoggedIn = true;
                model.CurrentCustomer = MTApp.CurrentCustomer;
                if (model.CurrentCustomer != null)
                {
                    model.CurrentOrder.UserEmail = model.CurrentCustomer.Email;
                }
                
                // Copy customer addresses to order
                model.CurrentCustomer.ShippingAddress.CopyTo(model.CurrentOrder.ShippingAddress);                
                if (model.BillShipSame == false)
                {
                    Address billAddr = model.CurrentCustomer.BillingAddress;
                    billAddr.CopyTo(model.CurrentOrder.BillingAddress);
                }                                
            }  
            
            // Payment
            DisplayPaymentMethods(model);
        }
        private void DisplayPaypalExpressMode(CheckoutViewModel model)
        {
            model.PayPalToken = Request.QueryString["token"] ?? string.Empty;
            model.PayPalPayerId = Request.QueryString["payerId"] ?? string.Empty;
            
            if (string.IsNullOrEmpty(model.PayPalToken)) Response.Redirect("~/cart");

            
                PayPalAPI ppAPI = MerchantTribe.Commerce.Utilities.PaypalExpressUtilities.GetPaypalAPI(this.MTApp.CurrentStore);
                bool failed = false;
                GetExpressCheckoutDetailsResponseType ppResponse = null;
                try
                {
                        if (!GetExpressCheckoutDetails(ppAPI, ref ppResponse, model))
                        {
                            failed = true;
                            EventLog.LogEvent("Paypal Express Checkout", "GetExpressCheckoutDetails call failed. Detailed Errors will follow. ", EventLogSeverity.Error);
                            foreach (ErrorType ppError in ppResponse.Errors)
                            {
                                EventLog.LogEvent("Paypal error number: " + ppError.ErrorCode, "Paypal Error: '" + ppError.ShortMessage + "' Message: '" + ppError.LongMessage + "' " + " Values passed to GetExpressCheckoutDetails: Token: " + model.PayPalToken, EventLogSeverity.Error);
                            }
                            this.FlashFailure("An error occurred during the Paypal Express checkout. No charges have been made. Please try again.");
                            ViewBag.HideCheckout = true;
                        }
                }
                finally
                {
                    Order o = model.CurrentOrder;
                    ViewBag.HideEditButton = false;
                    if (o.CustomProperties["PaypalAddressOverride"] != null)
                    {
                        if (o.CustomProperties["PaypalAddressOverride"].Value == "1")
                        {
                            ViewBag.HideEditButton = true;
                        }
                    }

                    o.CustomProperties.Add("bvsoftware", "PayerID", Request.QueryString["PayerID"]);
                    if (!failed)
                    {
                        if (ppResponse != null && ppResponse.GetExpressCheckoutDetailsResponseDetails != null && ppResponse.GetExpressCheckoutDetailsResponseDetails.PayerInfo != null)
                        {
                            o.UserEmail = ppResponse.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Payer;
                            if (string.IsNullOrEmpty(o.ShippingAddress.Phone))
                            {
                                o.ShippingAddress.Phone = ppResponse.GetExpressCheckoutDetailsResponseDetails.ContactPhone ?? string.Empty;
                            }
                        }
                    }
                    MTApp.OrderServices.Orders.Update(o);
                    ppAPI = null;
                }                        
        }
        private CheckoutViewModel IndexSetup()
        {
            ViewBag.Title = "Checkout";
            ViewBag.BodyClass = "store-checkout-page";

            CheckoutViewModel model = new CheckoutViewModel();
            LoadOrder(model);
            CheckForPoints(model);

            // Buttons
            ThemeManager themes = MTApp.ThemeManager();
            model.ButtonCheckoutUrl = themes.ButtonUrl("PlaceOrder", Request.IsSecureConnection);
            model.ButtonLoginUrl = MTApp.ThemeManager().ButtonUrl("Login", Request.IsSecureConnection);

            // Labels
            model.LabelRewardPoints = MTApp.CurrentStore.Settings.RewardsPointsName;

            // Agree Checkbox
            if (MTApp.CurrentStore.Settings.ForceTermsAgreement)
            {
                model.ShowAgreeToTerms = true;
                model.AgreedToTerms = false;
                model.AgreedToTermsDescription = SiteTerms.GetTerm(SiteTermIds.TermsAndConditionsAgreement);
                model.LabelTerms = SiteTerms.GetTerm(SiteTermIds.TermsAndConditions);                                
            }
            else
            {
                model.ShowAgreeToTerms = false;
                model.AgreedToTerms = true;
            }

            // Populate Countries
            model.Countries = MTApp.CurrentStore.Settings.FindActiveCountries();
            model.PaymentViewModel.AcceptedCardTypes = MTApp.CurrentStore.Settings.PaymentAcceptedCards;
            
            ViewData["AnalyticsTop"] += "<script type=\"text/javascript\" src=\"" + Url.Content("~/js/checkout.js") + "\" ></script>";

            // Render Side Column
            var columnRender = new code.TemplateEngine.TagHandlers.ContentColumn();
            model.SideColumn = columnRender.RenderColumnToString("601", MTApp, ViewBag);

            return model;
        }
        private CheckoutViewModel IndexSetup()
        {
            ViewBag.Title = "Checkout";
            ViewBag.BodyClass = "store-checkout-page";

            CheckoutViewModel model = new CheckoutViewModel();
            model.CurrentOrder = SessionManager.CurrentShoppingCart(MTApp.OrderServices, MTApp.CurrentStore);

            // Buttons
            ThemeManager themes = MTApp.ThemeManager();
            model.ButtonCheckoutUrl = themes.ButtonUrl("PlaceOrder", Request.IsSecureConnection);            
            model.ButtonCancelUrl = themes.ButtonUrl("keepshopping", Request.IsSecureConnection);
            model.ButtonLoginUrl = themes.ButtonUrl("edit", Request.IsSecureConnection);

            // Agree Checkbox
            if (MTApp.CurrentStore.Settings.ForceTermsAgreement)
            {
                model.ShowAgreeToTerms = true;
                model.AgreedToTerms = false;
                model.AgreedToTermsDescription = SiteTerms.GetTerm(SiteTermIds.TermsAndConditionsAgreement);
                model.LabelTerms = SiteTerms.GetTerm(SiteTermIds.TermsAndConditions);
            }
            else
            {
                model.ShowAgreeToTerms = false;
                model.AgreedToTerms = true;
            }

            // Populate Countries
            model.Countries = MTApp.CurrentStore.Settings.FindActiveCountries();

            // Side Column
            var columnRender = new code.TemplateEngine.TagHandlers.ContentColumn();
            model.SideColumn = columnRender.RenderColumnToString("601", MTApp, ViewBag);

            return model;
        }        
        private void LoadValuesFromForm(CheckoutViewModel model)
        {
            // Email
            model.CurrentOrder.UserEmail = Request.Form["customeremail"];

            // Addresses
            model.BillShipSame = (Request.Form["chkbillsame"] != null);

            LoadAddressFromForm("shipping", model.CurrentOrder.ShippingAddress);
            if (model.BillShipSame)
            {
                model.CurrentOrder.ShippingAddress.CopyTo(model.CurrentOrder.BillingAddress);
            }
            else
            {
                LoadAddressFromForm("billing", model.CurrentOrder.BillingAddress);
            }
            // Save addresses to customer account
            if (model.IsLoggedIn)
            {

                model.CurrentOrder.ShippingAddress.CopyTo(model.CurrentOrder.ShippingAddress);
                if (model.BillShipSame == false)
                {
                    model.CurrentOrder.BillingAddress.CopyTo(model.CurrentCustomer.BillingAddress);
                }
                MTApp.MembershipServices.Customers.Update(model.CurrentCustomer);
            }

            //Shipping
            string shippingRateKey = Request.Form["shippingrate"];
            MTApp.OrderServices.OrdersRequestShippingMethodByUniqueKey(shippingRateKey, model.CurrentOrder, MTApp.CurrentStore);

            // Save Values so far in case of later errors
            MTApp.CalculateOrder(model.CurrentOrder);

            // Save Payment Information
            model.UseRewardsPoints = Request.Form["userewardspoints"] == "1";
            ApplyRewardsPoints(model);

            // Payment Methods
            LoadPaymentFromForm(model);
            SavePaymentSelections(model);

            // Instructions
            model.CurrentOrder.Instructions = Request.Form["specialinstructions"];

            // Agree to Terms
            var agreedValue = Request.Form["agreed"];
            if (!String.IsNullOrEmpty(agreedValue))
            {
                model.AgreedToTerms = true;
            }

            // Save all the changes to the order
            MTApp.OrderServices.Orders.Update(model.CurrentOrder);
            SessionManager.SaveOrderCookies(model.CurrentOrder, MTApp.CurrentStore);
        }
 private void LoadPaymentFromForm(CheckoutViewModel model)
 {
     model.PaymentViewModel.SelectedPayment = Request.Form["paymethod"] ?? string.Empty;
     model.PaymentViewModel.DataPurchaseOrderNumber = Request.Form["purchaseorder"] ?? string.Empty;
     model.PaymentViewModel.DataCompanyAccountNumber = Request.Form["companyaccount"] ?? string.Empty;
     model.PaymentViewModel.DataCreditCard.CardHolderName = Request.Form["cccardholder"] ?? string.Empty;
     model.PaymentViewModel.DataCreditCard.CardNumber = MerchantTribe.Payment.CardValidator.CleanCardNumber(Request.Form["cccardnumber"] ?? string.Empty);
     int expMonth = -1;
     int.TryParse(Request.Form["ccexpmonth"] ?? string.Empty, out expMonth);
     model.PaymentViewModel.DataCreditCard.ExpirationMonth = expMonth;
     int expYear = -1;
     int.TryParse(Request.Form["ccexpyear"] ?? string.Empty, out expYear);
     model.PaymentViewModel.DataCreditCard.ExpirationYear = expYear;
     model.PaymentViewModel.DataCreditCard.SecurityCode = Request.Form["ccsecuritycode"] ?? string.Empty;
 }
        private List<MerchantTribe.Web.Validation.RuleViolation> ValidatePayment(CheckoutViewModel model)
        {
            List<MerchantTribe.Web.Validation.RuleViolation> violations = new List<MerchantTribe.Web.Validation.RuleViolation>();

            // Nothing to validate if no payment is needed
            if (model.PaymentViewModel.NoPaymentNeeded)
            {
                return violations;
            }

            if (model.PaymentViewModel.SelectedPayment == "creditcard")
            {
                return ValidateCreditCard(model);
            }
            if (model.PaymentViewModel.SelectedPayment == "check")
            {
                return violations;
            }
            if (model.PaymentViewModel.SelectedPayment == "telephone")
            {
                return violations;
            }
            if (model.PaymentViewModel.SelectedPayment == "purchaseorder")
            {
                ValidationHelper.Required("Purchase Order Number", model.PaymentViewModel.DataPurchaseOrderNumber.Trim(), violations, "purchaseorder");
                return violations;
            }
            if (model.PaymentViewModel.SelectedPayment == "companyaccount")
            {
                ValidationHelper.Required("Company Account Number", model.PaymentViewModel.DataCompanyAccountNumber.Trim(), violations, "companyaccount");
                return violations;
            }
            if (model.PaymentViewModel.SelectedPayment == "cod")
            {
                return violations;
            }
            if (model.PaymentViewModel.SelectedPayment == "paypal")
            {
                return violations;
            }

            // We haven't return anything so nothing is selected.
            // Try CC as default payment method
            if (model.PaymentViewModel.DataCreditCard.CardNumber.Length > 12)
            {
                model.PaymentViewModel.SelectedPayment = "creditcard";
                return ValidateCreditCard(model);
            }

            // nothing selected, trial of cc failed
            violations.Add(new RuleViolation("Payment Method", "", "Please select a payment method", ""));

            return violations;
        }
        private List<RuleViolation> ValidateCreditCard(CheckoutViewModel model)
        {
            List<RuleViolation> violations = new List<RuleViolation>();

            if ((!MerchantTribe.Payment.CardValidator.IsCardNumberValid(model.PaymentViewModel.DataCreditCard.CardNumber)))
            {
                violations.Add(new RuleViolation("Credit Card Number", "", "Please enter a valid credit card number", "cccardnumber"));
            }
            MerchantTribe.Payment.CardType cardTypeCheck = MerchantTribe.Payment.CardValidator.GetCardTypeFromNumber(model.PaymentViewModel.DataCreditCard.CardNumber);
            List<CardType> acceptedCards = MTApp.CurrentStore.Settings.PaymentAcceptedCards;
            if (!acceptedCards.Contains(cardTypeCheck))
            {
                violations.Add(new RuleViolation("Card Type Not Accepted", "", "That card type is not accepted by this store. Please use a different card.", "cccardnumber"));
            }

            ValidationHelper.RequiredMinimum(1, "Card Expiration Year", model.PaymentViewModel.DataCreditCard.ExpirationYear, violations, "ccexpyear");
            ValidationHelper.RequiredMinimum(1, "Card Expiration Month", model.PaymentViewModel.DataCreditCard.ExpirationMonth, violations, "ccexpmonth");
            ValidationHelper.Required("Name on Card", model.PaymentViewModel.DataCreditCard.CardHolderName, violations, "cccardholder");

            if (MTApp.CurrentStore.Settings.PaymentCreditCardRequireCVV == true)
            {
                ValidationHelper.RequiredMinimum(3, "Card Security Code", model.PaymentViewModel.DataCreditCard.SecurityCode.Length, violations, "ccsecuritycode");
            }

            return violations;
        }
        private void SavePaymentSelections(CheckoutViewModel model)
        {
            OrderPaymentManager payManager = new OrderPaymentManager(model.CurrentOrder, MTApp);
            payManager.ClearAllNonStoreCreditTransactions();

            bool found = false;

            if (model.PaymentViewModel.SelectedPayment == "creditcard")
            {
                found = true;
                payManager.CreditCardAddInfo(model.PaymentViewModel.DataCreditCard, model.CurrentOrder.TotalGrandAfterStoreCredits(MTApp.OrderServices));
            }

            if ((found == false) && (model.PaymentViewModel.SelectedPayment == "check"))
            {
                found = true;
                payManager.OfflinePaymentAddInfo(model.CurrentOrder.TotalGrandAfterStoreCredits(MTApp.OrderServices), "Customer will pay by check.");
            }

            if ((found == false) && (model.PaymentViewModel.SelectedPayment == "telephone"))
            {
                found = true;
                payManager.OfflinePaymentAddInfo(model.CurrentOrder.TotalGrandAfterStoreCredits(MTApp.OrderServices), "Customer will call with payment info.");
            }

            if ((found == false) && (model.PaymentViewModel.SelectedPayment == "purchaseorder"))
            {
                found = true;
                payManager.PurchaseOrderAddInfo(model.PaymentViewModel.DataPurchaseOrderNumber.Trim(), model.CurrentOrder.TotalGrandAfterStoreCredits(MTApp.OrderServices));
            }
            if ((found == false) && (model.PaymentViewModel.SelectedPayment == "companyaccount"))
            {
                found = true;
                payManager.CompanyAccountAddInfo(model.PaymentViewModel.DataCompanyAccountNumber.Trim(), model.CurrentOrder.TotalGrandAfterStoreCredits(MTApp.OrderServices));
            }

            if ((found == false) && (model.PaymentViewModel.SelectedPayment == "cod"))
            {
                found = true;
                payManager.OfflinePaymentAddInfo(model.CurrentOrder.TotalGrandAfterStoreCredits(MTApp.OrderServices), "Customer will pay cash on delivery.");
            }

            if ((found == false) && (model.PaymentViewModel.SelectedPayment == "paypal"))
            {
                found = true;
                // Need token and id before we can add this to the order
                // Handled on the checkout page.
                //payManager.PayPalExpressAddInfo(o.TotalGrand);
            }
        }
        private void ProcessPaymentErrorOrder(CheckoutViewModel model)
        {
            // Save as Order
            OrderTaskContext c = new OrderTaskContext(MTApp);
            c.UserId = MTApp.CurrentCustomerId;
            c.Order = model.CurrentOrder;

            if (Workflow.RunByName(c, WorkflowNames.ProcessNewOrderPayments) == true)
            {
                // Clear Pending Cart ID because payment is good
                SessionManager.SetCurrentPaymentPendingCartId(MTApp.CurrentStore, string.Empty);

                // Process Post Payment Stuff
                MerchantTribe.Commerce.BusinessRules.Workflow.RunByName(c, MerchantTribe.Commerce.BusinessRules.WorkflowNames.ProcessNewOrderAfterPayments);
                Order tempOrder = MTApp.OrderServices.Orders.FindForCurrentStore(model.CurrentOrder.bvin);
                MTApp.CurrentRequestContext.IntegrationEvents.OrderReceived(tempOrder, MTApp);
                Response.Redirect("~/checkout/receipt?id=" + model.CurrentOrder.bvin);
            }
        }
        private void SavePaymentInfo(CheckoutViewModel model)
        {
            OrderPaymentManager payManager = new OrderPaymentManager(model.CurrentOrder, MTApp);
            payManager.ClearAllTransactions();

            string token = model.PayPalToken;
            string payerId = model.PayPalPayerId;
            if (!string.IsNullOrEmpty(payerId))
            {
                // This is to fix a bug with paypal returning multiple payerId's
                payerId = payerId.Split(',')[0];
            }

            payManager.PayPalExpressAddInfo(model.CurrentOrder.TotalGrand, token, payerId);
        }
 private void LoadShippingMethodsForOrder(CheckoutViewModel model)
 {
     Order o = model.CurrentOrder;
     o.ShippingAddress.CopyTo(o.BillingAddress);
     MTApp.CalculateOrderAndSave(o);
     SessionManager.SaveOrderCookies(o, MTApp.CurrentStore);
     LoadShippingMethodsForOrder(o);
 }
        private bool GetExpressCheckoutDetails(PayPalAPI ppAPI, ref GetExpressCheckoutDetailsResponseType ppResponse, CheckoutViewModel model)
        {
            ppResponse = ppAPI.GetExpressCheckoutDetails(Request.QueryString["token"]);
            if (ppResponse.Ack == AckCodeType.Success || ppResponse.Ack == AckCodeType.SuccessWithWarning)
            {
                model.CurrentOrder.UserEmail = ppResponse.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Payer;
                model.CurrentOrder.ShippingAddress.FirstName = ppResponse.GetExpressCheckoutDetailsResponseDetails.PayerInfo.PayerName.FirstName ?? string.Empty;
                if (ppResponse.GetExpressCheckoutDetailsResponseDetails.PayerInfo.PayerName.MiddleName.Length > 0)
                {
                    model.CurrentOrder.ShippingAddress.MiddleInitial = ppResponse.GetExpressCheckoutDetailsResponseDetails.PayerInfo.PayerName.MiddleName.Substring(0, 1);
                }
                else
                {
                    model.CurrentOrder.ShippingAddress.MiddleInitial = string.Empty;
                }
                model.CurrentOrder.ShippingAddress.LastName = ppResponse.GetExpressCheckoutDetailsResponseDetails.PayerInfo.PayerName.LastName ?? string.Empty;
                model.CurrentOrder.ShippingAddress.Company = ppResponse.GetExpressCheckoutDetailsResponseDetails.PayerInfo.PayerBusiness ?? string.Empty;
                model.CurrentOrder.ShippingAddress.Line1 = ppResponse.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.Street1 ?? string.Empty;
                model.CurrentOrder.ShippingAddress.Line2 = ppResponse.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.Street2 ?? string.Empty;
                model.CurrentOrder.ShippingAddress.CountryData.Name = ppResponse.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.CountryName ?? string.Empty;
                model.CurrentOrder.ShippingAddress.CountryData.Bvin = ppResponse.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.Country.ToString();
                model.CurrentOrder.ShippingAddress.City = ppResponse.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.CityName ?? string.Empty;
                model.CurrentOrder.ShippingAddress.RegionData.Name = ppResponse.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.StateOrProvince ?? string.Empty;
                model.CurrentOrder.ShippingAddress.RegionData.Abbreviation =
                    model.CurrentOrder.ShippingAddress.RegionData.Name ?? string.Empty;
                model.CurrentOrder.ShippingAddress.PostalCode = ppResponse.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.PostalCode ?? string.Empty;
                model.CurrentOrder.ShippingAddress.Phone = ppResponse.GetExpressCheckoutDetailsResponseDetails.PayerInfo.ContactPhone ?? string.Empty;

                if (ppResponse.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.AddressStatus == AddressStatusCodeType.Confirmed)
                {
                    ViewBag.AddressStatus = "Confirmed";
                }
                else
                {
                    ViewBag.AddressStatus = "Unconfirmed";
                }
                return true;
            }
            else
            {
                return false;
            }
        }
        private CheckoutViewModel PaymentErrorSetup()
        {
            ViewBag.Title = "Checkout Payment Error";
            ViewBag.BodyClass = "store-checkout-page";

            CheckoutViewModel model = new CheckoutViewModel();
            LoadPendingOrder(model);

            // Buttons
            ThemeManager themes = MTApp.ThemeManager();
            model.ButtonCheckoutUrl = themes.ButtonUrl("PlaceOrder", Request.IsSecureConnection);
            model.ButtonCancelUrl = themes.ButtonUrl("Cancel", Request.IsSecureConnection);

            // Populate Countries
            model.Countries = MTApp.CurrentStore.Settings.FindActiveCountries();
            model.PaymentViewModel.AcceptedCardTypes = MTApp.CurrentStore.Settings.PaymentAcceptedCards;

            return model;
        }
        private CheckoutViewModel IndexSetup()
        {
            ViewBag.Title = "Checkout";
            ViewBag.BodyClass = "store-checkout-page";

            CheckoutViewModel model = new CheckoutViewModel();
            LoadOrder(model);
            CheckForPoints(model);

            // Buttons
            ThemeManager themes = MTApp.ThemeManager();
            model.ButtonCheckoutUrl = themes.ButtonUrl("PlaceOrder", Request.IsSecureConnection);
            model.ButtonLoginUrl = MTApp.ThemeManager().ButtonUrl("Login", Request.IsSecureConnection);

            // Labels
            model.LabelRewardPoints = MTApp.CurrentStore.Settings.RewardsPointsName;

            // Agree Checkbox
            if (MTApp.CurrentStore.Settings.ForceTermsAgreement)
            {
                model.ShowAgreeToTerms = true;
                model.AgreedToTerms = false;
                model.AgreedToTermsDescription = SiteTerms.GetTerm(SiteTermIds.TermsAndConditionsAgreement);
                model.LabelTerms = SiteTerms.GetTerm(SiteTermIds.TermsAndConditions);
            }
            else
            {
                model.ShowAgreeToTerms = false;
                model.AgreedToTerms = true;
            }

            // Populate Countries
            model.Countries = MTApp.CurrentStore.Settings.FindActiveCountries();
            model.PaymentViewModel.AcceptedCardTypes = MTApp.CurrentStore.Settings.PaymentAcceptedCards;

            return model;
        }
        private CheckoutViewModel PaymentErrorSetup()
        {
            ViewBag.Title = "Checkout Payment Error";
            ViewBag.BodyClass = "store-checkout-page";

            CheckoutViewModel model = new CheckoutViewModel();
            LoadPendingOrder(model);

            // Buttons
            ThemeManager themes = MTApp.ThemeManager();
            model.ButtonCheckoutUrl = themes.ButtonUrl("PlaceOrder", Request.IsSecureConnection);
            model.ButtonCancelUrl = themes.ButtonUrl("Cancel", Request.IsSecureConnection);

            // Populate Countries
            model.Countries = MTApp.CurrentStore.Settings.FindActiveCountries();
            model.PaymentViewModel.AcceptedCardTypes = MTApp.CurrentStore.Settings.PaymentAcceptedCards;

            ViewData["PassedAnalyticsTop"] += "<script type=\"text/javascript\" src=\"" + Url.Content("~/js/checkout.js") + "\" ></script>";
            return model;
        }
        private void ProcessOrder(CheckoutViewModel model)
        {
            // Save as Order
            OrderTaskContext c = new OrderTaskContext(MTApp);
            c.UserId = MTApp.CurrentCustomerId;
            c.Order = model.CurrentOrder;

            // Check for PayPal Request
            bool paypalCheckoutSelected = model.PaymentViewModel.SelectedPayment == "paypal";
            if (paypalCheckoutSelected)
            {
                c.Inputs.Add("bvsoftware", "Mode", "PaypalExpress");
                c.Inputs.Add("bvsoftware", "AddressSupplied", "1");
                if (!Workflow.RunByName(c, WorkflowNames.ThirdPartyCheckoutSelected))
                {
                    EventLog.LogEvent("Paypal Express Checkout Failed", "Specific Errors to follow", EventLogSeverity.Error);
                    // Show Errors
                    List<MerchantTribe.Web.Validation.RuleViolation> violations = new List<MerchantTribe.Web.Validation.RuleViolation>();
                    foreach (WorkflowMessage item in c.GetCustomerVisibleErrors())
                    {
                        violations.Add(new MerchantTribe.Web.Validation.RuleViolation("Workflow", item.Name, item.Description));
                    }
                }
            }
            else
            {
                if (Workflow.RunByName(c, WorkflowNames.ProcessNewOrder) == true)
                {
                    // Clear Cart ID because we're now an order
                    SessionManager.SetCurrentCartId(MTApp.CurrentStore, string.Empty);

                    // Process Payment
                    if (MerchantTribe.Commerce.BusinessRules.Workflow.RunByName(c, MerchantTribe.Commerce.BusinessRules.WorkflowNames.ProcessNewOrderPayments))
                    {
                        MerchantTribe.Commerce.BusinessRules.Workflow.RunByName(c, MerchantTribe.Commerce.BusinessRules.WorkflowNames.ProcessNewOrderAfterPayments);
                        Order tempOrder = MTApp.OrderServices.Orders.FindForCurrentStore(model.CurrentOrder.bvin);
                        MTApp.CurrentRequestContext.IntegrationEvents.OrderReceived(tempOrder, MTApp);
                        Response.Redirect("~/checkout/receipt?id=" + model.CurrentOrder.bvin);
                    }
                    else
                    {
                        // Redirect to Payment Error
                        SessionManager.SetCurrentPaymentPendingCartId(MTApp.CurrentStore, model.CurrentOrder.bvin);
                        Response.Redirect("~/checkout/paymenterror");
                    }
                }
                else
                {
                    // Show Errors
                    List<MerchantTribe.Web.Validation.RuleViolation> violations = new List<MerchantTribe.Web.Validation.RuleViolation>();
                    foreach (WorkflowMessage item in c.GetCustomerVisibleErrors())
                    {
                        violations.Add(new MerchantTribe.Web.Validation.RuleViolation("Workflow", item.Name, item.Description));
                    }
                    if (violations.Count < 1)
                    {
                        violations.Add(new MerchantTribe.Web.Validation.RuleViolation("Workflow", "Internal Error",
                            "An internal error occured while attempting to place your order. Please contact the store owner directly to complete your order."));
                    }
                }
            }
        }
        private void SaveShippingSelections(CheckoutViewModel model)
        {
            //Shipping
            string shippingRateKey = Request.Form["shippingrate"];
            MTApp.OrderServices.OrdersRequestShippingMethodByUniqueKey(shippingRateKey, model.CurrentOrder);

            // Save Values so far in case of later errors
            MTApp.CalculateOrder(model.CurrentOrder);

            // Save all the changes to the order
            MTApp.OrderServices.Orders.Update(model.CurrentOrder);
            SessionManager.SaveOrderCookies(model.CurrentOrder, MTApp.CurrentStore);
        }
        private decimal RewardsPotentialCredit(CheckoutViewModel model)
        {
            decimal result = 0;
            if (!model.UseRewardsPoints) return result;

            int points = MTApp.CustomerPointsManager.FindAvailablePoints(model.CurrentCustomer.Bvin);
            int potentialPointsToUse = MTApp.CustomerPointsManager.PointsNeededForPurchaseAmount(model.CurrentOrder.TotalOrderAfterDiscounts);
            int amountToUse = 0;
            if (points > potentialPointsToUse)
            {
                amountToUse = potentialPointsToUse;
            }
            else
            {
                amountToUse = points;
            }
            result = MTApp.CustomerPointsManager.DollarCreditForPoints(amountToUse);
            return result;
        }
 private bool ValidatePage(CheckoutViewModel model)
 {
     bool result = true;
     if (!MTApp.CurrentStore.Settings.PayPal.AllowUnconfirmedAddresses)
     {
         if (string.Compare(ViewBag.AddressStatus, "Unconfirmed", true) == 0)
         {
             model.Violations.Add(new RuleViolation() { ControlName = "",
                 ErrorMessage = "Unconfirmed addresses are not allowed by this store.",
                 PropertyName = "", PropertyValue = "" });
             result = false;
         }
     }
     if (Request.Form["shippingrate"] == null)
     {
         model.Violations.Add(new RuleViolation()
         {
             ControlName = "",
             ErrorMessage = "Please select a shipping method.",
             PropertyName = "",
             PropertyValue = ""
         });
         result =  false;
     }
     if (model.AgreedToTerms == false && model.ShowAgreeToTerms == true)
     {
         model.Violations.Add(new MerchantTribe.Web.Validation.RuleViolation("Terms", "Terms", SiteTerms.GetTerm(SiteTermIds.SiteTermsAgreementError)));
         result = false;
     }
     return result;
 }
 private void TagOrderWithAffiliate(CheckoutViewModel model)
 {
     string affid = MTApp.ContactServices.GetValidAffiliateId(MTApp).ToString();
     if (!string.IsNullOrEmpty(affid))
     {
         model.CurrentOrder.AffiliateID = affid;
     }
 }
        private void ApplyRewardsPoints(CheckoutViewModel model)
        {
            // Remove any current points info transactions
            foreach (OrderTransaction t in MTApp.OrderServices.Transactions.FindForOrder(model.CurrentOrder.bvin))
            {
                if (t.Action == MerchantTribe.Payment.ActionType.RewardPointsInfo)
                {
                    MTApp.OrderServices.Transactions.Delete(t.Id);
                }
            }

            // Don't add if we're not using points
            if (!model.UseRewardsPoints) return;

            // Apply Info to Order
            OrderPaymentManager payManager = new OrderPaymentManager(model.CurrentOrder, MTApp);
            payManager.RewardsPointsAddInfo(RewardsPotentialCredit(model));
        }
        private bool ValidateOrder(CheckoutViewModel model)
        {
            bool result = true;

            if (model.AgreedToTerms == false && model.ShowAgreeToTerms == true)
            {
                model.Violations.Add(new MerchantTribe.Web.Validation.RuleViolation("Terms", "Terms", SiteTerms.GetTerm(SiteTermIds.SiteTermsAgreementError)));
                result = false;
            }

            // Validate Email
            MerchantTribe.Web.Validation.ValidationHelper.ValidEmail("Email Address", model.CurrentOrder.UserEmail, model.Violations, "customeremail");

            // Validate Shipping Address
            model.Violations.AddRange(ValidateAddress(model.CurrentOrder.ShippingAddress, "Shipping"));

            // Validate Billing Address
            if (model.BillShipSame == false)
            {
                model.Violations.AddRange(ValidateAddress(model.CurrentOrder.BillingAddress, "Billing"));
            }

            Order Basket = SessionManager.CurrentShoppingCart(MTApp.OrderServices, MTApp.CurrentStore);
            //Collection<GiftCertificate> gcs = Basket.GetGiftCertificates();
            //decimal totalValue = 0m;
            //foreach (GiftCertificate item in gcs) {
            //    totalValue += item.CurrentAmount;
            //}

            // If Gift Certs are Included in the order, we may not need
            // additional payment information
            bool paymentFound = false;
            //Basket.CalculateGrandTotalOnly(false, false);
            //if ((totalValue >= Basket.TotalGrand)) {
            //	paymentFound = true;
            //}

            // Make sure a shipping method is selected
            // Basket validation checks for shipping method unique key
            if (!Basket.IsValid())
            {
                model.Violations.AddRange(Basket.GetRuleViolations());
            }

            // Payment Validation
            model.Violations.AddRange(ValidatePayment(model));

            if ((model.Violations.Count > 0))
            {
                result = false;
            }
            return result;
        }
        void CheckForPoints(CheckoutViewModel model)
        {
            model.ShowRewards = false;

            if (model.CurrentCustomer == null || model.CurrentCustomer.Bvin == string.Empty) return;

            string uid = model.CurrentCustomer.Bvin;
            int points = MTApp.CustomerPointsManager.FindAvailablePoints(uid);
            if (points > 0 && MTApp.CurrentStore.Settings.RewardsPointsOnPurchasesActive)
            {
                model.ShowRewards = true;
                int potentialPointsToUse = MTApp.CustomerPointsManager.PointsNeededForPurchaseAmount(model.CurrentOrder.TotalOrderAfterDiscounts);
                int amountToUse = 0;
                if (points > potentialPointsToUse)
                {
                    amountToUse = potentialPointsToUse;
                }
                else
                {
                    amountToUse = points;
                }
                model.RewardPointsAvailable = "You have " + points.ToString() + " " + model.LabelRewardPoints + " available.";
                decimal dollarValue = MTApp.CustomerPointsManager.DollarCreditForPoints(amountToUse);
                model.LabelRewardsUse = "Use " + amountToUse.ToString() + " [" + dollarValue.ToString("C") + "] " + model.LabelRewardPoints;
            }
        }
 private bool ValidatePaymentErrorOrder(CheckoutViewModel model)
 {
     model.Violations.AddRange(ValidateAddress(model.CurrentOrder.BillingAddress, "Billing"));
     model.Violations.AddRange(ValidatePayment(model));
     return (model.Violations.Count <= 0);
 }
        void DisplayPaymentMethods(CheckoutViewModel model)
        {
            MerchantTribe.Commerce.Payment.AvailablePayments availablePayments = new MerchantTribe.Commerce.Payment.AvailablePayments();
            Collection<DisplayPaymentMethod> enabledMethods;
            enabledMethods = availablePayments.EnabledMethods(MTApp.CurrentStore);

            model.PaymentViewModel.CheckDescription = WebAppSettings.PaymentCheckDescription;
            model.PaymentViewModel.CodDescription = WebAppSettings.PaymentCODDescription;
            model.PaymentViewModel.CompanyAccountDescription = WebAppSettings.PaymentCompanyAccountName;
            model.PaymentViewModel.PurchaseOrderDescription = WebAppSettings.PaymentPurchaseOrderName;
            model.PaymentViewModel.TelephoneDescription = WebAppSettings.PaymentTelephoneDescription;

            if ((model.CurrentOrder.TotalOrderAfterDiscounts > 0) || (!MTApp.CurrentStore.Settings.AllowZeroDollarOrders))
            {
                model.PaymentViewModel.NoPaymentNeeded = false;
                foreach (DisplayPaymentMethod m in enabledMethods)
                {
                    switch (m.MethodId)
                    {
                        case WebAppSettings.PaymentIdCheck:
                            model.PaymentViewModel.IsCheckActive = true;
                            break;
                        case WebAppSettings.PaymentIdCreditCard:
                            model.PaymentViewModel.IsCreditCardActive = true;
                            break;
                        case WebAppSettings.PaymentIdTelephone:
                            model.PaymentViewModel.IsTelephoneActive = true;
                            break;
                        case WebAppSettings.PaymentIdPurchaseOrder:
                            model.PaymentViewModel.IsPurchaseOrderActive = true;
                            break;
                        case WebAppSettings.PaymentIdCompanyAccount:
                            model.PaymentViewModel.IsCompanyAccountActive = true;
                            break;
                        case WebAppSettings.PaymentIdCashOnDelivery:
                            model.PaymentViewModel.IsCodActive = true;
                            break;
                        case WebAppSettings.PaymentIdPaypalExpress:
                            model.PaymentViewModel.IsPayPalActive = true;
                            break;
                        default:
                            // do nothing
                            break;
                    }
                }

                if (enabledMethods.Count == 1)
                {
                    switch (enabledMethods[0].MethodId)
                    {
                        case WebAppSettings.PaymentIdCheck:
                            model.PaymentViewModel.SelectedPayment = "check";
                            break;
                        case WebAppSettings.PaymentIdCreditCard:
                            model.PaymentViewModel.SelectedPayment = "creditcard";
                            break;
                        case WebAppSettings.PaymentIdTelephone:
                            model.PaymentViewModel.SelectedPayment = "telephone";
                            break;
                        case WebAppSettings.PaymentIdPurchaseOrder:
                            model.PaymentViewModel.SelectedPayment = "purchaseorder";
                            break;
                        case WebAppSettings.PaymentIdCompanyAccount:
                            model.PaymentViewModel.SelectedPayment = "companyaccount";
                            break;
                        case WebAppSettings.PaymentIdCashOnDelivery:
                            model.PaymentViewModel.SelectedPayment = "cod";
                            break;
                        case WebAppSettings.PaymentIdPaypalExpress:
                            model.PaymentViewModel.SelectedPayment = "paypal";
                            break;
                    }
                }
                else
                {
                    if (model.PaymentViewModel.IsCreditCardActive)
                    {
                        model.PaymentViewModel.SelectedPayment = "creditcard";
                    }
                }
            }
            else
            {
                model.PaymentViewModel.NoPaymentNeeded = true;
                model.PaymentViewModel.NoPaymentNeededDescription = WebAppSettings.PaymentNoPaymentNeededDescription;
            }
        }