protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                Session["adsRemaining"] = false;
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Info", "$( '#tabs' ).tabs({ disabled: [1, 2] });", true);
                //FillYearsDdl();
                VehiclesBilling CurrentBilling = new VehiclesBilling();
                if (Usr.CustomerType == "Business")
                {
                    CurrentBilling = VehiclesBilling.RemainingVehicleAdsBillingDetails(Usr.Id);
                    if (CurrentBilling != null)
                    {
                        Session["CurrentBilling"] = CurrentBilling;
                        if (CurrentBilling.AdsRemaining > 0)
                        {
                            Session["adsRemaining"] = true;
                        }

                        ltlRemaining.Text = string.Concat("<p class='text-info bold'>You have ", CurrentBilling.AdsRemaining, " out of ", CurrentBilling.AdsBought, " ads remaining.</p>");
                    }
                    else
                    {
                        ltlRemaining.Text = string.Empty;
                    }
                }
            }
        }
        protected void GetPaid(string itemType, string aditem, string amnt, CreditCardDetailsType cc)
        {
            HttpContext CurrContext = HttpContext.Current;

            //amnt = "1.00";
            try
            {
                DoDirectPaymentResponseType reply = DirectPayment.DoDirectPaymentAPIOperation(cc, amnt);
                Session["Reply"]       = reply;
                Session["PaymentInfo"] = cc;
                if (reply.Ack.ToString().Trim().ToUpper().Equals("SUCCESS"))
                {
                    switch (itemType)
                    {
                    case "car":
                        VehiclesBilling vb = Session["VehicleBilling"] as VehiclesBilling;
                        vb.PayPalId    = reply.TransactionID;
                        vb.PayPalState = reply.Ack.ToString();
                        vb.CreateTime  = Convert.ToDateTime(reply.Timestamp);
                        if (VehiclesBilling.PaidInFull(vb))
                        {
                            CustomerVehicleInfo.UpdateBillingId(Convert.ToInt32(Session["VehicleId"]), vb.Id);
                            NotifyCustomer(Convert.ToInt32(Session["VehicleId"]), itemType, vb.Payment, "0", reply.TransactionID);
                            NotifyAdmin(Request.QueryString["item"], vb.Payment, "0", reply.TransactionID);
                        }
                        break;

                    case "ad":
                        AdsBilling ad = new AdsBilling
                        {
                            CustomerId  = Convert.ToInt32(Session["CustomerId"]),
                            AdId        = Convert.ToInt32(Request.QueryString["id"]),
                            Payment     = Convert.ToDouble(amnt),
                            PayPalId    = reply.TransactionID,
                            PayPalState = reply.Ack.ToString(),
                            CreateTime  = Convert.ToDateTime(reply.Timestamp)
                        };
                        if (AdsBilling.InsertNewBilling(ad))
                        {
                            CustomerAd.PaidInFull(ad.AdId);
                            NotifyCustomer(ad.AdId, itemType, ad.Payment, "0", reply.TransactionID);
                            NotifyAdmin(Request.QueryString["item"], ad.Payment, "0", reply.TransactionID);
                        }
                        break;
                    }
                }
                else
                {
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Error", " alert('Transaction failed, please check your credit card information and try again.');", true);
                    //Server.Transfer("~/account/PaymentResponse.aspx");
                }
            }
            catch (WebException ex)
            {
                CurrContext.Items.Add("Error", ex.Message);
                ErrorHandler.writeExceptionToLogFile(ex);
            }
        }
        private void UpdateBillingAdmin(int VehicleId)
        {
            VehiclesBilling vb = Session["VehicleBilling"] as VehiclesBilling;

            vb.PayPalId    = "Ad by admin";
            vb.PayPalState = "SUCCESS";
            vb.CreateTime  = DateTime.Now;
            if (VehiclesBilling.PaidInFull(vb))
            {
                if (CustomerVehicleInfo.UpdateBillingId(VehicleId, vb.Id))
                {
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Success", " alert('You have completed posting a vehicle/item ad for a customer.');", true);
                }
            }
        }
        protected void BtnDecline_Click(object sender, EventArgs e)
        {
            CustomerVehicleInfo v  = Session["CurrentVehicle"] as CustomerVehicleInfo;
            VehiclesBilling     vb = VehiclesBilling.GetVehiclesBillingDetails(v.BillingId);

            vb.AdsRemaining += 1;
            if (CustomerVehicleInfo.DeclineItem(Convert.ToInt32(Request.QueryString["id"])))
            {
                bool remainingUpdated = VehiclesBilling.UpdateBilling(vb);
                AdDeclined(Convert.ToInt32(Session["Seller"].ToString()), v);
                Response.Redirect("~/admin/vehicles.aspx");
            }
            else
            {
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Error", "alert('Failed declining ad #" + Request.QueryString["id"] + ".');", true);
            }
        }
        protected void NotifyCustomer(Customer c, VehiclesBilling vb, int itemId)
        {
            StringBuilder msg = new StringBuilder();

            int remaininAds = vb.AdsBought - vb.AdsRemaining;

            msg.Append(string.Concat("<p>Hi ", c.FirstName, ",</p>"));
            msg.Append("<p>Thanks for placing an ad with emonthlies.com. Just one more step to verify your ad. ");
            msg.Append(string.Concat("<a href='https://www.emonthlies.com/confirmad.aspx?item=car", "&id=", itemId, "'>"));
            msg.Append("Confirm your ad</a>. We will approve your ad in 12 - 24 hours.</p>");
            msg.Append(string.Concat("<p>You have used ", remaininAds, " ads out of ", vb.AdsBought, " purchased.</p>"));
            msg.Append("<p>This posting is valid for 90 days and will automatically discontinue. ");
            msg.Append("<p>Thanks for your business,<br />Your emonthlies sales team</p>");
            if (Mailer.SendMail2Client(c.Email, msg.ToString(), "Confirm your ad") == false)
            {
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "info", " alert('We could not send you an email to verify your ad at this time.');", true);
            }
        }
        protected void AdDeclined(int CustomerId, CustomerVehicleInfo v)
        {
            Customer        customer = Customer.GetCustomerDetails(CustomerId);
            VehiclesBilling vb       = VehiclesBilling.GetVehiclesBillingDetails(v.BillingId);
            StringBuilder   msg      = new StringBuilder();

            msg.Append(string.Concat("<p>RE: Your ad for ", v.ModelYear, " ", v.Manufacturer, " ", v.Model, "</p>"));
            msg.Append("<p>Hi " + customer.FirstName + ",</p>");
            msg.Append("<p>Your ad has not been placed. It does not comply with emonthlies' advertising policies.</p>");
            if (vb.PromoCode == "")
            {
                msg.Append(string.Concat("You have ", vb.AdsRemaining, " out of ", vb.AdsBought, " ads remaining in your account."));
            }
            msg.Append("<p>Thanks for your patronage,<br />emonthlies</p>");
            if (Mailer.SendMail2Client(customer.Email, msg.ToString(), "Ad info") == false)
            {
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "info", " alert('Customer could not be notified.');", true);
            }
        }
        private void DoCheckout()
        {
            CustomerVehicleInfo    vi = (CustomerVehicleInfo)Session["VehicleInfo"];
            List <VehicleFeatures> vf = (List <VehicleFeatures>)Session["VehicleFeatures"];
            Financial fin             = (Financial)Session["FinancialInfo"];
            //Customer usr = (Customer)Session["User"];
            VehiclesBilling vb = new VehiclesBilling
            {
                CustomerId = Usr.Id
            };

            if (Session["Role"].ToString() == "admin")
            {
                vb.Payment   = 0.99;
                vb.AdsBought = 1;
            }
            else
            {
                if (Usr.CustomerType == "Business")
                {
                    vb.AdsBought = Convert.ToInt16(rblPricing.SelectedValue);
                    switch (rblPricing.SelectedValue)
                    {
                    case "1":
                        vb.Payment = 19.99;
                        break;

                    case "8":
                        vb.Payment      = 89.99;
                        vb.AdsRemaining = 7;
                        break;

                    case "20":
                        vb.Payment      = 199.99;
                        vb.AdsRemaining = 19;
                        break;
                    }
                }
                else
                {
                    vb.Payment   = 0.99;
                    vb.AdsBought = 1;
                }
            }
            vb.PromoCode = string.Empty;
            int billingId = VehiclesBilling.InsertNewBilling(vb);

            vb.Id = billingId;
            if (billingId > 0)
            {
                Session["VehicleBilling"] = vb;
                if (Session["Role"].ToString() == "admin")
                {
                    UpdateBillingAdmin(vi.Id);
                    Response.Redirect("~/admin/vehicles.aspx");
                }
                else
                {
                    Response.Redirect("CheckOut.aspx?item=car&size=" + vb.AdsBought + "&adtype=" + Usr.CustomerType + "&promo=" + BoolToInt(IsPromo) + "&id=" + billingId);
                }
            }
            else
            {
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Error", " alert('Failed inserting billing informtation.');", true);
            }
        }
        protected void BtnSaveImages_Click(object sender, EventArgs e)
        {
            string err = ImageErr();

            if (err != string.Empty)
            {
                pnlErr.Visible = true;
                lblErr.Text    = "<ul>" + err + "</ul><p>Please upload files with correct file-formats.</p>";
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Complete", "$( '#tabs' ).tabs({ active: 2 });", true);
                return;
            }
            HttpFileCollection     files = Request.Files;
            CustomerVehicleInfo    vi    = (CustomerVehicleInfo)Session["VehicleInfo"];
            List <VehicleFeatures> vf    = (List <VehicleFeatures>)Session["VehicleFeatures"];
            Financial    fin             = (Financial)Session["FinancialInfo"];
            VehicleImage imgs            = new VehicleImage();
            int          VehicleId       = CustomerVehicleInfo.InsertNewCustomerVehicleInfo(vi);
            //Customer usr = (Customer)Session["User"];
            string path = Usr.Id + "_v" + VehicleId;
            bool   featuresok;

            string[] allowedExtension = { ".jpeg", ".jpg", ".png", ".gif" };
            string[] videoExtensions  = { ".avi", ".mov", ".wmv", ".mp4", ".mpg" };
#pragma warning disable CS0219 // Variable is assigned but its value is never used
            bool biWeeklyPosted = false;
#pragma warning restore CS0219 // Variable is assigned but its value is never used

            if (VehicleId > 0)
            {
                vi.Id = VehicleId;
                Session["VehicleInfo"] = vi;
                Session["VehicleId"]   = VehicleId;
                featuresok             = InsertFeatures(vf, VehicleId);
                if (!featuresok)
                {
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Error", "alert('Error adding vehicle features.');", true);
                    return;
                }
                fin.VehicleId = VehicleId;
                int fid = Financial.InsertNewFinancialDetails(fin);
                if (fid > 0)
                {
                    if (pnlBiWeekly.Visible)
                    {
                        fin.Id             = 0;
                        fin.PaymentCycle   = "Bi-weekly";
                        fin.PaymentWithTax = Convert.ToDouble(txtBiWeeklyWithTax.Text);
                        int bwfid = Financial.InsertNewFinancialDetails(fin);
                        if (bwfid > 0)
                        {
                            biWeeklyPosted = true;
                        }
                    }
                    imgs.VehicleId = VehicleId;
                    imgs.ImgPath   = path;
                    if (FileUpload1.HasFile)
                    {
                        imgs.Img1 = @"/imgs/" + path + "/" + Helpers.RemoveInvalidChars(Path.GetFileName(FileUpload1.PostedFile.FileName));
                    }
                    if (FileUpload2.HasFile)
                    {
                        imgs.Img2 = @"/imgs/" + path + "/" + Helpers.RemoveInvalidChars(Path.GetFileName(FileUpload2.PostedFile.FileName));
                    }
                    ;
                    if (FileUpload3.HasFile)
                    {
                        imgs.Img3 = @"/imgs/" + path + "/" + Helpers.RemoveInvalidChars(Path.GetFileName(FileUpload3.PostedFile.FileName));
                    }
                    ;
                    if (FileUpload4.HasFile)
                    {
                        imgs.Img4 = @"/imgs/" + path + "/" + Helpers.RemoveInvalidChars(Path.GetFileName(FileUpload4.PostedFile.FileName));
                    }
                    ;
                    if (FileUpload5.HasFile)
                    {
                        imgs.Img5 = @"/imgs/" + path + "/" + Helpers.RemoveInvalidChars(Path.GetFileName(FileUpload5.PostedFile.FileName));
                    }
                    ;
                    if (FileUpload6.HasFile)
                    {
                        imgs.Img6 = @"/imgs/" + path + "/" + Helpers.RemoveInvalidChars(Path.GetFileName(FileUpload6.PostedFile.FileName));
                    }
                    ;
                    if (FileUpload7.HasFile)
                    {
                        imgs.Img7 = @"/imgs/" + path + "/" + Helpers.RemoveInvalidChars(Path.GetFileName(FileUpload7.PostedFile.FileName));
                    }
                    ;
                    if (FileUpload8.HasFile)
                    {
                        imgs.Img8 = @"/imgs/" + path + "/" + Helpers.RemoveInvalidChars(Path.GetFileName(FileUpload8.PostedFile.FileName));
                    }
                    ;
                    if (FileUpload10.HasFile)
                    {
                        imgs.Img9 = @"/imgs/" + path + "/" + Helpers.RemoveInvalidChars(Path.GetFileName(FileUpload10.PostedFile.FileName));
                    }
                    ;
                    if (FileUpload11.HasFile)
                    {
                        imgs.Img10 = @"/imgs/" + path + "/" + Helpers.RemoveInvalidChars(Path.GetFileName(FileUpload11.PostedFile.FileName));
                    }
                    ;
                    if (FileUpload12.HasFile)
                    {
                        imgs.Img11 = @"/imgs/" + path + "/" + Helpers.RemoveInvalidChars(Path.GetFileName(FileUpload12.PostedFile.FileName));
                    }
                    ;
                    if (FileUpload13.HasFile)
                    {
                        imgs.Img12 = @"/imgs/" + path + "/" + Helpers.RemoveInvalidChars(Path.GetFileName(FileUpload13.PostedFile.FileName));
                    }
                    ;
                    if (FileUpload14.HasFile)
                    {
                        imgs.Img13 = @"/imgs/" + path + "/" + Helpers.RemoveInvalidChars(Path.GetFileName(FileUpload14.PostedFile.FileName));
                    }
                    ;
                    if (FileUpload15.HasFile)
                    {
                        imgs.Img14 = @"/imgs/" + path + "/" + Helpers.RemoveInvalidChars(Path.GetFileName(FileUpload15.PostedFile.FileName));
                    }
                    ;
                    if (FileUpload16.HasFile)
                    {
                        imgs.Img15 = @"/imgs/" + path + "/" + Helpers.RemoveInvalidChars(Path.GetFileName(FileUpload16.PostedFile.FileName));
                    }
                    ;
                    if (FileUpload17.HasFile)
                    {
                        imgs.Img16 = @"/imgs/" + path + "/" + Helpers.RemoveInvalidChars(Path.GetFileName(FileUpload17.PostedFile.FileName));
                    }
                    ;
                    if (FileUpload18.HasFile)
                    {
                        imgs.Img17 = @"/imgs/" + path + "/" + Helpers.RemoveInvalidChars(Path.GetFileName(FileUpload18.PostedFile.FileName));
                    }
                    ;
                    if (FileUpload19.HasFile)
                    {
                        imgs.Img18 = @"/imgs/" + path + "/" + Helpers.RemoveInvalidChars(Path.GetFileName(FileUpload19.PostedFile.FileName));
                    }
                    ;
                    if (FileUpload20.HasFile)
                    {
                        imgs.Img19 = @"/imgs/" + path + "/" + Helpers.RemoveInvalidChars(Path.GetFileName(FileUpload20.PostedFile.FileName));
                    }
                    ;
                    if (FileUpload21.HasFile)
                    {
                        imgs.Img20 = @"/imgs/" + path + "/" + Helpers.RemoveInvalidChars(Path.GetFileName(FileUpload21.PostedFile.FileName));
                    }
                    ;

                    if (ddlVideoSource.SelectedIndex == 1)
                    {
                        if (FileUpload9.HasFile)
                        {
                            imgs.Video       = @"/imgs/" + path + "/" + Helpers.RemoveInvalidChars(Path.GetFileName(FileUpload9.PostedFile.FileName));
                            imgs.VideoFormat = FileUpload9.PostedFile.ContentType;
                        }
                    }
                    Session["Images"] = imgs;

                    bool filesuploaded = false;
                    try
                    {
                        if (files.Count > 0)
                        {
                            Directory.SetCurrentDirectory(Server.MapPath("~/imgs"));
                            if (!Directory.Exists(path))
                            {
                                Directory.CreateDirectory(path);
                            }
                            for (var i = 0; i < files.Count; i++)
                            {
                                if (files[i].FileName == "")
                                {
                                    continue;
                                }
                                if (allowedExtension.Contains(Path.GetExtension(files[i].FileName)))
                                {
                                    HttpPostedFile pf        = files[i];
                                    string         filetoput = Server.MapPath("~/imgs/" + path + "/" + Helpers.RemoveInvalidChars(Path.GetFileName(files[i].FileName)));
                                    SaveFile(pf, filetoput);
                                }
                            }
                        }
                        filesuploaded = VehicleImage.InsertNewVehicleImage(imgs);
                    }
                    catch (Exception ex)
                    {
                        ErrorHandler.writeExceptionToLogFile(ex);
                        ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Error", "alert('Pictures could not be uploaded.');", true);
                        filesuploaded = false;
                    }
                    if (filesuploaded)
                    {
                        VehiclesBilling vb = Session["CurrentBilling"] as VehiclesBilling;
                        pnlDetails.Visible = false;
                        if (Session["Role"].ToString() == "admin")
                        {
                            DoCheckout();
                        }
                        else
                        {
                            if (Usr.CustomerType == "Business")
                            {
                                if ((bool)Session["adsRemaining"] == false)
                                {
                                    pnlCheckout.Visible = true;
                                }
                                else
                                {
                                    pnlCheckout.Visible = false;
                                    vb.AdsRemaining    -= 1;
                                    if (VehiclesBilling.UpdateBilling(vb))
                                    {
                                        if (CustomerVehicleInfo.UpdateBillingId(vi.Id, vb.Id))
                                        {
                                            NotifyAdmin(Usr);
                                            NotifyCustomer(Usr, vb, VehicleId);
                                            ltlRemaining.Text = string.Concat("<p class='text-info bold'>You have ", vb.AdsRemaining, " out of ", vb.AdsBought, " ads remaining.</p>");
                                            Response.Redirect("~/account/myaccount.aspx");
                                        }
                                        else
                                        {
                                            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Error", "alert('An error occurred');", true);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString.Keys.Count > 0)
            {
                if (Request.QueryString["promo"] != null)
                {
                    if (Request.QueryString["promo"] == "1" && Request.QueryString["adtype"] == "Private")
                    {
                        CustomerVehicleInfo vi = (CustomerVehicleInfo)Session["VehicleInfo"];
                        VehiclesBilling     vb = Session["VehicleBilling"] as VehiclesBilling;
                        if (CustomerVehicleInfo.UpdateBillingId(vi.Id, vb.Id))
                        {
                            NotifyCustomer(vi.Id, Request.QueryString["item"], 0.99, "1", "");
                            NotifyAdmin(Request.QueryString["item"], 0, "1", "");
                        }
                        else
                        {
                            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Error", "alert('An error occurred');", true);
                        }
                    }
                }

                if (!IsPostBack)
                {
                    BindYear();
                    switch (Request.QueryString["item"])
                    {
                    case "ad":
                        switch (Request.QueryString["size"])
                        {
                        case "L":
                            lblItem.Text    = "Large Ad (rotating banner)";
                            txtPayment.Text = "599.00";
                            break;

                        case "S":
                            lblItem.Text    = "Small Ad (rotating images)";
                            txtPayment.Text = "299.00";
                            break;
                        }
                        break;

                    case "car":

                        switch (Request.QueryString["size"])
                        {
                        case "1":
                            lblItem.Text = "1 vehicle";
                            switch (Request.QueryString["adtype"])
                            {
                            case "Business":
                                txtPayment.Text = "19.99";
                                break;

                            case "Private":
                                txtPayment.Text = "0.99";
                                break;
                            }
                            break;

                        case "8":
                            lblItem.Text    = "8 vehicles";
                            txtPayment.Text = "89.99";
                            break;

                        case "20":
                            lblItem.Text    = "20 vehicles";
                            txtPayment.Text = "199.99";
                            break;
                        }
                        break;
                    }
                }
            }
        }