protected void btnRefund_Click( object sender , EventArgs e )
    {
        PayPalManager payPal = new PayPalManager();
        payPal.RefundTransaction( Request.QueryString[ "TransId" ] );

        Orders orders = new Orders();
        ProcessUpdateOrder updateOrder = new ProcessUpdateOrder();

        int refundedstatustype = 3;

        orders.OrderId = int.Parse( Request.QueryString["OrderId"] );
        orders.OrderStatusId = refundedstatustype;
        orders.ShipDate = ( DateTime ) SqlDateTime.Null;
        updateOrder.Orders = orders;

        try
        {
            updateOrder.Invoke();

            if (payPal.IsSubmissionSuccess)
            {
                EmailManager emailMngr = new EmailManager();
                EmailContents mailContents = new EmailContents();

                mailContents.To = Request.QueryString["Email"];
                mailContents.Bcc = EmailAddressConstants.Simon;
                mailContents.Subject = "Live Free Range Update - Order ID: " + Request.QueryString["OrderID"];
                mailContents.Body = "Your order has been refunded.  Please log into your account for details.";
                mailContents.FromEmailAddress = EmailAddressConstants.Contact;

                emailMngr.Send(mailContents);

                if (!emailMngr.IsSent)
                {
                    Response.Redirect("../ErrorPage.aspx");
                }
            }
        }
        catch(Exception ex)
        {
            Response.Redirect("../ErrorPage.aspx");
        }

        Response.Redirect("Orders.aspx");
    }
    protected void ibCompletePaypalOrder_Click(object sender, ImageClickEventArgs e)
    {
        Product[] products = new Product[gvShoppingCart.Rows.Count];
        foreach (GridViewRow row in gvShoppingCart.Rows)
        {
            if (row.RowType == DataControlRowType.DataRow)
            {
                Product prod = new Product();

                DataKey data = gvShoppingCart.DataKeys[row.DataItemIndex];

                prod.ProductId = int.Parse(data.Values["ProductId"].ToString());

                Literal litProductName = (Literal)row.FindControl("litProductName");
                prod.Name = litProductName.Text;

                Literal litQuantity = (Literal)row.FindControl("litQuantity");
                prod.Quantity = int.Parse(litQuantity.Text);

                Literal litUnitPrice = (Literal)row.FindControl("litUnitPrice");
                litUnitPrice.Text = litUnitPrice.Text.Replace("£", "");
                prod.Price = Convert.ToDecimal(litUnitPrice.Text);

                products.SetValue(prod, row.DataItemIndex);
            }
        }

        CurrentOrder.OrderDetails.Products = products;

        //order total
        this.litTotal.Text = this.litTotal.Text.Replace("£", "");
        this.CurrentOrder.OrderTotal = Convert.ToDecimal(this.litTotal.Text);
        this.CurrentOrder.EndUserId = this.CurrentEndUser.EndUserId;

        string token = Request.QueryString["token"];
        string payerId = Request.QueryString["PayerID"];

        //DoExpressCheckoutPayment
        PayPalManager payPal = new PayPalManager();
        PayPalInformation payPalInformation = new PayPalInformation();
        payPalInformation.Order = this.CurrentOrder;
        payPalInformation.Order.PayerId = payerId;
        payPalInformation.Order.SubTotal = this.CurrentOrder.OrderTotal;

        // #HACK: WJ: sub null for items array below to get it working
        PayPalManager.OrderInfo ppOrderInfo = new PayPalManager.OrderInfo();

        //this call returns an order info object
        //double orderTotal = Convert.ToDouble(this.CommercePage.Basket.GetBaseTotalAfterDiscount());

        double orderTotal = Math.Round(Convert.ToDouble(base.CurrentOrder.SubTotal), 2);

        // this call actually processes the payment
        ppOrderInfo = payPal.DoExpressCheckout(token, payPalInformation);

        string ack = ppOrderInfo.Ack; // says "Success" or "ERROR:..."
        string transactionId = ppOrderInfo.TransactionID;
        string receiptId = ppOrderInfo.ReceiptID;
        this.CurrentOrder.TransactionId = transactionId;
        // handle Paypal web service response
        if (ack.IndexOf("ERROR") != -1)
        {
            //find error placeholder, show and add error message
            ContentPlaceHolder cph = (ContentPlaceHolder)Page.Master.FindControl("ContentPlaceHolder1");

            this.pnlOrderDeclined.Visible = true;

            this.lblTransactionFailureMessage.Text = ack;

            // also need to show a credit card payment option - to do.
        }
        else
        {
            // Transaction successful: complete order!
            ProcessAddOrder addOrder = new ProcessAddOrder();
            addOrder.Orders = this.CurrentOrder;

            try
            {
                addOrder.Invoke();
            }
            catch (Exception ex)
            {
                Response.Redirect("ErrorPage.aspx");
            }

            this.UpdateStockLevel();
            this.DeleteShoppingCart();

            // now forward to order completed page
            Response.Redirect("~/CheckOut/CheckOutReceipt.aspx?ec=true");
        }
    }
    //Complete Pay Pal Order
    protected void ibCompletePaypalOrder_Click(object sender, ImageClickEventArgs e)
    {
        //GetExpressCheckoutDetails - required if shipping goods or if we need the billing address

        /*
        APIWrapper ppGetDetails = new APIWrapper();
        APIWrapper.PayerInfo ppInfo = new APIWrapper.PayerInfo();
        ppInfo = ppGetDetails.GetExpressCheckout(
        */

        string token = Request.QueryString["token"];
        string payerId = Request.QueryString["PayerID"];

        //DoExpressCheckoutPayment
        PayPalManager payPal = new PayPalManager();
        PayPalInformation payPalInformation = new PayPalInformation();
        payPalInformation.Order = this.LiveFreeRangePage.CurrentOrder;

        // #HACK: WJ: sub null for items array below to get it working
        PayPalManager.OrderInfo ppOrderInfo = new PayPalManager.OrderInfo();

        //this call returns an order info object
        //double orderTotal = Convert.ToDouble(this.CommercePage.Basket.GetBaseTotalAfterDiscount());

        this.LiveFreeRangePage.CurrentOrder = new Orders();
        double orderTotal = Convert.ToDouble(this.LiveFreeRangePage.CurrentOrder.SubTotal);

        // this call actually processes the payment
        ppOrderInfo =  payPal.DoExpressCheckout(token, payPalInformation);

        string ack = ppOrderInfo.Ack; // says "Success" or "ERROR:..."
        string transactionId = ppOrderInfo.TransactionID;
        string receiptId = ppOrderInfo.ReceiptID;

        // handle Paypal web service response
        if (ack.IndexOf("ERROR") != -1)
        {
            //find error placeholder, show and add error message
            ContentPlaceHolder cph = (ContentPlaceHolder)Page.Master.FindControl("ContentPlaceHolder1");

            Panel pnlOrderDeclined = (Panel)cph.FindControl("pnlOrderDeclined");
            pnlOrderDeclined.Visible = true;

            Label lblTransactionFailureMessage = (Label)cph.FindControl("lblTransactionFailureMessage");
            lblTransactionFailureMessage.Text = ack;

            // also need to show a credit card payment option - to do.
        }
        else
        {
            // Transaction successful: complete order!
            ProcessAddOrder addOrder = new ProcessAddOrder();
            addOrder.Orders = this.LiveFreeRangePage.CurrentOrder;

            try
            {
                addOrder.Invoke();
            }
            catch (Exception ex)
            {
                Response.Redirect("ErrorPage.aspx");
            }

            this.UpdateStockLevel();
            this.DeleteShoppingCart();

            // now forward to order completed page
            Response.Redirect("~/Web/CheckOutReceipt.aspx");
        }
    }
    //Get PayPal Token and redirect to pay pal
    protected void ibGetPaypalToken_Click(object sender, ImageClickEventArgs e)
    {
        //set the Order object
        if (this.LiveFreeRangePage.IsValid)
        {
            //this.LiveFreeRangePage.CurrentEndUser.FirstName = this.txtFirstName.Text;
            //this.LiveFreeRangePage.CurrentEndUser.LastName = this.txtLastName.Text;
            //this.LiveFreeRangePage.CurrentEndUser.Address.AddressLine = this.txtAddress.Text;
            //this.LiveFreeRangePage.CurrentEndUser.Address.AddressLine2 = this.txtAddress2.Text;
            //this.LiveFreeRangePage.CurrentEndUser.Address.City = this.txtCity.Text;
            //this.LiveFreeRangePage.CurrentEndUser.Address.PostalCode = this.txtPostalCode.Text;

            //this.LiveFreeRangePage.CurrentOrder = new Orders();
            //this.LiveFreeRangePage.CurrentOrder.Enduser.FirstName = this.txtFirstName.Text;
            //this.LiveFreeRangePage.CurrentOrder.Enduser.LastName = this.txtLastName.Text;

            //this.LiveFreeRangePage.CurrentOrder.ShippingAddress.AddressLine = this.txtAddress.Text;
            //this.LiveFreeRangePage.CurrentOrder.ShippingAddress.AddressLine2 = this.txtAddress2.Text;
            //this.LiveFreeRangePage.CurrentOrder.ShippingAddress.City = this.txtCity.Text;
            //this.LiveFreeRangePage.CurrentOrder.ShippingAddress.PostalCode = this.txtPostalCode.Text;

            //this.LiveFreeRangePage.CurrentOrder.CreditCard.CardType = this.ddlCreditCardType.SelectedItem.Value;
            //this.LiveFreeRangePage.CurrentOrder.CreditCard.Number = this.txtCreditCardNumber.Text;
            //this.LiveFreeRangePage.CurrentOrder.CreditCard.SecurityCode = this.txtSecurityCode.Text;
            //this.LiveFreeRangePage.CurrentOrder.CreditCard.ExpMonth = int.Parse(this.ddlExpMonth.SelectedItem.Text);
            //this.LiveFreeRangePage.CurrentOrder.CreditCard.ExpYear = int.Parse(this.ddlExpYear.SelectedItem.Text);

            //this.LiveFreeRangePage.CurrentOrder.CreditCard.Address.AddressLine = this.txtBillingAddress.Text;
            //this.LiveFreeRangePage.CurrentOrder.CreditCard.Address.AddressLine2 = this.txtBillingAddress2.Text;
            //this.LiveFreeRangePage.CurrentOrder.CreditCard.Address.City = this.txtBillingCity.Text;
            //this.LiveFreeRangePage.CurrentOrder.CreditCard.Address.PostalCode = this.txtBillingPostalCode.Text;

            this.LiveFreeRangePage.CurrentOrder = new Orders();
            this.litTax.Text = this.litTax.Text.Replace("£", "");
            this.LiveFreeRangePage.CurrentOrder.Tax = Convert.ToDecimal(litTax.Text);

            this.litSubTotal.Text = this.litSubTotal.Text.Replace("£", "");
            this.LiveFreeRangePage.CurrentOrder.SubTotal = Convert.ToDecimal(this.litSubTotal.Text);

            this.LiveFreeRangePage.CurrentOrder.ShippingTotal = Convert.ToDecimal(ddlShippingOption.SelectedItem.Value);

            //add order object to paypal information object
            PayPalManager payPal = new PayPalManager();
            PayPalInformation payPalInformation = new PayPalInformation();
            payPalInformation.Order = this.LiveFreeRangePage.CurrentOrder;

            //set required url's
            string payPalSubmitUrl = string.Empty;

            if (!(PayPalManager.IsPaypalSandboxOn()))
                payPalSubmitUrl = "https://www.livefreerange.com";
            else
                payPalSubmitUrl = "http://localhost/Web/CheckOut/CheckOut.aspx";

            string payPalCancelUrl = payPalSubmitUrl;

            //pass paypal information to setexpresscheckout and return a token.
            string payPalToken = payPal.SetExpressCheckout(payPalInformation, payPalSubmitUrl, payPalCancelUrl);

            //redirect to paypal with token
            if (payPalToken.ToLower().IndexOf("error") == -1)
                Response.Redirect(PayPalManager.GetPaypalFormSubmissionUrl()
                    + "?cmd=_express-checkout&token="
                    + payPalToken);
            else
            {
                //find error placeholder, show and add error message
                Panel pnlOrderDeclined = (Panel)Page.FindControl("pnlOrderDeclined");
                pnlOrderDeclined.Visible = true;

                Label lblTransactionFailureMessage = (Label)Page.FindControl("lblTransactionFailureMessage");
                lblTransactionFailureMessage.Text = payPalToken;
            }
        }
    }
    private void SubmitOrder()
    {
        PayPalManager payPal = new PayPalManager();
        PayPalInformation _payPalInformation = new PayPalInformation();

        _payPalInformation.Order = this.CurrentOrder;
        payPal.ProcessDirectPayment(_payPalInformation);

        //if payment successful - add Order to database and display
        if (payPal.IsSubmissionSuccess)
        {
            this.pnlSuccess.Visible = true;
            this.litOrderTotal.Text = string.Format("{0:c}", _payPalInformation.Order.OrderTotal);
            this.litTransactionId.Text = this.CurrentOrder.TransactionId;

            ProcessAddOrder addOrder = new ProcessAddOrder();
            addOrder.Orders = this.CurrentOrder;

            //when the order is added to the db must update stock level.
            //and also delete the corresponding baskets.

            try
            {
                addOrder.Invoke();
            }
            catch(Exception ex)
            {
                Response.Redirect("ErrorPage.aspx");
            }

            this.UpdateStockLevel();
            this.DeleteShoppingCart();
        }
        else
        {
            this.pnlFailure.Visible = true;
            this.litErrorMessage.Text = payPal.SubmissionError;
        }
    }
    //Get PayPal Token and redirect to pay pal
    protected void ibGetPaypalToken_Click(object sender, ImageClickEventArgs e)
    {
        //set the Order object
        if (this.IsValid)
        {
            this.CurrentOrder = new Orders();
            this.litTax.Text = this.litTax.Text.Replace("£", "");
            this.CurrentOrder.Tax = Math.Round(Convert.ToDecimal(litTax.Text),2);

            this.litSubTotal.Text = this.litSubTotal.Text.Replace("£", "");
            this.CurrentOrder.SubTotal = Math.Round(Convert.ToDecimal(this.litSubTotal.Text),2);

            this.CurrentOrder.ShippingTotal = Math.Round(Convert.ToDecimal(ddlShippingOption.SelectedItem.Value));

            //add order object to paypal information object
            PayPalManager payPal = new PayPalManager();
            PayPalInformation payPalInformation = new PayPalInformation();
            payPalInformation.Order = this.CurrentOrder;

            //set required url's
            string payPalSubmitUrl = string.Empty;

            if (!(PayPalManager.IsPaypalSandboxOn()))
                payPalSubmitUrl = "https://www.livefreerange.com";
            else
                payPalSubmitUrl = "http://localhost/Web/CheckOut/CheckOut.aspx";

            string payPalCancelUrl = payPalSubmitUrl;

            //pass paypal information to setexpresscheckout and return a token.
            string payPalToken = payPal.SetExpressCheckout(payPalInformation, payPalSubmitUrl, payPalCancelUrl);

            //redirect to paypal with token
            if (payPalToken.ToLower().IndexOf("error") == -1)
            {

                Response.Redirect(PayPalManager.GetPaypalFormSubmissionUrl() + "?cmd=_express-checkout&token=" + payPalToken);
            }
            //else
            //{
            //    //find error placeholder, show and add error message
            //    this.pnlOrderDeclined.Visible = true;
            //    this.lblTransactionFailureMessage.Text = payPalToken;
            //}

        }
    }
 protected void Page_Load(object sender, EventArgs e)
 {
     //if (!Request.IsSecureConnection)
     //{
     //    Response.Redirect(this.UrlBaseSSL);
     //}
       if (!IsPostBack)
     {
         token = Request.QueryString["token"];
         if (!string.IsNullOrEmpty(token))
         {
             payPalInformation = new PayPalInformation();
             payPalInformation.Order = this.CurrentOrder;
             payPal = new PayPalManager();
             payPalInformation = payPal.GetExpressCheckoutDetails(payPalInformation, token);
         }
         this.LoadShoppingCart();
         this.LoadInformation();
     }
 }