protected void lbtnPay_Click(object sender, EventArgs e)
    {
        bool _transaction = false;
        String UserMail = string.Empty;
        string Firstname = string.Empty;
        string LastName = string.Empty;
        StateManager statemail = StateManager.Instance;
        StateManager stateTribure = StateManager.Instance;
        Tributes objTribute = (Tributes)stateTribure.Get("TributeSession", StateManager.State.Session);

        try
        {
            //check for credit card lengths
            if (Request.Form["rdoCCType"] == "Visa" || Request.Form["rdoCCType"] == "MasterCard" || Request.Form["rdoCCType"] == "Discover")
            {
                if (txtCCNumber.Text.Length != 16 && txtCCVerification.Text.Length != 3)
                {
                    ShowMessage(ValidationSummary1.HeaderText, "Transaction Failed", true);
                    return;

                }
            }
            else if (Request.Form["rdoCCType"] == "Amex" && txtCCNumber.Text.Length != 15 && txtCCVerification.Text.Length != 4)
            {
                ShowMessage(ValidationSummary1.HeaderText, "Transaction Failed", true);
                return;

            }
            //else
            //{
            //HtmlInputRadioButton Lifetime = (HtmlInputRadioButton)this.FindControl("rdoMembershipLifetime");
            //HtmlInputRadioButton Yearly = (HtmlInputRadioButton)this.FindControl("rdoMembershipYearly");
            int couponType = 0;
            if (rdoMembershipLifetime.Checked)
                couponType = 3;
            else
                couponType = 2;
            if (txtCouponCode.Text != string.Empty)
            {
                int availability = _presenter.GetCouponAvailable(txtCouponCode.Text, couponType);

                if (availability == 1)
                {
                    //SetCouponAvailableStatus();
                    double Couponamount = 0;
                    if (rdoMembershipLifetime.Checked)
                    {
                        amount = WebConfig.LifeTimeVideoTributeUpgrade;
                        Couponamount = double.Parse(amount.Substring(1, amount.Length - 1));
                        // BillingTotal.InnerHtml = amount;
                    }
                    else
                    {
                        amount = WebConfig.OneYearVideoTributeUpgrade;
                        Couponamount = double.Parse(amount.Substring(1, amount.Length - 1));
                        //BillingTotal.InnerHtml = amount;
                    }
                    if (this._presenter.View.IsPercentage == false)
                        Couponamount = Couponamount - double.Parse(this._presenter.View.Denomination);
                    else
                        Couponamount = Couponamount - ((double.Parse(this._presenter.View.Denomination) * Couponamount) / 100);
                    if (Couponamount < 0)
                        Couponamount = 0;
                    BillingTotal.InnerHtml = ("$" + Couponamount.ToString());

                    //Remove Commented code for Payment Gateway :Amit :2/5/8
                    SessionValue objSessionmail = (SessionValue)statemail.Get("objSessionvalue", StateManager.State.Session);
                    if (objSessionmail != null)
                    {
                        Firstname = objSessionmail.FirstName;
                        LastName = objSessionmail.LastName;
                        UserMail = objSessionmail.UserEmail;
                    }

                    PaymentGateWay objPay = new PaymentGateWay();
                    if (Couponamount > 0)
                    {
                        //_transaction = true;//objPay.PayYourBill(TributePortalSecurity.Security.DecryptSymmetric(this._presenter.View.CreditCardNo), txtCCVerification.Text, int.Parse(ddlCCMonth.SelectedValue), int.Parse(txtCCYear.Text), double.Parse(Couponamount.ToString()), SelectCreditCardType(), txtCCName.Text, "", _presenter.View.Address.Replace(WebConfig.AddressSeparator, WebConfig.AddressSeparatorDisplay), txtCCCity.Text, StateV1.CA, CountryV1.US, txtCCZipCode.Text, _presenter.View.Telephone.ToString(), txtEmailAddress.Text.Trim(), HttpContext.Current.Request.UserHostAddress.ToString(), out confirmationId, out errorMesg);
                        sBeanStreamResponce = objPay.PayYourBill(TributePortalSecurity.Security.DecryptSymmetric(this._presenter.View.CreditCardNo), txtCCVerification.Text, int.Parse(ddlCCMonth.SelectedValue), int.Parse(txtCCYear.Text), double.Parse(Couponamount.ToString()), SelectCreditCardType(), txtCCName.Text.Trim(), "", _presenter.View.Address.Replace(WebConfig.AddressSeparator, WebConfig.AddressSeparatorDisplay), txtCCCity.Text, StateV1.CA, CountryV1.US, txtCCZipCode.Text, _presenter.View.Telephone.ToString(), txtEmailAddress.Text.Trim(), HttpContext.Current.Request.UserHostAddress.ToString(), out confirmationId, out errorMesg, out _transaction);
                    }
                    else
                        _transaction = true;
                    //End

                    if (_transaction)
                    {
                        bool result = AddMailChimpSubscriber(initailPackageId, getPackageId);
                        if (!Equals(objTribute, null))
                        {
                            // For making Amount Paid of Float type in Video tribute upgradation
                            StateManager stateManager = StateManager.Instance;
                            stateManager.Add("SentFrom", "VideoTributeSpons", StateManager.State.Session);
                            Session["SentFrom"] = "VideoTributeSpons";
                            _TribureId = objTribute.TributeId;
                            _tributeUrl = objTribute.TributeUrl;
                            this._presenter.TriputePackageInfo(TributeId);
                            if (PnlPaymentDetails.Visible == true)
                            {
                                // if billing amount is greater thn 0 then only insert CreditCrd Details and Insert new Package details with updated record
                                this._presenter.InsertCCDetails((SessionValue)statemail.Get("objSessionvalue", StateManager.State.Session), objTribute, confirmationId, SponsorNameandMsgForEmail);
                            }
                            else
                            {
                                // if there is no billing amount then insert only the new Package details
                                this._presenter.InsertPackageDetails(objTribute.TributeId, 0, confirmationId);
                            }
                        }
                        if (!string.IsNullOrEmpty(txtCouponCode.Text))
                            this._presenter.UpdateUsedCouponDetails(txtCouponCode.Text);

                        SetDefault();
                        if (Request.QueryString["PageName"] == "AdminMytributesPrivacy")
                        {
                            Response.Redirect(Session["APP_BASE_DOMAIN"] + this._presenter.View.TributeURL + "/paymentconfirmation.aspx?tid=" + _tributPackageId.ToString() + "&PageName=" + Request.QueryString["PageName"].ToString(), false);
                        }
                        else
                        {
                            try
                            {

                                // if person has not been charged than take him back to Tribute Main Page
                                if (Couponamount == 0)
                                    Response.Redirect(Session["APP_BASE_DOMAIN"] + this._presenter.View.TributeURL + "/", false);

                                // if person has been charged than take him to the payment Confirmation Page
                                if (WebConfig.ApplicationMode.ToLower() == "local")
                                    Response.Redirect(Session["APP_BASE_DOMAIN"] + "tribute/paymentconfirmation.aspx?tid=" + _tributPackageId.ToString() + "&SentFrom=VideoTributeSpons", false);
                                else
                                    Response.Redirect("http://video." + WebConfig.TopLevelDomain + "/tribute/paymentconfirmation.aspx?tid=" + _tributPackageId.ToString() + "&SentFrom=VideoTributeSpons", false);

                            }
                            catch //(Exception po)  by Ud
                            { }
                        }

                    }
                    else
                    {
                        ShowMessage(ValidationSummary1.HeaderText, errorMesg, true);
                        //if (Request.QueryString["PageName"] == "AdminMytributesPrivacy")
                        //{
                        //    Response.Redirect(Session["APP_BASE_DOMAIN"] + "adminmytributesprivacy.aspx", false);
                        //}
                        //else
                        //{
                        //    //Response.Redirect("http://" + this._presenter.View.SubDomain.Replace("New Baby", "newbaby") + "." + WebConfig.TopLevelDomain + "/" + this._presenter.View.TributeURL);
                        //    //uncomment the line above and comment the line below for server
                        //    Response.Redirect(Session["APP_BASE_DOMAIN"] + this._presenter.View.TributeURL);
                        //}
                    }
                }
                else
                {
                    if (txtCouponCode.Text != string.Empty)
                    {
                        SetCouponUnAvailableStatus();
                    }
                }
            }
            else
            {
                //SetCouponAvailableStatus();
                double Couponamount = 0;
                if (rdoMembershipLifetime.Checked)
                {
                    amount = WebConfig.LifeTimeVideoTributeUpgrade;
                    Couponamount = double.Parse(amount.Substring(1, amount.Length - 1).Trim());
                    BillingTotal.InnerHtml = amount;
                }
                else
                {
                    amount = WebConfig.OneYearVideoTributeUpgrade;
                    Couponamount = double.Parse(amount.Substring(1, amount.Length - 1).Trim());
                    BillingTotal.InnerHtml = amount;
                }

                SessionValue objSessionmail = (SessionValue)statemail.Get("objSessionvalue", StateManager.State.Session);
                if (objSessionmail != null)
                {
                    Firstname = objSessionmail.FirstName;
                    LastName = objSessionmail.LastName;
                    UserMail = objSessionmail.UserEmail;
                }
                PaymentGateWay objPay = new PaymentGateWay();
                //Pay only when coupon amount id greater than 0
                if (Couponamount > 0)
                {
                    //_transaction = true;// objPay.PayYourBill(TributePortalSecurity.Security.DecryptSymmetric(this._presenter.View.CreditCardNo), txtCCVerification.Text, int.Parse(ddlCCMonth.SelectedValue), int.Parse(txtCCYear.Text), double.Parse(Couponamount.ToString()), SelectCreditCardType(), txtCCName.Text, "", _presenter.View.Address.Replace(WebConfig.AddressSeparator, WebConfig.AddressSeparatorDisplay), txtCCCity.Text, StateV1.CA, CountryV1.US, txtCCZipCode.Text, _presenter.View.Telephone.ToString(), txtEmailAddress.Text.Trim(), HttpContext.Current.Request.UserHostAddress.ToString(),  confirmationId,  errorMesg);
                    sBeanStreamResponce = objPay.PayYourBill(TributePortalSecurity.Security.DecryptSymmetric(this._presenter.View.CreditCardNo), txtCCVerification.Text, int.Parse(ddlCCMonth.SelectedValue), int.Parse(txtCCYear.Text), double.Parse(Couponamount.ToString()), SelectCreditCardType(), txtCCName.Text.Trim(), "", _presenter.View.Address.Replace(WebConfig.AddressSeparator, WebConfig.AddressSeparatorDisplay), txtCCCity.Text, StateV1.CA, CountryV1.US, txtCCZipCode.Text, _presenter.View.Telephone.ToString(), txtEmailAddress.Text.Trim(), HttpContext.Current.Request.UserHostAddress.ToString(), out confirmationId, out errorMesg, out _transaction);
                }
                else
                {
                    _transaction = true;

                }
                if (_transaction)
                {
                    if (!Equals(objTribute, null))
                    {
                        // For making Amount Paid of Float type in Video tribute upgradation
                        StateManager stateManager = StateManager.Instance;
                        stateManager.Add("SentFrom", "VideoTributeSpons", StateManager.State.Session);
                        Session["SentFrom"] = "VideoTributeSpons";
                        _TribureId = objTribute.TributeId;
                        _tributeUrl = objTribute.TributeUrl;
                        this._presenter.TriputePackageInfo(TributeId);
                        // Insert Credit Card details, Sending Mail to Sponsor and Insertion in Tribute Package table
                        this._presenter.InsertCCDetails((SessionValue)statemail.Get("objSessionvalue", StateManager.State.Session), objTribute, confirmationId, SponsorNameandMsgForEmail);
                    }

                    SetDefault();
                    if (Request.QueryString["PageName"] == "AdminMytributesPrivacy")
                    {

                        Response.Redirect(Session["APP_BASE_DOMAIN"] + "tribute/paymentconfirmation.aspx?tid=" + _tributPackageId.ToString() + "&PageName=" + Request.QueryString["PageName"].ToString(), false);
                    }
                    else
                    {
                        try
                        {
                            if (WebConfig.ApplicationMode.ToLower() == "local")
                                Response.Redirect(Session["APP_BASE_DOMAIN"] + "tribute/paymentconfirmation.aspx?tid=" + _tributPackageId.ToString() + "&SentFrom=VideoTributeSpons", false);
                            else
                                Response.Redirect("http://video." + WebConfig.TopLevelDomain + "/tribute/paymentconfirmation.aspx?tid=" + _tributPackageId.ToString() + "&SentFrom=VideoTributeSpons", false);

                        }
                        catch //(Exception abc) // by Ud
                        { }
                    }
                }
                else
                {
                    ShowMessage(ValidationSummary1.HeaderText, errorMesg, true);
                }
            }
        }
        catch (Exception excep)
        {
            if (excep.Message.StartsWith("PAYMENT"))
                ShowMessage(ValidationSummary1.HeaderText, "Transaction Failed! An error has occured while trying to connect to the payment gateway. Please try later.", true);
            else
                ShowMessage(ValidationSummary1.HeaderText, "Transaction Failed! While your transaction was successful and your credit card was charged but we could not process it at our end. Please contact the webmaster.", true);
            //ShowMessage(ValidationSummary1.HeaderText, "Transaction Failed. Please try again later.", true);
        }
        //}
    }
    protected void lbtnPay_Click(object sender, EventArgs e)
    {
        bool _transaction = false;
        String UserMail = string.Empty;
        string Firstname = string.Empty;
        string LastName = string.Empty;
        double NewUpdatedCredit = 0;
        string strBillingTotal;
        StateManager statemail = StateManager.Instance;
        StateManager stateTribure = StateManager.Instance;
        Tributes objTribute = (Tributes)stateTribure.Get("TributeSession", StateManager.State.Session);

        try
        {
            //check for credit card lengths
            if (Request.Form["rdoCCType"] == "Visa" || Request.Form["rdoCCType"] == "MasterCard" || Request.Form["rdoCCType"] == "Discover")
            {
                if (txtCCNumber.Text.Length != 16 && txtCCVerification.Text.Length != 3)
                {
                    ShowMessage(ValidationSummary1.HeaderText, "Transaction Failed", true);
                    return;

                }
            }
            else if (Request.Form["rdoCCType"] == "Amex" && txtCCNumber.Text.Length != 15 && txtCCVerification.Text.Length != 4)
            {
                ShowMessage(ValidationSummary1.HeaderText, "Transaction Failed", true);
                return;

            }

            double Couponamount = 0;
            // Getting Value from Billing span at the bootm of the page
            strBillingTotal = Convert.ToString(BillingTotal.InnerText);
            double.TryParse(strBillingTotal.ToString().Replace("$", ""), out Couponamount);

            SessionValue objSessionmail = (SessionValue)statemail.Get("objSessionvalue", StateManager.State.Session);
            if (objSessionmail != null)
            {
                Firstname = objSessionmail.FirstName;
                LastName = objSessionmail.LastName;
                UserMail = objSessionmail.UserEmail;
            }
            PaymentGateWay objPay = new PaymentGateWay();
            // bool _transaction = true;

            //Start - Modification on 15-Dec-09 for the enhancement 1 of the Phase 1
            //If the bill amount (Couponamount) is greater than $0, then only the transaction should go to the payment gateway
            // Pay only if CouponAmount is greater than only pay the bill
            if (Couponamount > 0)
               // _transaction = objPay.PayYourBill(TributePortalSecurity.Security.DecryptSymmetric(this._presenter.View.CreditCardNo), txtCCVerification.Text, int.Parse(ddlCCMonth.SelectedValue), int.Parse(txtCCYear.Text), Couponamount.ToString(), SelectCreditCardType(), txtCCName.Text, "", _presenter.View.Address.Replace(WebConfig.AddressSeparator, WebConfig.AddressSeparatorDisplay), txtCCCity.Text, StateV1.CA, CountryV1.US, txtCCZipCode.Text, _presenter.View.Telephone.ToString(), txtEmailAddress.Text.Trim(), HttpContext.Current.Request.UserHostAddress.ToString(), out confirmationId, out errorMesg);
                sBeanStreamResponce=objPay.PayYourBill(TributePortalSecurity.Security.DecryptSymmetric(this._presenter.View.CreditCardNo), txtCCVerification.Text, int.Parse(ddlCCMonth.SelectedValue), int.Parse(txtCCYear.Text), Couponamount, SelectCreditCardType(), txtCCName.Text.Trim(), "", _presenter.View.Address.Replace(WebConfig.AddressSeparator, WebConfig.AddressSeparatorDisplay), txtCCCity.Text, StateV1.CA, CountryV1.US, txtCCZipCode.Text, _presenter.View.Telephone.ToString(), txtEmailAddress.Text.Trim(), HttpContext.Current.Request.UserHostAddress.ToString(), out confirmationId, out errorMesg, out _transaction);
            else
                _transaction = true;
            //End

            if (_transaction)
            {

                if (PnlPaymentDetails.Visible == true)
                {
                    // Insert Credit Card Info if payment panel is visible else not
                    CCIdentity = this._presenter.InsertCreditPointCCDetails((SessionValue)statemail.Get("objSessionvalue", StateManager.State.Session), confirmationId);
                }
                //     this._presenter.InsertPackageDetails(objTribute.TributeId, CCIdentity, confirmationId);

                // Get current credit Point in the User account
                _presenter.GetCreditPointCount();
                NewUpdatedCredit = double.Parse(Session["CreditPointSelected"].ToString()) + _NetCreditCount;

                // Insert updated Credit Point in CreditPointTransaction Table
                this._presenter.InsertCurrentCreditPoints(NewUpdatedCredit, CCIdentity.ToString(), confirmationId);

                if (Couponamount > 0)
                    //to get the sponsorship receipt and send the same on Email
                    _presenter.OnViewInitialized();

                SetDefault();
                if (Convert.ToInt32(Session["CreditPointSelected"].ToString()) > 1)
                {
                    Session["LineForPayConf"] = "Thank you for your order of <b>" + Session["CreditPointSelected"].ToString() + " credits</b>.<br/><br/>Your credit card will show a charge from \"Your"+ConfigurationManager.AppSettings["ApplicationWord"]+"\" for<b> $" + Couponamount.ToString() + "</b>. Your transaction ID is<b> " + TransactionId.ToString() + ".</b>";
                }
                else
                    Session["LineForPayConf"] = "Thank you for your order of <b> " + Session["CreditPointSelected"].ToString() + " credit</b>.<br/><br/>Your credit card will show a charge from \"Your"+ConfigurationManager.AppSettings["ApplicationWord"]+"\" for<b> $" + Couponamount.ToString() + "</b>. Your transaction ID is<b> " + TransactionId.ToString() + ".</b>";

                Session["SentFrom"] = "OrderCredit";
                if (WebConfig.ApplicationMode.ToLower() == "local")
                    Response.Redirect(Session["APP_BASE_DOMAIN"] + "tribute/paymentconfirmation.aspx?SentFrom=OrderCredit", false);
                else
                    Response.Redirect("http://" + WebConfig.TopLevelDomain + "/tribute/paymentconfirmation.aspx?SentFrom=OrderCredit", false);
                //Response.Redirect("http://video." + WebConfig.TopLevelDomain + "/tribute/paymentconfirmation.aspx?SentFrom=OrderCredit", false);
                // commented by udham to redirect to top level domain
            }
            else
            {
                //ShowMessage(ValidationSummary1.HeaderText, errorMesg, true);
                var sResponseArr = sBeanStreamResponce.Split('&');
                var sErrorMsg = sResponseArr.Length > 3 && sResponseArr[3].Split('=').Length > 1 && !string.IsNullOrEmpty(sResponseArr[3].Split('=')[1]) ? sResponseArr[3].Split('=')[1].Replace("+", " ") : "";
                //LHK:17-11-2011- for gracefull error message display.
                sErrorMsg = HttpUtility.UrlDecode(sErrorMsg);
                ShowMessage(ValidationSummary1.HeaderText, sErrorMsg, true);

            }
        }

        catch (Exception excep)
        {
            if (excep.Message.StartsWith("PAYMENT"))
                ShowMessage(ValidationSummary1.HeaderText, "Transaction Failed! An error has occured while trying to connect to the payment gateway. Please try later.", true);
            else
                ShowMessage(ValidationSummary1.HeaderText, "Transaction Failed! While your transaction was successful and your credit card was charged but we could not process it at our end. Please contact the webmaster.", true);
            //ShowMessage(ValidationSummary1.HeaderText, "Transaction Failed. Please try again later.", true);
        }
        //}
    }
        /// <summary>
        /// This method used for AutoRenewal for One Year
        /// </summary>
        public void AutoRenewalForOneYearPackage()
        {
            DataSet dsMailerList = new DataSet();
            DataSet dsMailerList1 = new DataSet();//vchange line added
            bool _transaction = true;
            PaymentGateWay objPay = new PaymentGateWay();
            ResourceAccess objResouce = new ResourceAccess();
            EmailMessages objEmail = EmailMessages.Instance;
            string _EmailBody=string.Empty;
            string confirmationId = string.Empty;//vchange line added
            string amount = string.Empty;//vchange line added
             object[] objParam = new object[3];
             object[] objParam2 = { null };
             try
             {

             dsMailerList = objResouce.GetDataSet("usp_AutoRenewalCustomerList", null);

                 if (dsMailerList.Tables[0].Rows.Count > 0)
                 {
                     for (int i = 0; i <= dsMailerList.Tables[0].Rows.Count - 1; i++)
                     {
                         //This code will execute on server
                         /*_transaction = objPay.PayYourBill(dsMailerList.Tables[0].Rows[i]["CreditCardNo"].ToString(), dsMailerList.Tables[0].Rows[i]["CVC"].ToString(),
                             int.Parse(DateTime.Now.Month.ToString()), int.Parse(DateTime.Now.Year.ToString()),
                             "20.00", SelectCreditCardType(dsMailerList.Tables[0].Rows[i]["CreditCardType"].ToString()),
                             dsMailerList.Tables[0].Rows[i]["FirstName"].ToString(), dsMailerList.Tables[0].Rows[i]["Lastname"].ToString(), "TimelessTribute BackOffice",
                         dsMailerList.Tables[0].Rows[i]["City"].ToString(), StateV1.CA, CountryV1.US, dsMailerList.Tables[0].Rows[i]["Zip"].ToString(),
                         dsMailerList.Tables[0].Rows[i]["Telephone"].ToString(), dsMailerList.Tables[0].Rows[i]["Email"].ToString(),
                         Environment.MachineName.ToString());*/
                         //This code will execute on local
                         /* _transaction = true;*/

                         //vchange added satarted
                         try
                         {
                             int Couponamount = 0;

                             amount = ConfigurationSettings.AppSettings["OneyearAmount"];
                             Couponamount = Convert.ToInt32(amount.Substring(1, amount.Length - 1));

                             _transaction = objPay.PayYourBill(TributePortalSecurity.Security.DecryptSymmetric(dsMailerList.Tables[0].Rows[i]["CreditCardNo"].ToString()), TributePortalSecurity.Security.DecryptSymmetric(dsMailerList.Tables[0].Rows[i]["CVC"].ToString()),
                               Convert.ToInt32(dsMailerList.Tables[0].Rows[i]["ExpiryMonth"]), Convert.ToInt32(dsMailerList.Tables[0].Rows[i]["ExpiryYear"]),
                               Couponamount.ToString(), SelectCreditCardType(dsMailerList.Tables[0].Rows[i]["CreditCardType"].ToString()),
                               dsMailerList.Tables[0].Rows[i]["FirstName"].ToString(), dsMailerList.Tables[0].Rows[i]["Lastname"].ToString(), dsMailerList.Tables[0].Rows[i]["Address"].ToString().Replace(ConfigurationSettings.AppSettings["AddressSeparator"],ConfigurationSettings.AppSettings["AddressSeparatorDisplay"]),
                           dsMailerList.Tables[0].Rows[i]["City"].ToString(), StateV1.CA, CountryV1.US, dsMailerList.Tables[0].Rows[i]["Zip"].ToString(),
                           dsMailerList.Tables[0].Rows[i]["Telephone"].ToString(), dsMailerList.Tables[0].Rows[i]["Email"].ToString(),
                           Environment.MachineName.ToString(), out confirmationId);

                          //   _transaction = objPay.PayYourBill(dsMailerList.Tables[0].Rows[i]["CreditCardNo"].ToString(), dsMailerList.Tables[0].Rows[i]["CVC"].ToString(),
                          //    int.Parse(DateTime.Now.Month.ToString()), int.Parse(DateTime.Now.Year.ToString()),
                          //    Couponamount.ToString(), SelectCreditCardType(dsMailerList.Tables[0].Rows[i]["CreditCardType"].ToString()),
                          //    dsMailerList.Tables[0].Rows[i]["FirstName"].ToString(), dsMailerList.Tables[0].Rows[i]["Lastname"].ToString(), "TimelessTribute BackOffice",
                          //dsMailerList.Tables[0].Rows[i]["City"].ToString(), StateV1.CA, CountryV1.US, dsMailerList.Tables[0].Rows[i]["Zip"].ToString(),
                          //dsMailerList.Tables[0].Rows[i]["Telephone"].ToString(), dsMailerList.Tables[0].Rows[i]["Email"].ToString(),
                          //Environment.MachineName.ToString(), out confirmationId);
                             //vchange added end
                             if (_transaction)
                             {
                                 EventLog.WriteEntry("Payment Recived");
                                 objParam[0] = dsMailerList.Tables[0].Rows[i]["TributePackageId"].ToString();
                                 objParam[1] = Couponamount.ToString();// vchnage "20";
                                 objParam[2] = confirmationId.Length == 0 ? 0 : int.Parse(confirmationId);

                                 //objResouce.GetDataSet("usp_RenewTributePackage", objParam);
                                 //vchnage code added satrt
                                 dsMailerList1 = objResouce.GetDataSet("usp_RenewTributePackage", objParam);
                                 if (dsMailerList1.Tables[0].Rows.Count > 0)
                                 {
                                         //vchnage code added end
                                         objEmail = EmailMessages.Instance;
                                         _EmailBody = ConfigurationSettings.AppSettings["MailAfterRenewal"];

                                         _EmailBody = _EmailBody.Replace("#FirstName", dsMailerList.Tables[0].Rows[i]["FirstName"].ToString());
                                         _EmailBody = _EmailBody.Replace("#LastName", dsMailerList.Tables[0].Rows[i]["LastName"].ToString());
                                         _EmailBody = _EmailBody.Replace("#TributeName", dsMailerList.Tables[0].Rows[i]["TributeName"].ToString());
                                         _EmailBody = _EmailBody.Replace("#TributeUrl", dsMailerList.Tables[0].Rows[i]["TributeUrl"].ToString());
                                         _EmailBody = _EmailBody.Replace("#RenewalDate", DateTime.Parse(dsMailerList.Tables[0].Rows[i]["EndDate"].ToString()).ToString("MMMM dd, yyyy"));
                                         _EmailBody = _EmailBody.Replace("#TributeType", dsMailerList.Tables[0].Rows[i]["TributeTypeName"].ToString().ToLower());
                                         objEmail.SendMessages("Your Tribute<*****@*****.**>", dsMailerList.Tables[0].Rows[i]["Email"].ToString(), "The " + dsMailerList.Tables[0].Rows[i]["TributeName"].ToString() + " Tribute renewed.", _EmailBody, EmailMessages.TextFormat.Html.ToString());

                                         ///vchnage code added start
                                         object[] param ={ dsMailerList1.Tables[0].Rows[0][0].ToString() };
                                         GetTransactionDetails(param);

                                 }
                             }
                             else
                             {
                                 //NotifyRenwealFailed()
                                 EventLog.WriteEntry("Payment not recevied");
                                 objEmail = EmailMessages.Instance;
                                 _EmailBody = ConfigurationSettings.AppSettings["MailRenewalFailed"];
                                 _EmailBody = _EmailBody.Replace("#FirstName", dsMailerList.Tables[0].Rows[i]["FirstName"].ToString());
                                 _EmailBody = _EmailBody.Replace("#LastName", dsMailerList.Tables[0].Rows[i]["LastName"].ToString());
                                 _EmailBody = _EmailBody.Replace("#TributeName", dsMailerList.Tables[0].Rows[i]["TributeName"].ToString());
                                 _EmailBody = _EmailBody.Replace("#TributeUrl", dsMailerList.Tables[0].Rows[i]["TributeUrl"].ToString());
                                 _EmailBody = _EmailBody.Replace("#TributeType", dsMailerList.Tables[0].Rows[i]["TributeTypeName"].ToString().ToLower());
                                 objEmail.SendMessages("Your Tribute<*****@*****.**>", dsMailerList.Tables[0].Rows[i]["Email"].ToString(), "Auto-Renewal of the " + dsMailerList.Tables[0].Rows[i]["TributeName"].ToString() + " Tribute has failed...", _EmailBody, EmailMessages.TextFormat.Html.ToString());
                             }
                         }
                         catch
                         {
                             // NotifyRenwealFailed()
                             EventLog.WriteEntry("Exception occured,Payment not recevied");
                             objEmail = EmailMessages.Instance;
                             _EmailBody = ConfigurationSettings.AppSettings["MailRenewalFailed"];
                             _EmailBody = _EmailBody.Replace("#FirstName", dsMailerList.Tables[0].Rows[i]["FirstName"].ToString());
                             _EmailBody = _EmailBody.Replace("#LastName", dsMailerList.Tables[0].Rows[i]["LastName"].ToString());
                             _EmailBody = _EmailBody.Replace("#TributeName", dsMailerList.Tables[0].Rows[i]["TributeName"].ToString());
                             _EmailBody = _EmailBody.Replace("#TributeUrl", dsMailerList.Tables[0].Rows[i]["TributeUrl"].ToString());
                             _EmailBody = _EmailBody.Replace("#TributeType", dsMailerList.Tables[0].Rows[i]["TributeTypeName"].ToString().ToLower());
                             objEmail.SendMessages("Your Tribute<*****@*****.**>", dsMailerList.Tables[0].Rows[i]["Email"].ToString(), "Auto-Renewal of the " + dsMailerList.Tables[0].Rows[i]["TributeName"].ToString() + " Tribute has failed...", _EmailBody, EmailMessages.TextFormat.Html.ToString());
                             ///vchnage code added end
                         }

                         objEmail = null;
                     }
                 }
             }
             catch (Exception ex)
             {
                 EventLog.WriteEntry(ex.Message.ToString());
             }
        }
    private bool CreateTribute()
    {
        bool retvalue = false;
        bool _transaction = true;
        PaymentGateWay objPay = new PaymentGateWay();
        String UserMail = string.Empty;
        string Firstname = string.Empty;
        string LastName = string.Empty;
        double Couponamount = 0;
        string strBillingTotal;
        double NewUpdatedCredit = 0;

        //BeanStream Responce string
        var bIsSuccess = false;

        //Remove Commented code for Payment Gateway :Amit :2/5/8

        try
        {
            int couponType = 0;
            if (rdoMembershipLifetime.Checked)
                couponType = 3;
            else
                couponType = 2;
            StateManager statemail = StateManager.Instance;
            SessionValue objSessionmail = (SessionValue)statemail.Get("objSessionvalue", StateManager.State.Session);
            if (objSessionmail != null)
            {
                Firstname = objSessionmail.FirstName;
                LastName = objSessionmail.LastName;
                UserMail = objSessionmail.UserEmail;
            }
            if (_accountType == 3)
            {
                this._presenter.CheckAvailability();
                if (int.Parse(Status) != 0)
                {
                    //Tribute Url already exists
                    AvailabilityStatus();
                    return false;
                }
            }
            if (!rdoMembershipFree.Checked)
            {
                #region CouponCheck&Update
                if (txtCouponCode.Text != string.Empty)
                {
                    int availability = _presenter.GetCouponAvailable(txtCouponCode.Text, couponType);

                    if (availability == 1)
                    {
                        //SetCouponAvailableStatus();

                        if (rdoMembershipLifetime.Checked)
                        {
                            if (_accountType == 2)
                            {
                                amount = WebConfig.PhotoLifeTimeAmount;
                            }
                            else if (_accountType == 3)
                            {
                                amount = WebConfig.TributeLifeTimeAmount;
                            }
                            Couponamount = Convert.ToDouble(amount.Substring(1, amount.Length - 1));

                            // BillingTotal.InnerHtml = amount;
                        }
                        else if (rdoMembershipYearly.Checked)
                        {
                            if (_accountType == 2)
                            {
                                amount = WebConfig.PhotoOneyearAmount;
                            }
                            else if (_accountType == 3)
                            {
                                amount = WebConfig.TributeOneyearAmount;
                            }
                            Couponamount = Convert.ToDouble(amount.Substring(1, amount.Length - 1));
                            //BillingTotal.InnerHtml = amount;
                        }
                            //LHK: is this case tested ever while development. issue in local not on staging
                        else if (rdbAnnounceFreeNoAds.Checked)
                        {
                            if (_accountType == 1)
                            {
                                amount = WebConfig.PhotoOneyearAmount;
                            }
                            Couponamount = Convert.ToDouble(amount.Substring(1, amount.Length - 1));
                        }
                        //LHK:till here is this case tested ever while development.
                        if (this._presenter.View.IsPercentage == false)
                            Couponamount = Couponamount - int.Parse(this._presenter.View.Denomination);
                        else
                            Couponamount = Couponamount - ((int.Parse(this._presenter.View.Denomination) * Couponamount) / 100);
                        if (Couponamount < 0)
                            Couponamount = 0;
                        BillingTotal.InnerHtml = ("$" + Couponamount.ToString());
                        //totalValue = Convert.ToInt32(amount);
                        double.TryParse(amount.Substring(1, 5).Trim(), out totalValue);
                    }
                    else
                    {
                        SetCouponUnAvailableStatus();
                        return false;
                    }
                }
                #endregion
                else if (PnlPaymentDetails.Visible == true)
                {
                    strBillingTotal = Convert.ToString(BillingTotal.InnerText);
                    Couponamount = Convert.ToDouble(strBillingTotal.Substring(1, strBillingTotal.Length - 1).Trim());
                    Couponamount = Math.Round(Couponamount, 2);
                    // totalValue = Convert.ToInt32(Couponamount);
                    totalValue = Couponamount;
                    //double.TryParse(Couponamount, out totalValue);
                }
                else
                {
                    Couponamount = 0;
                }
                try
                {
                    StateManager stateManager = StateManager.Instance;
                    SessionValue objSessionvalue = (SessionValue)stateManager.Get("objSessionvalue", StateManager.State.Session);

                    _amount = Couponamount.ToString();
                    // Pay only if coupon amount is graeter than 0 or billing panel is visible
                    if (Couponamount > 0 && PnlPaymentDetails.Visible == true)
                    {
                        //diffrentiating a numeric and a decimal number.
                        if (Couponamount == Math.Round(Couponamount))
                        {
                            //for Non- decimal values.
                            sBeanStreamResponce = objPay.PayYourBill(TributePortalSecurity.Security.DecryptSymmetric(this._presenter.View.CreditCardNo), txtCCVerification.Text, int.Parse(ddlCCMonth.SelectedValue), int.Parse(txtCCYear.Text), Couponamount, SelectCreditCardType(), txtCCName.Text.Trim(), "", _presenter.View.Address.Replace(WebConfig.AddressSeparator, WebConfig.AddressSeparatorDisplay), txtCCCity.Text, StateV1.CA, CountryV1.US, txtCCZipCode.Text, _presenter.View.Telephone.ToString(), txtEmailAddress.Text.Trim(), HttpContext.Current.Request.UserHostAddress.ToString(), out confirmationId, out errorMesg, out _transaction);
                        }
                        else
                        {
                            //for decimal case
                            sBeanStreamResponce = objPay.PayYourBill(TributePortalSecurity.Security.DecryptSymmetric(this._presenter.View.CreditCardNo), txtCCVerification.Text, int.Parse(ddlCCMonth.SelectedValue), int.Parse(txtCCYear.Text), Couponamount, SelectCreditCardType(), txtCCName.Text.Trim(), "", _presenter.View.Address.Replace(WebConfig.AddressSeparator, WebConfig.AddressSeparatorDisplay), txtCCCity.Text, StateV1.CA, CountryV1.US, txtCCZipCode.Text, _presenter.View.Telephone.ToString(), txtEmailAddress.Text.Trim(), HttpContext.Current.Request.UserHostAddress.ToString(), out confirmationId, out errorMesg, out _transaction);
                        }
                    }
                    else
                    {
                        _transaction = true;
                        confirmationId = "";
                    }
                }
                catch (ApplicationException ex)
                {
                    throw ex;
                }
            }

            #region TransactionTrue
            if (_transaction)
            {
                Application["Identity"] = (System.Decimal)_presenter.CreateTribute();

                bool resultSubscribe = AddMailChimpSubscriber(PackageId);
                if (int.Parse(Application["Identity"].ToString()) > 0)
                {
                    if (Request.QueryString["VideoTributeId"] != null)
                    {
                        _presenter.LinkVideoTribute(int.Parse(Request.QueryString["VideoTributeId"]), int.Parse(Application["Identity"].ToString()));
                    }

                    #region NewUpdatedCredit
                    if ((objSessionmail.UserType == 2) && (_accountType > 1))
                    {
                        //make a fresh entry for New Credit Points in CreditPointTransaction table
                        _presenter.GetCreditPointCount();
                        if (PnlPaymentDetails.Visible == true)
                        {
                            if (_accountType == 2)
                            {
                                if (rdoMembershipYearly.Checked)
                                {
                                    NewUpdatedCredit = double.Parse(Session["CreditPointSelected"].ToString()) + _NetCreditCount - double.Parse(WebConfig.PhotoYearlyCreditCost.Substring(0, 2).Trim());
                                    double.TryParse(WebConfig.PhotoOneyearAmount.Substring(1, 5).Trim(), out totalValue);
                                }
                                else if (rdoMembershipLifetime.Checked)
                                {
                                    NewUpdatedCredit = double.Parse(Session["CreditPointSelected"].ToString()) + _NetCreditCount - double.Parse(WebConfig.PhotoLifeTimeCreditCost.Substring(0, 2).Trim());
                                    double.TryParse(WebConfig.PhotoLifeTimeAmount.Substring(1, 5).Trim(), out totalValue);
                                }
                            }
                            else if (_accountType == 3)
                            {
                                if (rdoMembershipYearly.Checked)
                                {
                                    NewUpdatedCredit = double.Parse(Session["CreditPointSelected"].ToString()) + _NetCreditCount - double.Parse(WebConfig.TributeYearlyCreditCost.Substring(0, 2).Trim());
                                    double.TryParse(WebConfig.TributeOneyearAmount.Substring(1, 5).Trim(), out totalValue);
                                }
                                else if (rdoMembershipLifetime.Checked)
                                {
                                    NewUpdatedCredit = double.Parse(Session["CreditPointSelected"].ToString()) + _NetCreditCount - double.Parse(WebConfig.TributeLifeTimeCreditCost.Substring(0, 2).Trim());
                                    double.TryParse(WebConfig.TributeLifeTimeAmount.Substring(1, 5).Trim(), out totalValue);
                                }
                            }
                        }
                        else
                        {
                            if (_accountType == 2)
                            {
                                if (rdoMembershipYearly.Checked)
                                {
                                    NewUpdatedCredit = _NetCreditCount - double.Parse(WebConfig.PhotoYearlyCreditCost.Substring(0, 2).Trim());
                                    double.TryParse(WebConfig.PhotoOneyearAmount.Substring(1, 5).Trim(), out totalValue);
                                }
                                else if (rdoMembershipLifetime.Checked)
                                {
                                    NewUpdatedCredit = _NetCreditCount - double.Parse(WebConfig.PhotoLifeTimeCreditCost.Substring(0, 2).Trim());
                                    double.TryParse(WebConfig.PhotoLifeTimeAmount.Substring(1, 5).Trim(), out totalValue);
                                }
                            }
                            else if (_accountType == 3)
                            {
                                if (rdoMembershipYearly.Checked)
                                {
                                    NewUpdatedCredit = _NetCreditCount - double.Parse(WebConfig.TributeYearlyCreditCost.Substring(0, 2).Trim());
                                    double.TryParse(WebConfig.TributeOneyearAmount.Substring(1, 5).Trim(), out totalValue);
                                }
                                else if (rdoMembershipLifetime.Checked)
                                {
                                    NewUpdatedCredit = _NetCreditCount - double.Parse(WebConfig.TributeLifeTimeCreditCost.Substring(0, 2).Trim());
                                    double.TryParse(WebConfig.TributeLifeTimeAmount.Substring(1, 5).Trim(), out totalValue);
                                }
                            }
                        }
                    }

                    #endregion

                    if (!string.IsNullOrEmpty(txtCouponCode.Text))
                        this._presenter.UpdateUsedCouponDetails(txtCouponCode.Text);

                    #region Package specification
                    if ((PackageId == 8) || (PackageId == 3))
                    {
                        //to get the information abt the payment package used
                        _presenter.TriputePackageInfo(int.Parse(Application["Identity"].ToString()));
                    }
                    StateManager objtributeType = StateManager.Instance;
                    if (objtributeType.Get("TributeType", StateManager.State.Session) != null)
                        _Themename = objtributeType.Get("TributeType", StateManager.State.Session).ToString();
                    else
                        RedirectToLoginPage();

                    Tributes objTribute = new Tributes();
                    objTribute.TributeId = int.Parse(Application["Identity"].ToString());
                    objTribute.TributeName = txtTributeName.Text;
                    objTribute.TypeDescription = _Themename;
                    objTribute.CreatedDate = DateTime.Today;
                    objTribute.TributeUrl = this._presenter.View.TributeUrl;
                    TributesPortal.Utilities.StateManager stateManager = TributesPortal.Utilities.StateManager.Instance;
                    stateManager.Add("TributeSession", objTribute, TributesPortal.Utilities.StateManager.State.Session);

                    //Insert CCDetails
                    if ((PnlPaymentDetails.Visible == true) && (_accountType > 1))
                    {
                        CCIdentity = _presenter.InsertCCDetails((SessionValue)statemail.Get("objSessionvalue", StateManager.State.Session), objTribute);
                    }

                    this._presenter.InsertPackageDetails(Application["Identity"].ToString(), CCIdentity.ToString(), confirmationId);

                    if ((PnlPaymentDetails.Visible == true) && (objSessionmail.UserType == 1) && (_accountType > 1))
                    {
                        //send sponsor email
                        _presenter.SendSponsorTransactionEmail(confirmationId);
                    }
                    //updating credits and sending mail.
                    if ((objSessionmail.UserType == 2) && (_accountType > 1))
                    {
                        // Make an entry for new credits points attained by the user if the new updated credit is more than 0
                        if (NewUpdatedCredit >= 0)
                        {
                            this._presenter.InsertCurrentCreditPoints(NewUpdatedCredit, CCIdentity.ToString(), confirmationId);

                            //to get the information abt the payment package used
                            _presenter.TriputePackageInfo(int.Parse(Application["Identity"].ToString()));

                            //If the New updated credit in the Ctreator's  is greater than or equal to 0, then only the receipt and mail should be sent
                            if (NewUpdatedCredit >= 0)
                                //to get the sponsorship receipt and send the same on Email
                                _presenter.OnViewInitialized();
                            //End

                            Master.CreditLinkButton = NewUpdatedCredit.ToString();
                        }
                    }

                    if ((PackageId == 1) || (PackageId == 4) || (PackageId == 6))
                    {
                        divPaid.Visible = true;
                        package11.InnerHtml = "The <b>" + objTribute.TributeName + "</b> " + objTribute.TypeDescription + " Tribute has a <b>lifetime</b> account and will <b>never expire</b>. <br/>";
                        package12.InnerHtml = "<br/>Your credit card will show a charge from \"YOUR TRIBUTE\" for <b>$" + AmountPaid + "</b>. Your transaction ID is <b>" + TransactionId + "</b>. <br/>";

                        package11.Visible = true;
                        package12.Visible = true;
                        package2.Visible = false;
                        trial.Visible = false;
                        autoRenew.Visible = false;
                    }
                    else if ((PackageId == 2) || (PackageId == 5) || ((PackageId == 7)))
                    {
                        divPaid.Visible = true;
                        if (rdoYearlyAutoRenew.Checked)
                        {
                            package2.InnerHtml = "The <b>" + objTribute.TributeName + "</b> " + objTribute.TypeDescription + " Tribute will automatically renew in <b>1 Year</b> on <b>" + DateTime.Now.AddMonths(12).ToString("MMMM dd, yyyy") + "</b>.<br/><br/>";
                            autoRenew.Visible = true;
                            autoRenew.InnerHtml += "<br/><p>Your credit card will show a charge from \"YOUR TRIBUTE\" for <b>$" + AmountPaid + "</b>. Your transaction ID is <b>" + TransactionId + "</b>.</P>";
                        }
                        else
                        {
                            autoRenew.Visible = false;
                            package2.InnerHtml = "The <b>" + objTribute.TributeName + "</b> " + objTribute.TypeDescription + " Tribute will expire in <b>1 Year</b> on <b>" + DateTime.Now.AddMonths(12).ToString("MMMM dd, yyyy") + "</b>.<br/><br/>";
                            //Start - Modification on 17-Dec-09 for the enhancement 1 of the Phase 1
                            //This message should be shown only when the credit card is charged
                            if (Couponamount > 0)
                                package2.InnerHtml += "<br/><p>Your credit card will show a charge from \"YOUR TRIBUTE\" for <b>$" + AmountPaid + "</b>. Your transaction ID is <b>" + TransactionId + "</b>.</P>";
                            //End
                        }

                        package2.Visible = true;
                        package11.Visible = false;
                        package12.Visible = false;
                        trial.Visible = false;
                    }
                    else
                    {
                        divPaid.Visible = false;
                        package11.Visible = false;
                        package12.Visible = false;
                        package2.Visible = false;
                        autoRenew.Visible = false;
                        recieveMail.Visible = false;
                        trial.Visible = true;
                    }
                    #endregion
                    //to create default file for url rewriting.
                    if (_Themename == "New Baby")
                        _presenter.CreateDefaultFolder(WebConfig.NewBabyFolderPath);
                    else if (_Themename == "Birthday")
                        _presenter.CreateDefaultFolder(WebConfig.BirthdayFolderPath);
                    else if (_Themename == "Graduation")
                        _presenter.CreateDefaultFolder(WebConfig.GraduationFolderPath);
                    else if (_Themename == "Wedding")
                        _presenter.CreateDefaultFolder(WebConfig.WeddingFolderPath);
                    else if (_Themename == "Anniversary")
                        _presenter.CreateDefaultFolder(WebConfig.AnniversaryFolderPath);
                    else if (_Themename == "Memorial")
                        _presenter.CreateDefaultFolder(WebConfig.MemorialFolderPath);

                    //to save video tribute if user is coming from Video Upload page
                    if (!Equals((stateManager.Get("TokenDetails", StateManager.State.Session)), null))
                    {
                        _presenter.SaveVideoTribute();
                        stateManager.Add("TokenDetails", null, StateManager.State.Session); //to set null to tokendetails session
                    }

                    // Get the Video object of the Video Tribute to save in Corresponding Memorial Tribute
                    if (Request.QueryString["VideoTributeId"] != null)
                    {
                        _presenter.SaveVideoForMemTribute(int.Parse(Request.QueryString["VideoTributeId"]));
                    }
                    objtributeType.Remove("TributeType", StateManager.State.Session);
                    _Themename = "";
                    UserID = 0;
                    retvalue = true;
                }
                else
                {
                    Exception exc = new Exception("Problem creating Tribute.");
                    throw new ApplicationException("INTERNAL", exc);//due to multiple clicks if not able to generate TributeId
                }
            }
            else
            {
                //lblErrMsg.InnerHtml = SetHeaderMessage(errorMesg, PortalValidationSummary.HeaderText);
                var sResponseArr = sBeanStreamResponce.Split('&');
                var sErrorMsg = sResponseArr.Length > 3 && sResponseArr[3].Split('=').Length > 1 && !string.IsNullOrEmpty(sResponseArr[3].Split('=')[1]) ? sResponseArr[3].Split('=')[1].Replace("+", " ") : "";
                //LHK:17-11-2011- for gracefull error message display.
                sErrorMsg = HttpUtility.UrlDecode(sErrorMsg);
                lblErrMsg.InnerHtml = SetHeaderMessage(sErrorMsg, PortalValidationSummary.HeaderText);
                lblErrMsg.Visible = true;
                retvalue = false;
            }
            SaveDefaultheme();

        }
            #endregion
        catch (Exception ex)
        {
            retvalue = false;
            if (ex.Message.StartsWith("PAYMENT"))
                throw ex;
            else
                throw new ApplicationException("INTERNAL", ex);
        }
        return retvalue;
    }
    protected void lbtnPay_Click(object sender, EventArgs e)
    {
        bool _transaction = false;
        String UserMail = string.Empty;
        string Firstname = string.Empty;
        string LastName = string.Empty;
        StateManager statemail = StateManager.Instance;
        StateManager stateTribure = StateManager.Instance;
        Tributes objTribute = (Tributes) stateTribure.Get("TributeSession", StateManager.State.Session);

        DateTime expiryDate = new DateTime();
        int cardExMonth = ddlCCMonth.SelectedIndex;
        int cardExYear = 0; // = txtCCYear.ToString();
        int.TryParse(txtCCYear.Text.ToString(), out cardExYear);

        //Phone number check
        bool IsValidPhone = false;
        bool checkPh1 = false;
        bool checkPh2 = false;
        bool checkPh3 = false;

        int TestPhoneNo = 0;
        checkPh1 = int.TryParse(txtPhoneNumber1.Text.ToString(), out TestPhoneNo);
        checkPh2 = int.TryParse(txtPhoneNumber2.Text.ToString(), out TestPhoneNo);
        checkPh3 = int.TryParse(txtPhoneNumber3.Text.ToString(), out TestPhoneNo);

        IsValidPhone = checkPh1 && checkPh2 && checkPh3;
        //Phone check till here

        DateTime currDate = DateTime.Now.Date;
        bool ValidExpiry = false;
        if ((cardExYear >= currDate.Year) && ((cardExYear == currDate.Year) ? (cardExMonth >= currDate.Month) ? true : false : true))
        {
            ValidExpiry = true;
        }

        if (((IsValidPhone) && (ValidExpiry)) || (PnlPaymentDetails.Visible == false))
        {

            if (chkAgree.Checked == true)
            {
                # region Upgrade

                try
                {
                    //check for credit card lengths
                    if (Request.Form["rdoCCType"] == "Visa" || Request.Form["rdoCCType"] == "MasterCard" || Request.Form["rdoCCType"] == "Discover")
                    {
                        if (txtCCNumber.Text.Length != 16 && txtCCVerification.Text.Length != 3)
                        {
                            ShowMessage(ValidationSummary1.HeaderText, "Transaction Failed", true);
                            return;

                        }
                    }
                    else if (Request.Form["rdoCCType"] == "Amex" && txtCCNumber.Text.Length != 15 && txtCCVerification.Text.Length != 4)
                    {
                        ShowMessage(ValidationSummary1.HeaderText, "Transaction Failed", true);
                        return;
                    }

                    int couponType = 0;
                    if (rdoPhotoMembershipLifeTime.Checked || rdoTributeMembershipLifeTime.Checked)
                        couponType = 3;
                    else
                        couponType = 2;
                    if (rdoAdminYes.Checked)
                    {
                        if (rdoHaveAccountYes.Checked)
                        {
                            if ((txtEmail.Text != string.Empty) && (txtPassword.Text != string.Empty))
                            {
                                emailPassSuccess = this._presenter.GetUserDetails(txtEmail.Text, Password, 0);
                                if (emailPassSuccess == -1)
                                {
                                    ShowMessage(ValidationSummary1.HeaderText, "Enter valid email or password", true);
                                    return;
                                }
                                flagForAdminCndtns = 1;
                            }
                            else
                            {
                                ShowMessage(ValidationSummary1.HeaderText, "Either you have not entered the email or the password", true);
                                return;
                            }
                        }
                        if (rdoHaveAccountNo.Checked)
                        {
                            if (txtEmailSignUp.Text != string.Empty)
                            {
                                _email = _presenter.EmailAvailable();
                                if (_email > 0)
                                {
                                    ShowMessage(ValidationSummary1.HeaderText, "Email you entered already exists!! Please enter a different email", true);
                                    return;
                                }
                            }

                            if ((txtEmailSignUp.Text == string.Empty) && (txtPasswordSignUp.Text == string.Empty) && (txtPasswordSignUp.Text == string.Empty) && (txtConfrmPassword.Text == string.Empty) && (txtFirstName.Text == string.Empty))
                            {
                                ShowMessage(ValidationSummary1.HeaderText, "You have not entered the complete Sign up info", true);
                                return;
                            }

                            if ((txtPasswordSignUp.Text != string.Empty) && (txtConfrmPassword.Text != string.Empty))
                            {
                                if (txtPasswordSignUp.Text != txtConfrmPassword.Text)
                                {
                                    ShowMessage(ValidationSummary1.HeaderText, "Password fields do not match", true);
                                    return;
                                }
                                if (txtPasswordSignUp.Text.Length < 6)
                                {
                                    ShowMessage(ValidationSummary1.HeaderText, "Password should be at least of 6 digits", true);
                                    return;
                                }
                            }
                            else
                            {
                                ShowMessage(ValidationSummary1.HeaderText, "Please enter password fields", true);
                                return;
                            }

                            flagForAdminCndtns = 2;
                        }
                    }

                    // Custom URL is mandatory when the upgrade
                    if (rdoTributeMembershipYearly.Checked || rdoTributeMembershipLifeTime.Checked)
                    {
                        if (txtTributeAddress.Visible == true)
                        {
                            if (txtTributeAddress.Text != string.Empty)
                            {
                                this._presenter.CheckAvailability();
                                if (int.Parse(Status) != 0)
                                {
                                    ShowMessage(ValidationSummary1.HeaderText, "Please enter a different URL", true);
                                    return;
                                }
                            }
                        }
                    }

                    if (txtCouponCode.Text != string.Empty)
                    {
                        int availability = _presenter.GetCouponAvailable(txtCouponCode.Text, couponType);

                        if (availability == 1)
                        {
                            //SetCouponAvailableStatus();
                            double Couponamount = 0;
                            if (rdoPhotoMembershipLifeTime.Checked)
                            {
                                amount = BillingTotalInDollars;
                                Couponamount = Convert.ToDouble(amount.Substring(1, amount.Length - 1));
                            }
                            else if (rdoTributeMembershipYearly.Checked)
                            {
                                amount = BillingTotalInDollars;
                                Couponamount = Convert.ToDouble(amount.Substring(1, amount.Length - 1));
                            }
                            else
                            {
                                amount = BillingTotalInDollars;
                                Couponamount = Convert.ToDouble(amount.Substring(1, amount.Length - 1));
                            }
                            if (this._presenter.View.IsPercentage == false)
                                Couponamount = Couponamount - double.Parse(this._presenter.View.Denomination);
                            else
                                Couponamount = Couponamount -
                                               ((double.Parse(this._presenter.View.Denomination)*Couponamount)/100);
                            if (Couponamount < 0)
                                Couponamount = 0;
                            //LHK; coupon amount upto 2 decimal places.
                            Couponamount = Math.Round(Couponamount, 2);
                            BillingTotal.InnerHtml = BillingTotalAbove.InnerHtml = ("$" + Couponamount.ToString());

                            //Remove Commented code for Payment Gateway :Amit :2/5/8
                            SessionValue objSessionmail =
                                (SessionValue) statemail.Get("objSessionvalue", StateManager.State.Session);
                            if (objSessionmail != null)
                            {
                                Firstname = objSessionmail.FirstName;
                                LastName = objSessionmail.LastName;
                                UserMail = objSessionmail.UserEmail;
                            }
                            PaymentGateWay objPay = new PaymentGateWay();
                            //Start - Modification on 15-Dec-09 for the enhancement 1 of the Phase 1
                            //If the bill amount (Couponamount) is greater than $0, then only the transaction should go to the payment gateway
                            if (Couponamount > 0)
                            {
                                if (Couponamount == Math.Round(Couponamount))
                                {
                                    sBeanStreamResponce = PayYourBill(TributePortalSecurity.Security.DecryptSymmetric(this._presenter.View.CreditCardNo), txtCCVerification.Text, int.Parse(ddlCCMonth.SelectedValue), int.Parse(txtCCYear.Text), Couponamount, SelectCreditCardType(), txtCCName.Text.Trim(), "", _presenter.View.Address.Replace(WebConfig.AddressSeparator, WebConfig.AddressSeparatorDisplay), txtCCCity.Text, StateV1.CA, CountryV1.US, txtCCZipCode.Text, _presenter.View.Telephone.ToString(), txtEmailAddress.Text.Trim(), HttpContext.Current.Request.UserHostAddress.ToString(), out confirmationId, out errorMesg, out _transaction);
                                }
                                else
                                {
                                    sBeanStreamResponce = PayYourBill(TributePortalSecurity.Security.DecryptSymmetric(this._presenter.View.CreditCardNo), txtCCVerification.Text, int.Parse(ddlCCMonth.SelectedValue), int.Parse(txtCCYear.Text), double.Parse(Couponamount.ToString()), SelectCreditCardType(), txtCCName.Text.Trim(), "", _presenter.View.Address.Replace(WebConfig.AddressSeparator, WebConfig.AddressSeparatorDisplay), txtCCCity.Text, StateV1.CA, CountryV1.US, txtCCZipCode.Text, _presenter.View.Telephone.ToString(), txtEmailAddress.Text.Trim(), HttpContext.Current.Request.UserHostAddress.ToString(), out confirmationId, out errorMesg, out _transaction);
                                }
                            }
                            else
                                _transaction = true;
                            //End

                            if (_transaction)
                            {
                                if (!Equals(objTribute, null))
                                {
                                    _TribureId = objTribute.TributeId;
                                    _tributeUrl = objTribute.TributeUrl;
                                    _tributeType = objTribute.TypeDescription;
                                    this._presenter.TriputePackageInfo(TributeId);
                                    if (PnlPaymentDetails.Visible == true)
                                    {
                                        this._presenter.InsertCCDetails((SessionValue)statemail.Get("objSessionvalue", StateManager.State.Session), objTribute, confirmationId, SponsorNameandMsgForEmail);
                                    }
                                    else
                                    {
                                        //MG using 100% coupon off
                                        this._presenter.SendSponsorEmailOnFreeUpgrade((SessionValue)statemail.Get("objSessionvalue", StateManager.State.Session), objTribute, confirmationId, SponsorNameandMsgForEmail);
                                        this._presenter.InsertPackageDetails(objTribute.TributeId, 0, confirmationId);
                                    }
                                }

                                linkedVideoTributeId = this._presenter.GetLinkedVideoTributeId(objTribute.TributeId, UserID);
                                _videoTributeOwnerid = _presenter.GetUserIdByTributeId(linkedVideoTributeId);

                                if (linkedVideoTributeId > 0 && _videoTributeOwnerid != UserID)
                                {
                                    _presenter.UpdateCreditPointOfVideoTributeOwner(_videoTributeOwnerid);
                                }

                                if (flagForAdminCndtns == 1)
                                {
                                    if ((txtEmail.Text != string.Empty) || (txtPassword.Text != string.Empty))
                                    {
                                        emailPassSuccess = this._presenter.GetUserDetails(txtEmail.Text, Password, _TribureId);
                                        SendEmailtoNewAdmin();
                                    }
                                    else
                                    {
                                        ShowMessage(ValidationSummary1.HeaderText, "Please enter both email and password", true);
                                    }
                                }
                                else if (flagForAdminCndtns == 2)
                                {
                                    if (_email == 0)
                                    {
                                        UserRegistration objUserReg = SaveAccount();
                                        _presenter.SavePersonalAccount(objUserReg);
                                        emailPassSuccess = this._presenter.GetUserDetails(txtEmailSignUp.Text, Password, _TribureId);
                                        SendEmailtoNewAdmin();
                                    }
                                }

                                if (rdoTributeMembershipLifeTime.Checked || rdoTributeMembershipYearly.Checked)
                                {
                                    if (rdoChangeAddressYes.Checked)
                                    {
                                        if (TributeURL != null)
                                        {
                                            this._presenter.UpdateTributeURL(_TribureId, TributeURL);
                                            CreateFoldersForNewTributeUrl(_TribureId, OldTributeURL, TributeURL, _tributeType);
                                        }
                                    }
                                }

                                if (!string.IsNullOrEmpty(txtCouponCode.Text))
                                    this._presenter.UpdateUsedCouponDetails(txtCouponCode.Text);

                                SetDefault();
                                if (Request.QueryString["PageName"] == "AdminMytributesPrivacy")
                                {
                                    Response.Redirect(Session["APP_BASE_DOMAIN"] + objTribute.TributeUrl + "/paymentconfirmation.aspx?tid=" + _tributPackageId.ToString() + "&PageName=" + Request.QueryString["PageName"].ToString(), false);
                                }
                                else
                                {
                                    try
                                    {
                                        //Start - Modification on 16-Dec-09 for the enhancement 1 of the Phase 1
                                        //If the amount is zero the application is redirected to the Tribute page
                                        if (Couponamount == 0)
                                            Response.Redirect(Session["APP_BASE_DOMAIN"] + objTribute.TributeUrl + "/", false);
                                        //End
                                        if (WebConfig.ApplicationMode.ToLower() == "local")
                                        {
                                            Response.Redirect(
                                                Session["APP_BASE_DOMAIN"] + objTribute.TributeUrl +
                                                "/paymentconfirmation.aspx?tid=" + _tributPackageId.ToString(), false);
                                        }
                                        else
                                        {
                                            Response.Redirect(
                                                "http://" +
                                                this._presenter.View.SubDomain.Replace("New Baby", "newbaby").ToLower() +
                                                "." + WebConfig.TopLevelDomain + "/" + objTribute.TributeUrl +
                                                "/paymentconfirmation.aspx?tid=" + _tributPackageId.ToString(),false);
                                        }

                                    }
                                    catch (Exception po)
                                    {
                                    }
                                }

                                bool result = AddMailChimpSubscriber(initailPackageId, getPackageId);
                            }
                            else
                            {
                                var sResponseArr = sBeanStreamResponce.Split('&');
                                var sErrorMsg = sResponseArr.Length > 3 && sResponseArr[3].Split('=').Length > 1 && !string.IsNullOrEmpty(sResponseArr[3].Split('=')[1]) ? sResponseArr[3].Split('=')[1].Replace("+", " ") : "";
                                //LHK:17-11-2011- for gracefull error message display.
                                sErrorMsg = HttpUtility.UrlDecode(sErrorMsg);
                                ShowMessage(ValidationSummary1.HeaderText, sErrorMsg, true);

                            }
                        }
                        else
                        {
                            if (txtCouponCode.Text != string.Empty)
                            {
                                SetCouponUnAvailableStatus();
                            }
                        }
                    }
                    else
                    {
                        double Couponamount = 0;

                        amount = BillingTotal.InnerHtml;
                        Couponamount = Convert.ToDouble(amount.Substring(1, amount.Length - 1));
                        BillingTotal.InnerHtml = BillingTotalAbove.InnerHtml = amount;

                        //Remove Commented code for Payment Gateway :Amit :2/5/8
                        SessionValue objSessionmail = (SessionValue)statemail.Get("objSessionvalue", StateManager.State.Session);
                        if (objSessionmail != null)
                        {
                            Firstname = objSessionmail.FirstName;
                            LastName = objSessionmail.LastName;
                            UserMail = objSessionmail.UserEmail;
                        }
                        PaymentGateWay objPay = new PaymentGateWay();
                        if (Couponamount == Math.Round(Couponamount))
                        {
                            sBeanStreamResponce = objPay.PayYourBill(TributePortalSecurity.Security.DecryptSymmetric(this._presenter.View.CreditCardNo), txtCCVerification.Text, int.Parse(ddlCCMonth.SelectedValue), int.Parse(txtCCYear.Text), Couponamount, SelectCreditCardType(), txtCCName.Text, "", _presenter.View.Address.Replace(WebConfig.AddressSeparator, WebConfig.AddressSeparatorDisplay), txtCCCity.Text, StateV1.CA, CountryV1.US, txtCCZipCode.Text, _presenter.View.Telephone.ToString(), txtEmailAddress.Text.Trim(), HttpContext.Current.Request.UserHostAddress.ToString(), out confirmationId, out errorMesg, out _transaction);
                        }
                        else
                        {
                            sBeanStreamResponce = objPay.PayYourBill(TributePortalSecurity.Security.DecryptSymmetric(this._presenter.View.CreditCardNo), txtCCVerification.Text, int.Parse(ddlCCMonth.SelectedValue), int.Parse(txtCCYear.Text), double.Parse(Couponamount.ToString()), SelectCreditCardType(), txtCCName.Text, "", _presenter.View.Address.Replace(WebConfig.AddressSeparator, WebConfig.AddressSeparatorDisplay), txtCCCity.Text, StateV1.CA, CountryV1.US, txtCCZipCode.Text, _presenter.View.Telephone.ToString(), txtEmailAddress.Text.Trim(), HttpContext.Current.Request.UserHostAddress.ToString(), out confirmationId, out errorMesg, out _transaction);
                        }

                        if (_transaction)
                        {
                            #region Transaction True

                            if (!Equals(objTribute, null))
                            {
                                _TribureId = objTribute.TributeId;
                                _tributeUrl = objTribute.TributeUrl;
                                _tributeType = objTribute.TypeDescription;
                                this._presenter.TriputePackageInfo(TributeId);
                                this._presenter.InsertCCDetails((SessionValue)statemail.Get("objSessionvalue", StateManager.State.Session), objTribute, confirmationId, SponsorNameandMsgForEmail);
                            }

                            linkedVideoTributeId = this._presenter.GetLinkedVideoTributeId(objTribute.TributeId, UserID);
                            _videoTributeOwnerid = _presenter.GetUserIdByTributeId(linkedVideoTributeId);

                            if (linkedVideoTributeId > 0 && _videoTributeOwnerid != UserID)
                            {

                                _presenter.UpdateCreditPointOfVideoTributeOwner(_videoTributeOwnerid);
                            }

                            if (flagForAdminCndtns == 1)
                            {
                                if ((txtEmail.Text != string.Empty) || (txtPassword.Text != string.Empty))
                                {
                                    emailPassSuccess = this._presenter.GetUserDetails(txtEmail.Text, Password, _TribureId);
                                    SendEmailtoNewAdmin();
                                }
                                else
                                {
                                    ShowMessage(ValidationSummary1.HeaderText, "Please enter both email and password", true);
                                }
                            }
                            else if (flagForAdminCndtns == 2)
                            {
                                if (_email == 0)
                                {
                                    UserRegistration objUserReg = SaveAccount();
                                    _presenter.SavePersonalAccount(objUserReg);
                                    emailPassSuccess = this._presenter.GetUserDetails(txtEmailSignUp.Text, Password, _TribureId);
                                    SendEmailtoNewAdmin();
                                }
                            }

                            if (rdoTributeMembershipLifeTime.Checked || rdoTributeMembershipYearly.Checked)
                            {

                                if (rdoChangeAddressYes.Checked)
                                {
                                    if (TributeURL != null)
                                    {
                                        this._presenter.UpdateTributeURL(_TribureId, TributeURL);
                                        //Copying all the data of existing TributeUrl for new TributeURL
                                        CreateFoldersForNewTributeUrl(_TribureId, OldTributeURL, TributeURL, _tributeType);
                                    }
                                }
                            }
                            SetDefault();
                            if (Request.QueryString["PageName"] == "AdminMytributesPrivacy")
                            {
                                Response.Redirect(Session["APP_BASE_DOMAIN"] + objTribute.TributeUrl + "/paymentconfirmation.aspx?tid=" + _tributPackageId.ToString() + "&PageName=" + Request.QueryString["PageName"].ToString(), false);
                            }
                            else
                            {
                                try
                                {
                                    if (WebConfig.ApplicationMode.ToLower() == "local")
                                    {
                                        Response.Redirect(
                                            Session["APP_BASE_DOMAIN"] + objTribute.TributeUrl +
                                            "/paymentconfirmation.aspx?tid=" + _tributPackageId.ToString(), false);
                                    }
                                    else
                                    {
                                        Response.Redirect(
                                            "http://" +
                                            _tributeType.Replace("New Baby", "newbaby").ToLower() +
                                            "." + WebConfig.TopLevelDomain + "/" + _tributeUrl +
                                            "/paymentconfirmation.aspx?tid=" + _tributPackageId.ToString(),false);
                                    }
                                }
                                catch (Exception abc)
                                {
                                }
                            }
                        }
                        else
                        {
                            //ShowMessage(ValidationSummary1.HeaderText, errorMesg, true);
                            var sResponseArr = sBeanStreamResponce.Split('&');
                            var sErrorMsg = sResponseArr.Length > 3 && sResponseArr[3].Split('=').Length > 1 && !string.IsNullOrEmpty(sResponseArr[3].Split('=')[1]) ? sResponseArr[3].Split('=')[1].Replace("+", " ") : "";

                            sErrorMsg = HttpUtility.UrlDecode(sErrorMsg);

                            ShowMessage(ValidationSummary1.HeaderText, sErrorMsg, true);
                        }

                        #endregion
                    }

                }
                catch (Exception excep)
                {
                    if (excep.Message.StartsWith("PAYMENT"))
                        ShowMessage(ValidationSummary1.HeaderText, "Transaction Failed! An error has occured while trying to connect to the payment gateway. Please try later.", true);
                    else
                        ShowMessage(ValidationSummary1.HeaderText, "Transaction Failed! While your transaction was successful and your credit card was charged but we could not process it at our end. Please contact the webmaster.", true);
                }
                # endregion
            }
            else
            {
                ShowMessage(ValidationSummary1.HeaderText, "Please accept that you have read and agree to the terms of use, cancellation/refund policy and the privacy policy.", true);
                ErrorAccept.Visible = true;
            }
        }