protected void Suggest(object sender, EventArgs e)
    {
        if (VenueSuggestTextBox.Text.Trim() != "")
        {
            Data dat = new Data(DateTime.Now);
            VenueSuggestTextBox.Text = dat.stripHTML(VenueSuggestTextBox.Text.Trim());

            dat.SendEmail(System.Configuration.ConfigurationManager.AppSettings["emailemail"].ToString(),
                System.Configuration.ConfigurationManager.AppSettings["emailName"].ToString(),
                System.Configuration.ConfigurationManager.AppSettings["emailemail"].ToString()
                , "Gotten a venue suggestions from: IP: " + dat.GetIP() + ", Message: " + VenueSuggestTextBox.Text + ", Email: " + EmailTextBox.Text,
                "Venue Suggestion Submitted");

            SuggestErrorLabel.Text = "Your suggestion has been made! Thanks!";
        }
    }
    protected void PostIt(object sender, EventArgs e)
    {
        object appSeshCountry;
        object appSeshState;
        object appSeshCity;
        object appSeshZip;
        object appSeshRadius;
        HttpCookie cookie = Request.Cookies["BrowserDate"];

        DateTime isn = DateTime.Now;

        if (!DateTime.TryParse(cookie.Value.ToString().Replace("%20", " ").Replace("%3A", ":"), out isn))
            isn = DateTime.Now;
        DateTime isNow = isn;
        Data dat = new Data(isn);
        string state = "";

        AuthorizePayPal d = new AuthorizePayPal();

        if (AgreeCheckBox.Checked)
        {
            bool chargeCard = false;
            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ToString());
            conn.Open();

            //Add case for if Paypal is filled in...
            //Authorize Credit Card
            decimal price = 0.00M;
            bool goOn = false;
            string message = "";
            string transactionID = "";
            if (FeaturePanel.Visible && TotalLabel.Text.Trim() != "")
            {
                if (decimal.TryParse(TotalLabel.Text.Trim(), out price))
                {
                    if (price != 0.00M)
                    {
                        if (PaymentPanel.Visible)
                        {
                            if (FirstNameTextBox.Text.Trim() == "" || LastNameTextBoxtBox.Text.Trim() == "" ||
                               BillingStreetAddressTextBox.Text.Trim() == "" || BillingCityTextBox.Text.Trim() == "" ||
                               BillingZipCodeTextBox.Text.Trim() == "" || BillingStateTextBox.Text.Trim() == "" ||
                                CardNumberTextBox.Text.Trim() == "" || CSVTextBox.Text.Trim() == "")
                            {
                                goOn = false;
                                Session["Featured"] = false;
                                message = "Please fill in all of the billing information.";
                            }
                            else
                            {
                                goOn = false;
                                Session["Featured"] = false;
                                string country = dat.GetDataDV("SELECT country_2_code FROM Countries WHERE country_id=" + BillingCountry.SelectedValue)[0]["country_2_code"].ToString();
                                com.paypal.sdk.util.NVPCodec status = d.DoPayment("Authorization", TotalLabel.Text, CardTypeDropDown.SelectedValue, CardNumberTextBox.Text.Trim(),
                                    ExpirationMonth.SelectedItem.Text, ExpirationYear.SelectedItem.Text, CSVTextBox.Text.Trim(), FirstNameTextBox.Text.Trim(), LastNameTextBoxtBox.Text.Trim(),
                                    BillingStreetAddressTextBox.Text.Trim(), BillingCityTextBox.Text, BillingStateTextBox.Text, country, BillingZipCodeTextBox.Text.Trim(), dat.GetIP());
                                message = status.ToString();
                                string successORFailure = status["ACK"];
                                switch (successORFailure.ToLower())
                                {
                                    case "failure":
                                        goOn = false;
                                        Session["Featured"] = false;
                                        message = status["L_LONGMESSAGE0"];
                                        break;
                                    case "successwithwarning":
                                        goOn = false;
                                        Session["Featured"] = false;
                                        message = status["L_SHORTMESSAGE0"];
                                        if (message == "Transaction approved but with invalid CSC format.")
                                            message = "Your CVC/CSV format for this card is not valid.";
                                        break;
                                    case "success":
                                        transactionID = status["TRANSACTIONID"];
                                        Session["TransID"] = transactionID;
                                        goOn = true;
                                        chargeCard = true;
                                        Session["Featured"] = true;
                                        break;
                                    default:
                                        goOn = false;
                                        Session["Featured"] = false;
                                        message = "There was an internal problem. Please contact support at: [email protected]. Please include as much detail as possible about what you are trying to do.";
                                        foreach (string key in status.Keys)
                                        {
                                            message += "key: " + key.ToString() + ", value: " + status[key].ToString() + "<br/>";
                                        }
                                        break;
                                }
                            }
                        }
                        else
                        {
                            goOn = true;
                            Session["Featured"] = true;
                        }
                    }
                    else
                    {
                        if (SearchTermsListBox.Items.Count > 0 && price == 0.00M)
                        {
                            goOn = false;
                            Session["Featured"] = false;
                            message = "You have entered search terms, but, have not included any dates.";
                        }
                        else
                        {
                            goOn = true;
                            Session["Featured"] = false;
                        }
                    }
                }
                else
                {
                    goOn = true;
                    Session["Featured"] = false;
                }
            }
            else
            {
                goOn = true;
                Session["Featured"] = false;
            }

            if (goOn)
            {
                bool isEdit = false;

                DateTime LastFetUpdate = DateTime.Now;

                if (Request.QueryString["edit"] != null)
                {
                    isEdit = bool.Parse(Request.QueryString["edit"].ToString());
                }

                string mediaCat = "0";
                if (PictureCheckList.Items.Count > 0)
                    mediaCat = "1";

                string command = "";

                DataSet dsEvent;
                bool wasFeatured = false;
                DataView dvRenu = new DataView();
                if (isEdit)
                {
                    dsEvent = dat.GetData("SELECT * FROM Ads WHERE Ad_ID=" + adID.Text);
                    wasFeatured = bool.Parse(dsEvent.Tables[0].Rows[0]["Featured"].ToString());
                    LastFetUpdate = DateTime.Parse(dsEvent.Tables[0].Rows[0]["LastFetUpdate"].ToString());
                    //numViews = int.Parse(dsEvent.Tables[0].Rows[0]["NumViews"].ToString());

                    string rad = "";

                    //if (RadiusPanel.Visible)
                    //    rad = ", Radius=@radius ";

                    dvRenu = dat.GetDataDV("SELECT * FROM Ads WHERE Ad_ID=" + adID.Text);

                    command = "UPDATE Ads SET LastFetUpdate=@fetUpdate, DatesOfAd=@dates, Template=@template, hasSongs=@songs, User_ID=@userID, FeaturedSummary=@featuredSummary , " +
                        "Description=@description, Featured=@featured, Header=@header, CountShown=@countShown,  mediaCategory=" + mediaCat + ", " +
                        "FeaturedPicture=@featuredPicture, FeaturedPictureName=@featuredPictureName, CatCountry=@catCountry, " +
                        "CatState=@catState, CatCity=@catCity  WHERE Ad_ID=" + adID.Text;
                }
                else
                {
                    string rad = "";
                    string radEnd = "";
                    //if (RadiusPanel.Visible)
                    //{
                    //    rad = ", Radius ";
                    //    radEnd = ", @radius ";
                    //}

                    command = "INSERT INTO Ads (LastFetUpdate, DatesOfAd, Template, hasSongs, User_ID, FeaturedSummary ,Description, Header, " +
                        "CountShown, Featured, mediaCategory, FeaturedPicture, FeaturedPictureName, CatCountry, CatState, CatCity, " +
                        " DateAdded) "
                        + " VALUES('" + DateTime.Now.ToString() + "', @dates, @template, @songs, @userID, @featuredSummary, @description, @header, @countShown, " +
                        "@featured, " + mediaCat + ", @featuredPicture, @featuredPictureName, @catCountry, @catState, @catCity, '" +
                        DateTime.Now.ToString() + "')";
                }

                SqlCommand cmd = new SqlCommand(command, conn);
                cmd.CommandType = CommandType.Text;
                cmd.Parameters.Add("@description", SqlDbType.NVarChar).Value = DescriptionTextBox.Content;
                cmd.Parameters.Add("@userID", SqlDbType.Int).Value = int.Parse(Session["User"].ToString());

                string fetDays = "";
                bool newDates = false;
                foreach (ListItem item in FeatureDatesListBox.Items)
                {
                    fetDays += ";" + item.Text + ";";
                    if (item.Value != "Disabled")
                        newDates = true;
                }

                if (wasFeatured)
                {
                    if (newDates)
                        cmd.Parameters.Add("@fetUpdate", SqlDbType.DateTime).Value = DateTime.Now;
                    else
                        cmd.Parameters.Add("@fetUpdate", SqlDbType.DateTime).Value = LastFetUpdate;

                    cmd.Parameters.Add("@featured", SqlDbType.Bit).Value = true;

                    if (FeaturePanel.Visible)
                    {
                        cmd.Parameters.Add("@dates", SqlDbType.NVarChar).Value = fetDays;
                    }
                    else
                        cmd.Parameters.Add("@dates", SqlDbType.NVarChar).Value = dvRenu[0]["DatesOfAd"].ToString();
                }
                else
                {
                    cmd.Parameters.Add("@fetUpdate", SqlDbType.DateTime).Value = DateTime.Now;
                    cmd.Parameters.Add("@featured", SqlDbType.Bit).Value = FeaturePanel.Visible;
                    if (FeaturePanel.Visible)
                    {
                        cmd.Parameters.Add("@dates", SqlDbType.NVarChar).Value = fetDays;
                    }
                    else
                    {
                        cmd.Parameters.Add("@dates", SqlDbType.NVarChar).Value = DBNull.Value;
                    }
                }

                if (FeaturePanel.Visible)
                {
                    if (BannerAdCheckBox.Checked)
                    {
                        cmd.Parameters.Add("@template", SqlDbType.Int).Value = TemplateRadioList.SelectedValue;

                    }
                    else
                    {
                        cmd.Parameters.Add("@template", SqlDbType.Int).Value = 1;
                    }
                }
                else
                {
                    if (wasFeatured)
                        cmd.Parameters.Add("@template", SqlDbType.Int).Value = dvRenu[0]["Template"].ToString();
                    else
                        cmd.Parameters.Add("@template", SqlDbType.Int).Value = DBNull.Value;
                }
                cmd.Parameters.Add("@songs", SqlDbType.Bit).Value = false;

                if (FeaturePanel.Visible)
                    cmd.Parameters.Add("@featuredSummary", SqlDbType.NVarChar).Value = SummaryTextBox.InnerHtml;
                else
                {
                    if (wasFeatured)
                        cmd.Parameters.Add("@featuredSummary", SqlDbType.NVarChar).Value = dvRenu[0]["FeaturedSummary"].ToString();
                    else
                        cmd.Parameters.Add("@featuredSummary", SqlDbType.NVarChar).Value = DBNull.Value;
                }

                cmd.Parameters.Add("@header", SqlDbType.NVarChar).Value = AdNameTextBox.Text;
                cmd.Parameters.Add("@countShown", SqlDbType.Int).Value = 0;

                if (FeaturePanel.Visible)
                    if (AdPictureCheckList.Items.Count > 0 && AdMediaPanel.Visible)
                    {
                        cmd.Parameters.Add("@featuredPicture", SqlDbType.NVarChar).Value = AdPictureCheckList.Items[0].Value;
                        cmd.Parameters.Add("@featuredPictureName", SqlDbType.NVarChar).Value = AdPictureCheckList.Items[0].Text;
                    }
                    else
                    {
                        cmd.Parameters.Add("@featuredPicture", SqlDbType.NVarChar).Value = DBNull.Value;
                        cmd.Parameters.Add("@featuredPictureName", SqlDbType.NVarChar).Value = DBNull.Value;
                    }
                else
                {
                    if (wasFeatured)
                    {
                        cmd.Parameters.Add("@featuredPicture", SqlDbType.NVarChar).Value = dvRenu[0]["FeaturedPicture"].ToString();
                        cmd.Parameters.Add("@featuredPictureName", SqlDbType.NVarChar).Value = dvRenu[0]["FeaturedPictureName"].ToString();
                    }
                    else
                    {
                        cmd.Parameters.Add("@featuredPicture", SqlDbType.NVarChar).Value = DBNull.Value;
                        cmd.Parameters.Add("@featuredPictureName", SqlDbType.NVarChar).Value = DBNull.Value;
                    }
                }

                if (CountryDropDown.SelectedIndex != -1)
                {
                    appSeshCountry = CountryDropDown.SelectedValue;
                    cmd.Parameters.Add("@catCountry", SqlDbType.Int).Value = CountryDropDown.SelectedValue;

                    if (StateDropDownPanel.Visible)
                    {
                        if (StateDropDown.SelectedIndex != -1)
                            state = StateDropDown.SelectedItem.Text;
                    }
                    else
                        state = StateTextBox.Text;

                    appSeshState = state;

                    if (state != "")
                        cmd.Parameters.Add("@catState", SqlDbType.NVarChar).Value = state;
                    else
                        cmd.Parameters.Add("@catState", SqlDbType.NVarChar).Value = DBNull.Value;

                    string city = "";
                    if (CityDropDownPanel.Visible)
                        city = MajorCityDrop.SelectedItem.Text;
                    else
                        city = CityTextBox.Text;
                    appSeshCity = city;
                    cmd.Parameters.Add("@catCity", SqlDbType.NVarChar).Value = city;
                }
                else
                {
                    cmd.Parameters.Add("@catCountry", SqlDbType.Int).Value = DBNull.Value;
                    cmd.Parameters.Add("@catState", SqlDbType.NVarChar).Value = DBNull.Value;
                    cmd.Parameters.Add("@catCity", SqlDbType.NVarChar).Value = DBNull.Value;
                }

                //Media Categories: NONE: 0, Slider: 1.
                bool isSlider = false;
                if (PictureCheckList.Items.Count > 0)
                    isSlider = true;

                cmd.ExecuteNonQuery();

                cmd = new SqlCommand("SELECT @@IDENTITY AS ID", conn);
                SqlDataAdapter da2 = new SqlDataAdapter(cmd);
                DataSet ds3 = new DataSet();
                da2.Fill(ds3);

                string ID = ds3.Tables[0].Rows[0]["ID"].ToString();

                if (isEdit)
                    ID = Request.QueryString["ID"].ToString();

                #region Take care of search terms
                if (FeaturePanel.Visible)
                {
                    string terms = "";
                    foreach (ListItem item in SearchTermsListBox.Items)
                    {
                        terms += ";" + item.Text + ";";
                    }
                    foreach (ListItem item in FeatureDatesListBox.Items)
                    {
                        if (item.Value != "Disabled")
                            dat.Execute("INSERT INTO AdSearchTerms (AdID, SearchTerms, SearchDate) VALUES(" + ID +
                                ", '" + terms.Replace("'", "''") + "', '" + item.Text + "')");
                    }
                }
                #endregion

                string theID = ID;
                if (isEdit)
                {
                    theID = adID.Text;
                }
                //if (MusicCheckBox.Checked)
                //{

                //    if (isEdit)
                //    {

                //        dat.Execute("DELETE FROM Ad_Song_Mapping WHERE AdID="+theID);
                //    }

                //    for (int i = 0; i < SongCheckList.Items.Count; i++)
                //    {
                //            cmd = new SqlCommand("INSERT INTO Ad_Song_Mapping (AdID, SongName, SongTitle) "+
                //                "VALUES(@eventID, @songName, @songTitle)", conn);
                //            cmd.Parameters.Add("@eventID", SqlDbType.Int).Value = int.Parse(theID);
                //            cmd.Parameters.Add("@songName", SqlDbType.NVarChar).Value = SongCheckList.Items[i].Value.ToString();
                //            cmd.Parameters.Add("@songTitle", SqlDbType.NVarChar).Value = SongCheckList.Items[i].Text;
                //            cmd.ExecuteNonQuery();

                //            dat.Execute("UPDATE Ads SET hasSongs=1 WHERE Ad_ID="+theID);
                //    }
                //}

                if (isEdit)
                {
                    dat.Execute("DELETE FROM Ad_Slider_Mapping WHERE AdID=" + theID);
                }

                if (MainAttractionCheck.Checked)
                {

                    if (isSlider)
                    {

                        char[] delim2 = { '\\' };
                        string[] fileArray = System.IO.Directory.GetFiles(MapPath(".") + "\\UserFiles\\" +
                            Session["UserName"].ToString() + "\\AdSlider\\");

                        if (!System.IO.Directory.Exists(MapPath(".") + "\\UserFiles"))
                        {
                            System.IO.Directory.CreateDirectory(MapPath(".") + "\\UserFiles");
                            System.IO.Directory.CreateDirectory(MapPath(".") + "\\UserFiles\\" + Session["UserName"].ToString() + "\\");
                            System.IO.Directory.CreateDirectory(MapPath(".") + "\\UserFiles\\" + Session["UserName"].ToString() + "\\AdSlider");
                            System.IO.Directory.CreateDirectory(MapPath(".") + "\\UserFiles\\" + Session["UserName"].ToString() + "\\AdSlider\\" + theID);
                        }
                        else
                        {
                            if (!System.IO.Directory.Exists(MapPath(".") + "\\UserFiles\\" + Session["UserName"].ToString() + "\\"))
                            {
                                System.IO.Directory.CreateDirectory(MapPath(".") + "\\UserFiles\\" + Session["UserName"].ToString() + "\\");
                                System.IO.Directory.CreateDirectory(MapPath(".") + "\\UserFiles\\" + Session["UserName"].ToString() + "\\AdSlider");
                                System.IO.Directory.CreateDirectory(MapPath(".") + "\\UserFiles\\" + Session["UserName"].ToString() + "\\" + theID);
                            }
                            else
                            {
                                if (!System.IO.Directory.Exists(MapPath(".") + "\\UserFiles\\" + Session["UserName"].ToString() + "\\AdSlider"))
                                {
                                    System.IO.Directory.CreateDirectory(MapPath(".") + "\\UserFiles\\" + Session["UserName"].ToString() + "\\AdSlider");
                                    System.IO.Directory.CreateDirectory(MapPath(".") + "\\UserFiles\\" + Session["UserName"].ToString() + "\\AdSlider\\" + theID);
                                }
                                else
                                {
                                    if (!System.IO.Directory.Exists(MapPath(".") + "\\UserFiles\\" + Session["UserName"].ToString() + "\\AdSlider\\" + theID))
                                    {
                                        System.IO.Directory.CreateDirectory(MapPath(".") + "\\UserFiles\\" + Session["UserName"].ToString() + "\\AdSlider\\" + theID);
                                    }
                                }
                            }
                        }

                        string YouTubeStr = "";
                        char[] delim3 = { '.' };
                        for (int i = 0; i < PictureCheckList.Items.Count; i++)
                        {
                            int length = fileArray[i].Split(delim2).Length;
                            string[] tokens = PictureCheckList.Items[i].Value.ToString().Split(delim3);

                            if (tokens.Length >= 2)
                            {
                                if (tokens[1].ToUpper() == "JPG" || tokens[1].ToUpper() == "JPEG" || tokens[1].ToUpper() == "GIF" || tokens[1].ToUpper() == "PNG")
                                {
                                    if (!System.IO.File.Exists(MapPath(".") + "\\UserFiles\\" + Session["UserName"].ToString() +
                                        "\\AdSlider\\" + theID + "\\" + PictureCheckList.Items[i].Value))
                                    {
                                        System.IO.File.Copy(MapPath(".") + "\\UserFiles\\" + Session["UserName"].ToString() +
                                                                "\\AdSlider\\" + PictureCheckList.Items[i].Value,
                                                                MapPath(".") + "\\UserFiles\\" + Session["UserName"].ToString() +
                                        "\\AdSlider\\" + theID + "\\" +
                                                                PictureCheckList.Items[i].Value);
                                    }

                                    cmd = new SqlCommand("INSERT INTO Ad_Slider_Mapping (AdID, PictureName, RealPictureName) " +
                                        "VALUES (@eventID, @picName, @realName)", conn);
                                    cmd.Parameters.Add("@eventID", SqlDbType.Int).Value = theID;
                                    cmd.Parameters.Add("@picName", SqlDbType.NVarChar).Value = PictureCheckList.Items[i].Value;
                                    cmd.Parameters.Add("@realName", SqlDbType.NVarChar).Value = PictureCheckList.Items[i].Text;
                                    cmd.ExecuteNonQuery();
                                }
                            }
                            else
                            {
                                YouTubeStr += PictureCheckList.Items[i].Value + ";";
                            }

                        }

                        //if (YouTubeStr != "")
                        //{
                        dat.Execute("UPDATE Ads SET YouTubeVideo='" + YouTubeStr + "' WHERE Ad_ID=" + theID);
                        //}

                    }
                }
                else
                {

                }

                if (isEdit)
                {
                    dat.Execute("DELETE FROM Ad_Category_Mapping WHERE AdID=" + theID);
                }

                CreateCategories(theID);

                string adFeatured = "";
                string adFeaturedEmail = "";

                DataSet dsUser = dat.GetData("SELECT Email, UserName FROM USERS WHERE User_ID=" +
                        Session["User"].ToString());

                try
                {
                    bool showMessage = false;
                    if (chargeCard)
                    {
                        Encryption encrypt = new Encryption();

                        //Charge Card
                        string country = dat.GetDataDV("SELECT country_2_code FROM Countries WHERE country_id=" + BillingCountry.SelectedValue)[0]["country_2_code"].ToString();
                        com.paypal.sdk.util.NVPCodec status = d.DoCaptureCode(transactionID, price.ToString(),
                            "B" + theID + isn.ToString(), "Capture Transaction for Featuring Bulletin '" +
                            dat.MakeNiceNameFull(AdNameTextBox.Text) + "'");
                        //message = status.ToString();
                        string successORFailure = status["ACK"];
                        switch (successORFailure.ToLower())
                        {
                            case "failure":
                                MessagePanel.Visible = true;
                                YourMessagesLabel.Text += status["L_LONGMESSAGE0"];
                                //MessagePanel.Visible = true;
                                //foreach (string key in status.Keys)
                                //{
                                //    YourMessagesLabel.Text += "key: '" + key + "', value: '" + status[key] + "' <br/>";
                                //}
                                break;
                            case "success":
                                showMessage = true;
                                break;
                            default:
                                MessagePanel.Visible = true;
                                foreach (string key in status.Keys)
                                {
                                    YourMessagesLabel.Text += "key: '" + key + "', value: '" + status[key] + "' <br/>";
                                }
                                break;
                        }
                    }
                    else
                    {
                        showMessage = true;
                    }

                    if (showMessage)
                    {

                        string emailBody = "Dear " + dsUser.Tables[0].Rows[0]["UserName"].ToString() + ", <br/><br/> you have successfully posted the bulletin \"" + AdNameTextBox.Text +
                            "\". <br/><br/> You can find this bulletin <a href=\"http://hippohappenings.com/" + dat.MakeNiceName(AdNameTextBox.Text) + "_" + theID + "_Ad\">here</a>. " + adFeaturedEmail +
                            "<br/><br/> To rate your experience posting this bulletin <a href=\"http://hippohappenings.com/RateExperience.aspx?Type=A&ID=" + theID + "\">please include your feedback here.</a>" +
                            "<br/><br/><br/>Have a HippoHappening Day!<br/><br/>";

                        if (isEdit)
                        {
                            emailBody = "Dear " + dsUser.Tables[0].Rows[0]["UserName"].ToString() + ", <br/><br/> you have successfully edited the bulletin \"" + AdNameTextBox.Text +
                                "\". <br/><br/> You can find this bulletin <a href=\"http://hippohappenings.com/" + dat.MakeNiceName(AdNameTextBox.Text) + "_" + theID + "_Ad\">here</a>. " + adFeaturedEmail +
                                "<br/><br/> To rate your experience editing this bulletin <a href=\"http://hippohappenings.com/RateExperience.aspx?Type=A&ID=" + theID + "\">please include your feedback here.</a>" +
                                "<br/><br/><br/>Have a HippoHappening Day!<br/><br/>";
                        }

                        if (!Request.IsLocal)
                        {
                            dat.SendEmail(System.Configuration.ConfigurationManager.AppSettings["emailemail"].ToString(),
                                        System.Configuration.ConfigurationManager.AppSettings["emailName"].ToString(),
                                        dsUser.Tables[0].Rows[0]["Email"].ToString(), emailBody, "You have successfully posted the bulletin: " +
                                        AdNameTextBox.Text);
                        }
                        conn.Close();

                        Session["Message"] = "Your bulletin has been posted successfully!<br/> Here are your next steps: <br/>";

                        if (isEdit)
                        {
                            Session["Message"] = "Your bulletin has been edited successfully!<br/> Here are your next steps: <br/>";
                        }

                        //Clear cache so that the PlayerList.xml can be grabbed by the browser again.
                        ClearCache();

                        Session["Message"] += "<br/>" + "Go to <a class=\"AddLink\" onclick=\"Search('" + dat.MakeNiceName(AdNameTextBox.Text) + "_" + theID + "_Ad');\">your bulletin's</a> home page." + adFeatured + "<br/><br/> -<a class=\"AddLink\" onclick=\"Search('RateExperience.aspx?Type=A&ID=" + theID + "');\" >Rate </a>your user experience posting this bulletin.<br/>";
                        //MessageLiteral.Text = "<script type=\"text/javascript\">alert('" + message + "');</script>";
                        Encryption encrypt = new Encryption();
                        MessageRadWindow.NavigateUrl = "Message.aspx?message=" + encrypt.encrypt(Session["Message"].ToString() +
                            "<br/><br/><div align=\"center\">" +
                            "<div style=\"width: 50px;\" onclick=\"Search('home')\">" +
                            "<div class=\"topDiv\" style=\"clear: both;\">" +
                              "  <img style=\"float: left;\" src=\"NewImages/ButtonLeft.png\" height=\"27px\" /> " +
                               " <div class=\"NavyLink\" style=\"font-size: 12px; text-decoration: none; padding-top: 5px;padding-left: 6px; padding-right: 6px;height: 27px;float: left;background: url('NewImages/ButtonPixel.png'); background-repeat: repeat-x;\">" +
                                   " OK " +
                                "</div>" +
                               " <img style=\"float: left;\" src=\"NewImages/ButtonRight.png\" height=\"27px\" /> " +
                            "</div>" +
                            "</div>" +
                            "</div><br/>");
                        MessageRadWindow.Visible = true;
                        MessageRadWindowManager.VisibleOnPageLoad = true;

                        Session["categorySession"] = null;
                    }
                }
                catch (Exception ex)
                {
                    MessagePanel.Visible = true;
                    YourMessagesLabel.Text += ex.ToString();
                }
            }
            else
            {
                MessagePanel.Visible = true;
                YourMessagesLabel.Text = message;
            }
        }
        else
        {
            MessagePanel.Visible = true;
            YourMessagesLabel.Text += "You must agree to the terms and conditions.";
        }
    }
    protected void GoToSearch(object sender, EventArgs e)
    {
        HttpCookie cookie = Request.Cookies["BrowserDate"];
        Data dat = new Data(DateTime.Parse(cookie.Value.ToString().Replace("%20", " ").Replace("%3A", ":")));
        string cookieName = FormsAuthentication.FormsCookieName;
        HttpCookie authCookie = Context.Request.Cookies[cookieName];

        string country = "";
        string state = "";
        string city = "";

        FormsAuthenticationTicket authTicket = null;

        string group = "";
        if (authCookie != null)
        {
            authTicket = FormsAuthentication.Decrypt(authCookie.Value);
            group = authTicket.UserData.ToString();
        }

        if (group.Contains("User"))
        {
            DataSet ds1 = dat.GetData("SELECT * FROM Users U, UserPreferences UP WHERE U.User_ID=" +
                authTicket.Name + " AND U.User_ID=UP.UserID ");

            if(ds1.Tables.Count > 0)
                if (ds1.Tables[0].Rows.Count > 0)
                {
                    country = ds1.Tables[0].Rows[0]["CatCountry"].ToString();
                    state = ds1.Tables[0].Rows[0]["CatState"].ToString();
                    city = ds1.Tables[0].Rows[0]["CatCity"].ToString();
                }
        }
        else
        {
            DataSet ds1 = dat.GetData("SELECT * FROM SearchIPs WHERE IP='" + dat.GetIP() + "'");

            if(ds1.Tables.Count > 0)
                if (ds1.Tables[0].Rows.Count > 0)
                {
                    country = ds1.Tables[0].Rows[0]["Country"].ToString();
                    state = ds1.Tables[0].Rows[0]["State"].ToString();
                    city = ds1.Tables[0].Rows[0]["City"].ToString();
                }

        }

        if (country != "")
            country = " AND E.Country = " + country;

        int c = 0;

        if (state != "")
        {

            c++;
        }

        if (city != "")
        {

            c++;
        }

        SqlDbType[] types = new SqlDbType[c];
        object[] data = new object[c];

        if (state != "")
        {
            types[0] = SqlDbType.NVarChar;
            data[0] = state;
            state = " AND E.State=@p0 ";
            if (city != "")
            {
                types[1] = SqlDbType.NVarChar;
                data[1] = city;
                city = " AND E.City=@p1 ";
            }
        }
        else
        {
            if (city != "")
            {
                types[0] = SqlDbType.NVarChar;
                data[0] = city;
                city = " AND E.City=@p0 ";
            }
        }

        DataSet ds = dat.GetDataWithParemeters("SELECT DISTINCT TOP 10 EO.DateTimeStart, E.Header, E.Content, EO.EventID FROM Events E, Event_Occurance EO WHERE E.ID=EO.EventID " + country + state + city + " AND CONVERT(NVARCHAR, MONTH(EO.DateTimeStart)) + '/' + CONVERT(NVARCHAR, DAY(EO.DateTimeStart)) + '/' + CONVERT(NVARCHAR, YEAR(EO.DateTimeStart)) = '" + RadCalendar1.SelectedDate.ToShortDateString() + "'", types, data);

        EventPanel.Controls.Clear();
        if (ds.Tables.Count > 0)
            if (ds.Tables[0].Rows.Count > 0)
            {

                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {

                    DateTime date = DateTime.Parse(ds.Tables[0].Rows[i]["DateTimeStart"].ToString());
                    ASP.controls_homeevent_ascx eventH = new ASP.controls_homeevent_ascx();
                    eventH.DAY = date.DayOfWeek.ToString().Substring(0, 3);
                    eventH.DAY_NUMBER = date.Day.ToString();
                    eventH.MONTH = dat.GetMonth(date.Month.ToString()).Substring(0, 3);
                    eventH.EVENT_NAME = ds.Tables[0].Rows[i]["Header"].ToString();
                    if (ds.Tables[0].Rows[i]["Content"].ToString().Length > 150)
                        eventH.SUMMARY = dat.BreakUpString(ds.Tables[0].Rows[i]["Content"].ToString().Substring(0, 150), 67) + "...";
                    else
                        eventH.SUMMARY = dat.BreakUpString(ds.Tables[0].Rows[i]["Content"].ToString(), 67) + "...";
                    eventH.EVENT_ID = int.Parse(ds.Tables[0].Rows[i]["EventID"].ToString());
                    EventPanel.Controls.Add(eventH);

                }
            }
            else
            {
                Label label = new Label();
                label.CssClass = "EventBody";
                label.Text = "No events are listed for this date. Sorry. But perhaps you could enter one... <a class=\"AddLink\" href=\"EnterEvent.aspx\">Enter Events</a>.";
                EventPanel.Controls.Add(label);
            }
        else
        {
            Label label = new Label();
            label.CssClass = "EventBody";
            label.Text = "No events are listed for this date. Sorry. But perhaps you could enter one... <a class=\"AddLink\" href=\"EnterEvent.aspx\">Enter Events</a>.";
            EventPanel.Controls.Add(label);
        }

        Session["HomeEvents"] = ds;
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        //Page.Trace.IsEnabled = true;
        //Page.Trace.TraceMode = TraceMode.SortByTime;

        try
        {
            HtmlMeta hm = new HtmlMeta();
            HtmlMeta kw = new HtmlMeta();

            HtmlHead head = (HtmlHead)Page.Header;

            hm.Name = "Description";
            hm.Content = "Find your local events, venues and classifieds all while " +
                     "ads from your peers, neighborhood, and community are displayed to you purely based on your interests." +
                     "Large corporations are not welcome!";
            head.Controls.AddAt(0, hm);

            HtmlMeta nMT = new HtmlMeta();
            nMT.Name = "google-site-verification";
            nMT.Content = "tw8rmOWW-DlZa-H4DZdGr201J5kC7NVLXUmk5oN8vFM";

            head.Controls.Add(nMT);

            HtmlLink lkl = new HtmlLink();
            lkl.Href = "ror.xml";
            lkl.Attributes.Add("rel", "alternate");
            lkl.Attributes.Add("type", "application/xml");
            lkl.Attributes.Add("title", "ROR");

            head.Controls.Add(lkl);

            HttpCookie cookie = Request.Cookies["BrowserDate"];
            if (cookie == null)
            {
                cookie = new HttpCookie("BrowserDate");
                cookie.Value = DateTime.Now.Date.ToString();
                cookie.Expires = DateTime.Now.AddDays(22);
                Response.Cookies.Add(cookie);
            }
            bool fillUserData = false;
            Data dat = new Data(DateTime.Parse(cookie.Value.ToString().Replace("%20", " ").Replace("%3A", ":").Replace("%28", "(").Replace("%29", ")")));

            kw.Name = "keywords";
            kw.Content = "events, ads, venues, post, search, find, local events, concerts, festivals, world, theatre, technology, " +
                "family, peers, neighborhood, classifieds";

            DataView dvCats = dat.GetDataDV("SELECT * FROM AdCategories");

            for (int i = 0; i < dvCats.Count; i++)
            {
                kw.Content += ", " + dvCats[i]["Name"].ToString();
            }

            dvCats = dat.GetDataDV("SELECT * FROM EventCategories");

            for (int i = 0; i < dvCats.Count; i++)
            {
                kw.Content += ", " + dvCats[i]["Name"].ToString();
            }

            dvCats = dat.GetDataDV("SELECT * FROM VenueCategories");

            for (int i = 0; i < dvCats.Count; i++)
            {
                kw.Content += ", " + dvCats[i]["Name"].ToString();
            }

            head.Controls.AddAt(0, kw);

            string cookieName = FormsAuthentication.FormsCookieName;
            HttpCookie authCookie = Context.Request.Cookies[cookieName];

                //logInPanel.Visible = Session["User"] == null;
                //loggedInPanel.Visible = Session["User"] != null;

            string country = "";
            string state = "";
            string city = "";
            string countryID = "";
            string stateID = "";
            string cityID = "";
            FormsAuthenticationTicket authTicket = null;
            try
            {
                string group = "";
                if (authCookie != null)
                {
                    authTicket = FormsAuthentication.Decrypt(authCookie.Value);
                    group = authTicket.UserData.ToString();
                }

                if (group.Contains("User"))
                {
                    Session["User"] = authTicket.Name;
                    DataSet ds1 = dat.GetData("SELECT * FROM Users U, UserPreferences UP WHERE U.User_ID=" +
                        authTicket.Name + " AND U.User_ID=UP.UserID ");
                    Session["UserName"] = ds1.Tables[0].Rows[0]["UserName"].ToString();

                    country = ds1.Tables[0].Rows[0]["CatCountry"].ToString();
                    countryID = country;

                    state = ds1.Tables[0].Rows[0]["CatState"].ToString();
                    city = ds1.Tables[0].Rows[0]["CatCity"].ToString();
                    stateID = state;
                    cityID = city;

                    //DataSet ds2 = dat.RetrieveAds(Session["User"].ToString(), false);
                    //DataSet dsMain = dat.RetrieveMainAds(Session["User"].ToString());
                    //Ads1.DATA_SET = ds2;
                    //Ads1.MAIN_AD_DATA_SET = dsMain;

                    fillUserData = true;
                }
                else
                {
                    DataSet ds1 = dat.GetData("SELECT * FROM SearchIPs WHERE IP='" + dat.GetIP() + "'");

                    bool getAnotherDs1 = false;
                    if (ds1.Tables.Count > 0)
                        if (ds1.Tables[0].Rows.Count > 0)
                        {
                            country = ds1.Tables[0].Rows[0]["Country"].ToString();
                            countryID = country;
                            state = ds1.Tables[0].Rows[0]["State"].ToString();
                            city = ds1.Tables[0].Rows[0]["City"].ToString();
                            stateID = state;
                            cityID = city;
                        }
                        else
                        {
                            getAnotherDs1 = true;
                        }
                    else
                    {
                        getAnotherDs1 = true;
                    }

                    if (getAnotherDs1)
                    {
                        ds1 = dat.GetData("SELECT * FROM Users U, UserPreferences UP WHERE " +
                            " U.User_ID=UP.UserID AND U.IPs LIKE '%" + dat.GetIP() + "%'");
                        if (ds1.Tables.Count > 0)
                            if (ds1.Tables[0].Rows.Count > 0)
                            {
                                country = ds1.Tables[0].Rows[0]["CatCountry"].ToString();
                                countryID = country;
                                state = ds1.Tables[0].Rows[0]["CatState"].ToString();
                                city = ds1.Tables[0].Rows[0]["CatCity"].ToString();
                                stateID = state;
                                cityID = city;
                            }
                    }

                    //if (!IsPostBack)
                    //{
                    //    Ads1.DATA_SET = dat.RetrieveAllAds(false);
                    //    Ads1.MAIN_AD_DATA_SET = dat.RetrieveAllAds(true);
                    //}
                    Button calendarLink = (Button)dat.FindControlRecursive(this, "CalendarLink");
                    calendarLink.Visible = false;

                }
            }
            catch (Exception ex)
            {

            }

            DataSet ds;

            if (!IsPostBack)
            {
                LocationLabel.Text = "";
                if (country != "")
                    country = " AND E.Country = " + country;

                int c = 0;

                if (state != "")
                {

                    c++;
                }

                if (city != "")
                {

                    c++;
                }

                SqlDbType[] types = new SqlDbType[c];
                object[] data = new object[c];

                if (state != "")
                {
                    types[0] = SqlDbType.NVarChar;
                    data[0] = state;
                    state = " AND E.State=@p0 ";
                    if (city != "")
                    {
                        types[1] = SqlDbType.NVarChar;
                        data[1] = city;
                        city = " AND E.City=@p1 ";
                    }
                }
                else
                {
                    if (city != "")
                    {
                        types[0] = SqlDbType.NVarChar;
                        data[0] = city;
                        city = " AND E.City=@p0 ";
                    }
                }

                ds = dat.GetDataWithParemeters("SELECT DISTINCT TOP 10 EO.DateTimeStart, E.Header, E.Content, EO.EventID FROM Events E, Event_Occurance EO WHERE E.ID=EO.EventID " + country + state + city + " AND EO.DateTimeStart > '" + DateTime.Parse(cookie.Value.ToString().Replace("%20", " ").Replace("%3A", ":")).Date + "'", types, data);

                Session["HomeEvents"] = ds;
                LocationLabel.Text = "";
                if (country == "" && state == "" && city == "")
                {
                    LocationLabel.Text = " The World ";
                }
                else
                {
                    if (city != "")
                    {
                        LocationLabel.Text += cityID;
                        if (state != "")
                            LocationLabel.Text += ", " + stateID;
                    }
                    else
                    {
                        if (state != "")
                            LocationLabel.Text += stateID;
                    }
                }

                if (LocationLabel.Text == "")
                {
                    DataSet dsCountry = dat.GetData("SELECT * FROM Countries WHERE country_id=" + countryID);
                    LocationLabel.Text = dsCountry.Tables[0].Rows[0]["country_name"].ToString();
                }
            }
            else
            {
                EventPanel.Controls.Clear();
                LocationLabel.Text = "";
                ds = (DataSet)Session["HomeEvents"];

                if (countryID == "" && stateID == "" && cityID == "")
                {
                    LocationLabel.Text = " The World ";
                }
                else
                {
                    if (cityID != "")
                    {
                        LocationLabel.Text += cityID;
                        if (state != "")
                            LocationLabel.Text += ", " + stateID;
                    }
                    else
                    {
                        if (state != "")
                            LocationLabel.Text += stateID;
                    }
                }

                if (RadCalendar1.SelectedDate.ToShortDateString() != "1/1/0001")
                    LocationLabel.Text += " on " + RadCalendar1.SelectedDate.ToShortDateString();

            }

            ds = (DataSet)Session["HomeEvents"];

            if (ds != null)
            {

                if (ds.Tables.Count > 0)
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                        {
                            DateTime date = DateTime.Parse(ds.Tables[0].Rows[i]["DateTimeStart"].ToString());
                            ASP.controls_homeevent_ascx eventH = new ASP.controls_homeevent_ascx();
                            eventH.DAY = date.DayOfWeek.ToString().Substring(0, 3);
                            eventH.DAY_NUMBER = date.Day.ToString();
                            eventH.MONTH = dat.GetMonth(date.Month.ToString()).Substring(0, 3);
                            eventH.EVENT_NAME = ds.Tables[0].Rows[i]["Header"].ToString();
                            if (ds.Tables[0].Rows[i]["Content"].ToString().Length > 150)
                                eventH.SUMMARY = dat.BreakUpString(ds.Tables[0].Rows[i]["Content"].ToString().Substring(0, 150), 67) + "...";
                            else
                                eventH.SUMMARY = dat.BreakUpString(ds.Tables[0].Rows[i]["Content"].ToString(), 67) + "...";
                            eventH.EVENT_ID = int.Parse(ds.Tables[0].Rows[i]["EventID"].ToString());
                            EventPanel.Controls.Add(eventH);
                        }

                    }
                    else
                    {

                        Label label = new Label();
                        label.CssClass = "EventBody";
                        label.Text = "No events are listed for this date. Sorry. But perhaps you could enter one... <a class=\"AddLink\" href=\"BlogEvent.aspx\">Enter Events</a>.";
                        EventPanel.Controls.Add(label);
                    }
                else
                {

                    Label label = new Label();
                    label.CssClass = "EventBody";
                    label.Text = "No events are listed for this date. Sorry. But perhaps you could enter one... <a class=\"AddLink\" href=\"BlogEvent.aspx\">Enter Events</a>.";
                    EventPanel.Controls.Add(label);
                }
            }
            else
            {

                Label label = new Label();
                label.CssClass = "EventBody";
                label.Text = "No events are listed for this date. Sorry. But perhaps you could enter one... <a class=\"AddLink\" href=\"BlogEvent.aspx\">Enter Events</a>.";
                EventPanel.Controls.Add(label);
            }

            #region Original Home page code
            //if (ds.Tables.Count > 0)
            //{
            //    if (ds.Tables[0].Rows.Count > 0)
            //    {

            //        ASP.controls_footer_ascx thefooter = (ASP.controls_footer_ascx)dat.FindControlRecursive(this, "TheFooter");
            //        thefooter.EVENT_ID = int.Parse(ds.Tables[0].Rows[0]["ID"].ToString());

            //        string ID = ds.Tables[0].Rows[0]["ID"].ToString();
            //        DataSet dsDate = dat.GetData("SELECT * FROM Event_Occurance WHERE EventID=" + ID);
            //        DataSet dsVenue = dat.GetData("SELECT * FROM Venues WHERE ID=" + ds.Tables[0].Rows[0]["Venue"]);
            //        TagCloud.THE_ID = int.Parse(ID);

            //        DataSet dsComments = dat.GetData("SELECT C.BlogDate AS theDate, * FROM Comments C, Users U WHERE U.User_ID=C.UserID AND C.BlogID=" + ID +" ORDER BY C.BlogDate");
            //        TheComments.DATA_SET = dsComments;
            //        TheComments.DataBind2(true);

            //        if (bool.Parse(ds.Tables[0].Rows[0]["hasSongs"].ToString()))
            //        {
            //            DataSet dsSongs = dat.GetData("SELECT * FROM Event_Song_Mapping WHERE EventID=" + ID);
            //            ASP.controls_songplayer_ascx songs = new ASP.controls_songplayer_ascx();
            //            int songCount = dsSongs.Tables[0].Rows.Count;

            //            if (songCount > 2)
            //            {
            //                songs.SONG1 = dsSongs.Tables[0].Rows[0]["SongName"].ToString();
            //                songs.SONG2 = dsSongs.Tables[0].Rows[1]["SongName"].ToString();
            //                songs.SONG3 = dsSongs.Tables[0].Rows[2]["SongName"].ToString();
            //            }
            //            else if (songCount > 1)
            //            {
            //                songs.SONG1 = dsSongs.Tables[0].Rows[0]["SongName"].ToString();
            //                songs.SONG2 = dsSongs.Tables[0].Rows[1]["SongName"].ToString();
            //            }
            //            else
            //                songs.SONG1 = dsSongs.Tables[0].Rows[0]["SongName"].ToString();

            //            songs.USER_NAME = ds.Tables[0].Rows[0]["UserName"].ToString();

            //            SongPanel.Controls.Add(songs);
            //        }

            //        EventName.Text = ds.Tables[0].Rows[0]["Header"].ToString();
            //        Session["Subject"] = "Re: "+ds.Tables[0].Rows[0]["Header"].ToString();
            //        Session["CommentSubject"] = "Re: " + ds.Tables[0].Rows[0]["Header"].ToString();
            //        EventName.NavigateUrl = "~/Event.aspx?EventID=" + ID;
            //        Session["EventID"] = ID;
            //        VenueName.Text = dsVenue.Tables[0].Rows[0]["Name"].ToString();
            //        VenueName.NavigateUrl = "Venue.aspx?ID="+dsVenue.Tables[0].Rows[0]["ID"].ToString();
            //        DateTime date = (DateTime)dsDate.Tables[0].Rows[0]["DateTimeStart"];
            //        DateAndTimeLabel.Text = date.DayOfWeek.ToString() + ", " + GetMonth(date.Month.ToString()) + " " + date.Day + " " + date.Hour + ":" + date.Minute;
            //        string content = ds.Tables[0].Rows[0]["Content"].ToString();
            //        SendTxtID.MESSAGE = EventName.Text + " occurs at " + VenueName.Text + " on " + DateAndTimeLabel.Text;

            //        string href = Request.Url.AbsoluteUri;
            //        SendEmailID.MESSAGE = "EventName: <a class=\"AddLink\" href=\"" + href +
            //            "\">" + EventName.Text + "</a> \n\r Venue: " + VenueName.Text +
            //            " \n\r Date: " + DateAndTimeLabel.Text + " \n\r " + content;

            //        //if (fillUserData)
            //        //{
            //        //    DataSet ds2 = dat.GetData("SELECT EEL.ExcitmentLevel AS Level FROM User_Calendar UC, Event_ExcitmentLevel EEL WHERE UC.UserID="
            //        //        + Session["User"].ToString() + " AND UC.EventID = " + ID + " AND UC.ExcitmentID=EEL.ID ");

            //        //    bool addEvent = false;

            //        //    if (ds2.Tables.Count > 0)
            //        //        if (ds2.Tables[0].Rows.Count > 0)
            //        //        {
            //        //            Label label = new Label();
            //        //            label.CssClass = "AddLinkGoing";
            //        //            label.Text = "Guess What?!: you're going to this event and you are " + ds2.Tables[0].Rows[0]["Level"].ToString();
            //        //            CalendarPanel.Controls.Add(label);
            //        //        }
            //        //        else
            //        //            addEvent = true;
            //        //    else
            //        //        addEvent = true;

            //        //    if (addEvent)
            //        //    {
            //        //        ASP.controls_addtocalendar_ascx AddTo1 = new ASP.controls_addtocalendar_ascx();
            //        //        AddTo1.ID = "AddTo1";
            //        //        AddTo1.TEXT = "Add this event to calendar";
            //        //        AddTo1.EVENT_ID = int.Parse(ID);
            //        //        CalendarPanel.Controls.Add(AddTo1);
            //        //    }

            //        //}

            //        if (content.Length > 500)
            //        {
            //            ShowDescriptionBegining.Text = content.Substring(0, 500);
            //            int j = 500;
            //            if (content[500] != ' ')
            //            {

            //                while (content[j] != ' ')
            //                {
            //                    ShowDescriptionBegining.Text += content[j];
            //                    j++;
            //                }
            //            }
            //            ShowDescriptionBegining.Text = dat.BreakUpString(ShowDescriptionBegining.Text, 65);
            //            ShowRestOfDescription.Text = dat.BreakUpString(content.Substring(j), 65);
            //        }
            //        else
            //        {
            //            ShowDescriptionBegining.Text = dat.BreakUpString(content, 65);
            //            ShowRestOfDescription.Text = "";
            //        }

            //        //Media Categories: NONE: 0, Picture: 1, Video: 2, YouTubeVideo: 3, Slider: 4
            //        int mediaCategory = int.Parse(ds.Tables[0].Rows[0]["mediaCategory"].ToString());

            //        switch (mediaCategory)
            //        {
            //            case 0:
            //                break;
            //            case 1:
            //                ShowVideoPictureLiteral.Text = "<img style=\"float: left; padding-right: 10px; padding-top: 9px;\" height=\"250px\" width=\"440px\" src=\"UserFiles/" + ds.Tables[0].Rows[0]["Picture"].ToString() + "\" />";
            //                break;
            //            case 2:
            //                ShowVideoPictureLiteral.Text = "<div style=\"float:left; padding-top: 9px; padding-right: 10px;\"><embed  height=\"250px\" width=\"440px\" src=\"UserFiles/" + ds.Tables[0].Rows[0]["Video"].ToString() + "\" /></div>";
            //                break;
            //            case 3:
            //                ShowVideoPictureLiteral.Text = "<div style=\"float:left; padding-top: 9px; padding-right: 10px;\"><object width=\"440\" height=\"250\"><param name=\"movie\" value=\"http://www.youtube.com/v/" + ds.Tables[0].Rows[0]["YouTubeVideo"].ToString() + "\"></param><param name=\"allowFullScreen\" value=\"true\"></param><embed src=\"http://www.youtube.com/v/" + ds.Tables[0].Rows[0]["YouTubeVideo"].ToString() + "\" type=\"application/x-shockwave-flash\" allowfullscreen=\"true\" width=\"440\" height=\"250\"></embed></object></div>";
            //                break;
            //            case 4:
            //                ShowVideoPictureLiteral.Text = "";
            //                DataSet dsSlider = dat.GetData("SELECT * FROM Event_Slider_Mapping WHERE EventID=" + ID);
            //                if (dsSlider.Tables.Count > 0)
            //                    if (dsSlider.Tables[0].Rows.Count > 0)
            //                    {
            //                        char[] delim = { '\\' };
            //                        string[] fileArray = System.IO.Directory.GetFiles(MapPath(".") + "\\UserFiles\\" + Session["UserName"].ToString() + "\\Slider\\");

            //                        string[] finalFileArray = new string[fileArray.Length];

            //                        for (int i = 0; i < fileArray.Length; i++)
            //                        {
            //                            int length = fileArray[i].Split(delim).Length;
            //                            finalFileArray[i] = "http://" + Request.Url.Authority + "/HippoHappenings/UserFiles/" + Session["UserName"].ToString() + "/Slider/" + fileArray[i].Split(delim)[length - 1];
            //                        }
            //                        Rotator1.DataSource = finalFileArray;
            //                        Rotator1.DataBind();
            //                        RotatorPanel.Visible = true;
            //                    }
            //                break;
            //            default: break;
            //        }

            //        this.Title = EventName.Text;
            //    }
            //}
            #endregion
        }
        catch (Exception ex)
        {
            ErrorLabel.Text = ex.ToString();
        }
    }
    protected void MakeItSo(object sender, EventArgs e)
    {
        HttpCookie cookie = Request.Cookies["BrowserDate"];
        if (cookie == null)
        {
            cookie = new HttpCookie("BrowserDate");
            cookie.Value = DateTime.Now.ToString();
            cookie.Expires = DateTime.Now.AddDays(22);
            Response.Cookies.Add(cookie);
        }
        Data dat = new Data(DateTime.Parse(cookie.Value.ToString().Replace("%20", " ").Replace("%3A", ":")));
        try
        {
            bool hasState = false;
            if (StateDropDown.Visible && StateDropDown.SelectedValue != "-1")
                hasState = true;

            if (!StateDropDown.Visible && StateTextBox.THE_TEXT.Trim() != "")
                hasState = true;

            bool hasCity = false;
            if (CityTextBox.THE_TEXT.Trim() != "")
                hasCity = true;

            bool hasHeadr = false;
            if (HowHeardTextBox.THE_TEXT.Trim() != "")
                hasHeadr = true;

            UserNameTextBox.THE_TEXT = UserNameTextBox.THE_TEXT.Trim().Replace(" ", "");
            //ReferringUserName.Text = ReferringUserName.Text.Trim().Replace(" ", "");

            //if (!dat.TrapKey(ReferringUserName.Text, 1))
            //{
            //    MessageLabel.Text = "The Referring User Name cannot contain any illegal characters.";
            //    return;
            //}
            //else
            //{
            //    DataView dv = dat.GetDataDV("SELECT * FROM Users WHERE UserName='******'");
            //    if (dv.Count == 0)
            //    {
            //        MessageLabel.Text = "The Referring User Name you have provided does not exist in our system.";
            //        return;
            //    }
            //}

            MessageLabel.Text = "";
            if (hasCity && hasState && hasHeadr && UserNameTextBox.THE_TEXT != "" && PasswordTextBox.Text != "" &&
                ConfirmPasswordTextBox.Text != "" && ((FirstNameTextBox.THE_TEXT.Trim() != ""
                && LastNameTextBox.THE_TEXT.Trim() != "" && dat.TrapKey(FirstNameTextBox.THE_TEXT.Trim(), 1)
                && dat.TrapKey(LastNameTextBox.THE_TEXT.Trim(), 1))|| (FirstNameTextBox.THE_TEXT.Trim() == "" &&
                LastNameTextBox.THE_TEXT.Trim() == "")))
            {

                bool safeToGo = false;
                if (dat.TrapKey(UserNameTextBox.THE_TEXT, 1))
                {
                    DataSet ds = dat.GetData("SELECT * FROM Users WHERE UserName='******'");

                    string message = "";
                    if (ds.Tables.Count > 0)
                        if (ds.Tables[0].Rows.Count > 0)
                        {
                            message = "*This User Name already exists in the database. Choose a different User Name.";

                        }
                        else
                            safeToGo = true;
                    else
                        safeToGo = true;

                    ds = dat.GetData("SELECT * FROM Users WHERE Email='"+EmailLabel.Text+"'");

                    if (ds.Tables.Count > 0)
                        if (ds.Tables[0].Rows.Count > 0)
                        {
                            message += " This Email is already used by another user. You might have already completed this step. In that case, all you need to do is <a href=\"UserLogin.aspx\">Login</a>";
                            safeToGo = false;
                        }

                    if (safeToGo)
                    {
                        if (dat.TrapKey(PasswordTextBox.Text, 1))
                        {
                            safeToGo = true;
                        }
                        else
                        {
                            MessageLabel.Text = "*The Password can contain only letters and numbers.";
                            safeToGo = false;
                        }

                        if (safeToGo)
                        {
                            if (PasswordTextBox.Text == ConfirmPasswordTextBox.Text)
                                safeToGo = true;
                            else
                            {
                                safeToGo = false;
                                MessageLabel.Text = "*The Confirm Password must match the Password.";
                            }

                            if (safeToGo)
                            {
                                //if (CheckImageButton.ImageUrl == "image/CheckSelected.png")
                                //    safeToGo = true;
                                //else
                                //{
                                //    safeToGo = false;
                                //    MessageLabel.Text = "*Read and agree to the Terms And Conditions in order to sign up.";
                                //}

                                if (safeToGo)
                                {
                                    Encryption encrypt = new Encryption();
                                    string namesStart = "";
                                    string namesEnd = "";
                                    if (FirstNameTextBox.THE_TEXT.Trim() != "")
                                    {
                                        namesStart = ", FirstName, LastName";
                                        namesEnd = ", '" +
                                        dat.stripHTML(FirstNameTextBox.THE_TEXT.Trim().Replace("'", "''")) + "', '" +
                                        dat.stripHTML(LastNameTextBox.THE_TEXT.Trim().Replace("'", "''")) + "'";
                                    }
                                    dat.Execute("INSERT INTO Users (HowHeard, UserName, Email, Password, IPs" + namesStart + ", DateCreated) VALUES('" +
                                        HowHeardTextBox.THE_TEXT.Trim().Replace("'", "").Replace("\"", "") + "','" +
                                        UserNameTextBox.THE_TEXT + "', '" + EmailLabel.Text + "', '" +
                                        encrypt.encrypt(PasswordTextBox.Text) + "', ';" + dat.GetIP() + ";'" + namesEnd + ", GETDATE())");
                                    DataSet dsID = dat.GetData("SELECT User_ID FROM Users WHERE UserName='******'");
                                    string ID = dsID.Tables[0].Rows[0]["User_ID"].ToString();
                                    string message2 = "Welcome to Hippo Happenings! <br/> It is now your place for Events, "
                                    + "Venues, Classifieds and connecting with people in your area. <br/> To start, select your preferences"
                                    + " for filtering your content on the site by going to <a class=\"AddLink\" href=\"UserPreferences.aspx\">My Preferences</a>. ";
                                    dat.Execute("INSERT INTO UserPreferences (UserID, EventsAttended, CalendarPrivacyMode, CommunicationPrefs, CommentsPreferences, PollPreferences, CatCountry, EmailPrefs, RecommendationPrefs) VALUES (" + ID + ", 0, 1, 1, 1, 1, 223, '123456789C', 3)");
                                    dat.Execute("INSERT INTO UserMessages (MessageContent, MessageSubject, "
                                        + "From_UserID, To_UserID, Date, [Read], Mode, Live) VALUES('" + message2 +
                                        "', 'Hippo Happenings Welcome!', 6, " + ID + ", '" + DateTime.Parse(cookie.Value.ToString().Replace("%20", " ").Replace("%3A", ":")).ToString() + "', 'False', 1, 'True')");

                                    ds = dat.GetData("SELECT U.Password, U.User_ID, UP.CatCountry, UP.CatState, UP.CatCity, U.UserName FROM Users U, UserPreferences UP WHERE U.User_ID=UP.UserID AND U.UserName='******'");
                                    Session["UserName"] = UserNameTextBox.THE_TEXT.Trim();
                                    Session["User"] = ID;

                                    //insert all ad categories
                                    DataView dvCats = dat.GetDataDV("SELECT * FROM AdCategories WHERE isParent = 'True'");

                                    for (int i = 0; i < dvCats.Count; i++)
                                    {
                                        dat.Execute("INSERT INTO UserCategories (UserID, CategoryID) VALUES(" + ID + ", " + dvCats[i]["ID"].ToString() + ")");
                                    }

                                    string radius = "";
                                    if (RadiusPanel.Visible)
                                    {
                                        radius = ", Radius=" + RadiusDropDown.SelectedValue;
                                    }
                                    SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ToString());

                                    if (conn.State != ConnectionState.Open)
                                        conn.Open();
                                    SqlCommand cmd = new SqlCommand("UPDATE UserPreferences SET  " +
                                        " CatCountry=@catCountry, CatState=@catState, CatCity=@catCity, CatZip=@catZip" +
                                        radius +
                                        " WHERE UserID=@id ", conn);
                                    cmd.Parameters.Add("@id", SqlDbType.Int).Value = ID;
                                    cmd.Parameters.Add("@catCity", SqlDbType.NVarChar).Value = CityTextBox.THE_TEXT;

                                    if (CatZipTextBox.THE_TEXT.Trim() != "")
                                        cmd.Parameters.Add("@catZip", SqlDbType.NVarChar).Value =
                                            dat.GetAllZipsInRadius(RadiusDropDown.SelectedValue,
                                                    CatZipTextBox.THE_TEXT.Trim(), true);
                                    else
                                        cmd.Parameters.Add("@catZip", SqlDbType.NVarChar).Value = DBNull.Value;

                                    cmd.Parameters.Add("@catCountry", SqlDbType.Int).Value = CountryDropDown.SelectedValue;
                                    Session["UserCountry"] = CountryDropDown.SelectedValue;
                                    string state = "";
                                    if (StateDropDownPanel.Visible)
                                        state = StateDropDown.SelectedItem.Text;
                                    else
                                        state = StateTextBox.THE_TEXT;

                                    cmd.Parameters.Add("@catState", SqlDbType.NVarChar).Value = state;

                                    Session["UserState"] = state;
                                    Session["UserCity"] = CityTextBox;
                                    Session["UserCity"] = CatZipTextBox.THE_TEXT.Trim();

                                    cmd.ExecuteNonQuery();
                                    conn.Close();

                                    string groups = "User, Admin";
                                    //FormsAuthentication.RedirectFromLoginPage(txtUserName.Text, false);
                                    FormsAuthenticationTicket authTicket =
                                        new FormsAuthenticationTicket(1, ds.Tables[0].Rows[0]["User_ID"].ToString(),
                                                      DateTime.Parse(cookie.Value.ToString().Replace("%20", " ").Replace("%3A", ":")),
                                                      DateTime.Parse(cookie.Value.ToString().Replace("%20", " ").Replace("%3A", ":")).AddMinutes(60),
                                                      false, groups);

                                    // Now encrypt the ticket.
                                    string encryptedTicket =
                                      FormsAuthentication.Encrypt(authTicket);
                                    // Create a cookie and add the encrypted ticket to the
                                    // cookie as data.
                                    HttpCookie authCookie =
                                                 new HttpCookie(FormsAuthentication.FormsCookieName,
                                                                encryptedTicket);

                                    // Add the cookie to the outgoing cookies collection.
                                    Response.Cookies.Add(authCookie);
                                    dat.WhatHappensOnUserLogin(ds);

                                    //Send out welcome email
                                    dat.SendWelcome();

                                    Response.Redirect("User.aspx");

                                }
                            }

                        }

                    }
                    else
                    {
                        MessageLabel.Text = message;
                    }
                }
                else
                    MessageLabel.Text = "User Name can only contain letter and numbers.";
            }
            else
                MessageLabel.Text = "All fields with * must be filled in. If you include First and Last name, these cannot have any special keys, only letters. If you include one of the names, you must include the other.";
        }
        catch (Exception ex)
        {
            MessageLabel.Text = ex.ToString();
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        HttpCookie cookie = Request.Cookies["BrowserDate"];
        if (cookie == null)
        {
            cookie = new HttpCookie("BrowserDate");
            cookie.Value = DateTime.Now.ToString();
            cookie.Expires = DateTime.Now.AddDays(22);
            Response.Cookies.Add(cookie);
        }
        Data dat = new Data(DateTime.Parse(cookie.Value.ToString().Replace("%20", " ").Replace("%3A", ":")));
        DataSet ds;

        HtmlHead head = (HtmlHead)Page.Header;

        if (Request.QueryString["ID"] != null)
        {
            string catID = Request.QueryString["ID"].ToString();

            string location = "";

            //Get the location
            if (Session["User"] != null)
            {
                DataView dvPrefs = dat.GetDataDV("SELECT * FROM UserPreferences WHERE UserID=" + Session["User"].ToString());
                location = " AND G.State='" + dvPrefs[0]["CatState"].ToString() + "' AND G.City='" +
                    dvPrefs[0]["CatCity"].ToString() + "'";
            }
            else
            {
                DataView dvIP = dat.GetDataDV("SELECT * FROM Users U, UserPreferences UP WHERE UP.UserID=U.User_ID AND U.IPs LIKE '%;" + dat.GetIP() + ";%'");

                //If one or multiple found, look up ads on city and state of the first record
                if (dvIP.Count > 0)
                {
                    location = " AND G.State='" + dvIP[0]["CatState"].ToString() +
                        "' AND G.City='" + dvIP[0]["CatCity"].ToString() + "'";
                }
                //If not found look in searches table, get the city and state
                else
                {
                    DataView dvSearch = dat.GetDataDV("SELECT * FROM SearchIPs WHERE IP='" + dat.GetIP() + "'");
                    location = " AND G.State='" + dvSearch[0]["State"].ToString() +
                        "' AND G.City='" + dvSearch[0]["City"].ToString() + "'";
                }
            }

            ds = dat.GetData("SELECT * FROM Groups G, Group_Category GC, GroupCategories GCC WHERE GCC.ID=" +
                catID + " AND GC.Category_ID=GCC.ID AND G.ID=GC.Group_ID " + location);

            SearchElements.GROUP_DS = ds;
            SearchElements.DataBind2();

            NumResultsLabel.Text = "(" + ds.Tables[0].Rows.Count + " Records Found)";

            string theLink = "http://" + Request.Url.Authority + "/" +
            dat.MakeNiceName(ds.Tables[0].Rows[0]["GroupName"].ToString()) + "_" + catID + "_Group_Category";

            HtmlLink lk = new HtmlLink();
            lk.Href = theLink;
            lk.Attributes.Add("rel", "bookmark");
            head.Controls.AddAt(0, lk);

            HtmlMeta hm = new HtmlMeta();
            HtmlMeta kw = new HtmlMeta();
            HtmlMeta dc = new HtmlMeta();

            kw.Name = "keywords";
            kw.Content = ds.Tables[0].Rows[0]["GroupName"].ToString() + " Group Category";

            head.Controls.AddAt(0, kw);

            dc.Name = "description";
            dc.Content = "Results for group category: " + ds.Tables[0].Rows[0]["GroupName"].ToString();

            head.Controls.AddAt(0, dc);

            SearchResultsTitleLabel.Text = "<a href=\"" + theLink + "\" style=\"text-decoration: none; color: white;\" >Groups in '" +
                ds.Tables[0].Rows[0]["GroupName"].ToString() + "' Category</a>";
        }
        else
        {
            Response.Redirect("home");
        }
    }
    protected void MakeItSo(object sender, EventArgs e)
    {
        HttpCookie cookie = Request.Cookies["BrowserDate"];
        if (cookie == null)
        {
            cookie = new HttpCookie("BrowserDate");
            cookie.Value = DateTime.Now.ToString();
            cookie.Expires = DateTime.Now.AddDays(22);
            Response.Cookies.Add(cookie);
        }
        Data dat = new Data(DateTime.Parse(cookie.Value.ToString().Replace("%20", " ").Replace("%3A", ":")));
        try
        {
            bool hasState = false;
            if (StateDropDown.Visible && StateDropDown.SelectedValue != "-1")
                hasState = true;

            if (!StateDropDown.Visible && StateTextBox.Text.Trim() != "")
                hasState = true;

            bool hasCity = false;
            if (CityTextBox.Text.Trim() != "")
                hasCity = true;

            bool hasHeadr = false;
            if (HowHeardTextBox.Text.Trim() != "")
                hasHeadr = true;

            bool hasZip = false;
            if (CatZipTextBox.Text.Trim() != "")
                hasZip = true;

            UserNameTextBox.Text = UserNameTextBox.Text.Trim().Replace(" ", "");

            MessageLabel.Text = "";
            if (hasZip && hasCity && hasState && hasHeadr && UserNameTextBox.Text != "" && PasswordTextBox.Text != "" &&
                ConfirmPasswordTextBox.Text != "" && ((FirstNameTextBox.Text.Trim() != ""
                && LastNameTextBox.Text.Trim() != "" && dat.TrapKey(FirstNameTextBox.Text.Trim(), 1)
                && dat.TrapKey(LastNameTextBox.Text.Trim(), 1))|| (FirstNameTextBox.Text.Trim() == "" &&
                LastNameTextBox.Text.Trim() == "")))
            {

                bool safeToGo = false;
                if (dat.TrapKey(UserNameTextBox.Text, 1))
                {
                    DataSet ds = dat.GetData("SELECT * FROM Users WHERE UserName='******'");

                    string message = "";
                    if (ds.Tables.Count > 0)
                        if (ds.Tables[0].Rows.Count > 0)
                        {
                            message = "*This User Name already exists in the database. Choose a different User Name.";

                        }
                        else
                            safeToGo = true;
                    else
                        safeToGo = true;

                    ds = dat.GetData("SELECT * FROM Users WHERE Email='"+EmailLabel.Text+"'");

                    if (ds.Tables.Count > 0)
                        if (ds.Tables[0].Rows.Count > 0)
                        {
                            message += " This Email is already used by another user. You might have already completed this step. In that case, all you need to do is <a href=\"login\">Login</a>";
                            safeToGo = false;
                        }

                    if (safeToGo)
                    {
                        if (dat.TrapKey(PasswordTextBox.Text, 1))
                        {
                            safeToGo = true;
                        }
                        else
                        {
                            MessageLabel.Text = "*The Password can contain only letters and numbers.";
                            safeToGo = false;
                        }

                        if (safeToGo)
                        {
                            if (PasswordTextBox.Text == ConfirmPasswordTextBox.Text)
                                safeToGo = true;
                            else
                            {
                                safeToGo = false;
                                MessageLabel.Text = "*The Confirm Password must match the Password.";
                            }

                            if (safeToGo)
                            {
                                if (safeToGo)
                                {
                                    Encryption encrypt = new Encryption();
                                    string namesStart = "";
                                    string namesEnd = "";
                                    if (FirstNameTextBox.Text.Trim() != "")
                                    {
                                        namesStart = ", FirstName, LastName";
                                        namesEnd = ", '" +
                                        dat.stripHTML(FirstNameTextBox.Text.Trim().Replace("'", "''")) + "', '" +
                                        dat.stripHTML(LastNameTextBox.Text.Trim().Replace("'", "''")) + "'";
                                    }
                                    dat.Execute("INSERT INTO Users (HowHeard, UserName, Email, Password, IPs" + namesStart + ", DateCreated) VALUES( '" +
                                        HowHeardTextBox.Text.Trim().Replace("'", "").Replace("\"", "") + "','" +
                                        UserNameTextBox.Text + "', '" + EmailLabel.Text + "', '" +
                                        encrypt.encrypt(PasswordTextBox.Text) + "', ';" + dat.GetIP() + ";'" + namesEnd + ", GETDATE())");
                                    DataSet dsID = dat.GetData("SELECT User_ID FROM Users WHERE UserName='******'");
                                    string ID = dsID.Tables[0].Rows[0]["User_ID"].ToString();
                                    string message2 = "Welcome to Hippo Happenings! <br/> We strive to be your favorite place for Happenings, "
                                    + "Trips & Sights, Locales, Bulletins and connecting with people in your area. <br/>So, let's "+
                                    "do it. Explore our site by posting events in your area, add them to your calendar and "+
                                    "share with your friends at <a href=\"http://hippohappenings.com/blog-event\">Post an Event</a>. " +
                                    "Spread word about your favorite locales by entering them into the Hippo at <a href=\"http://hippohappen"+
                                    "ings.com/enter-locale\">Post a Locale</a>. And, share neighborhood and local trip's you've been "+
                                    "dying to tell people about at <a href=\"http://hippohappenings.com/enter-trip\">Post a Trip</a>. <br/>"+
                                    "Own a business? Need more people at your garage sale? Call out to your community via our bulletins at <a href=\"http://hippohappenings.com/Pos"+
                                    "tAnAd.aspx\">Post a Bulletin</a><br/><br/>";
                                    dat.Execute("INSERT INTO UserPreferences (Mayors, UserID, EventsAttended, CalendarPrivacyMode, CommunicationPrefs, CommentsPreferences, PollPreferences, CatCountry, EmailPrefs, RecommendationPrefs, MajorCity) VALUES ('" +
                                        BossCheckBox.Checked.ToString() + "'," + ID + ", 0, 1, 1, 1, 1, 223, '123456789C', 3, " + MajorCityDropDown.SelectedItem.Value + ")");
                                    dat.Execute("INSERT INTO UserMessages (MessageContent, MessageSubject, "
                                        + "From_UserID, To_UserID, Date, [Read], Mode, Live) VALUES('" + message2.Replace("'", "''") +
                                        "', 'Hippo Happenings Welcome!', 6, " + ID + ", '" + DateTime.Parse(cookie.Value.ToString().Replace("%20", " ").Replace("%3A", ":")).ToString() + "', 'False', 1, 'True')");

                                    ds = dat.GetData("SELECT U.Password, U.User_ID, UP.CatCountry, UP.CatState, UP.CatCity, U.UserName FROM Users U, UserPreferences UP WHERE U.User_ID=UP.UserID AND U.UserName='******'");
                                    Session["UserName"] = UserNameTextBox.Text.Trim();
                                    Session["User"] = ID;

                                    //insert all ad categories
                                    DataView dvCats = dat.GetDataDV("SELECT * FROM AdCategories WHERE isParent = 'True'");

                                    for (int i = 0; i < dvCats.Count; i++)
                                    {
                                        dat.Execute("INSERT INTO UserCategories (UserID, CategoryID) VALUES(" + ID + ", " + dvCats[i]["ID"].ToString() + ")");
                                    }

                                    SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ToString());

                                    if (conn.State != ConnectionState.Open)
                                        conn.Open();
                                    SqlCommand cmd = new SqlCommand("UPDATE UserPreferences SET  " +
                                        " CatCountry=@catCountry, MajorCity=@major, CatState=@catState, CatCity=@catCity, CatZip=@catZip WHERE UserID=" + ID, conn);
                                    cmd.Parameters.Add("@id", SqlDbType.Int).Value = ID;
                                    cmd.Parameters.Add("@catCity", SqlDbType.NVarChar).Value = CityTextBox.Text;

                                    cmd.Parameters.Add("@catZip", SqlDbType.NVarChar).Value = CatZipTextBox.Text.Trim();

                                    if (CountryDropDown.SelectedValue == "223")
                                    {
                                        cmd.Parameters.Add("@major", SqlDbType.Int).Value = MajorCityDropDown.SelectedValue;
                                    }
                                    else
                                    {
                                        cmd.Parameters.Add("@major", SqlDbType.Int).Value = DBNull.Value;
                                    }

                                    cmd.Parameters.Add("@catCountry", SqlDbType.Int).Value = CountryDropDown.SelectedValue;
                                    Session["UserCountry"] = CountryDropDown.SelectedValue;
                                    string state = "";
                                    if (StateDropDownPanel.Visible)
                                        state = StateDropDown.SelectedItem.Text;
                                    else
                                        state = StateTextBox.Text;

                                    cmd.Parameters.Add("@catState", SqlDbType.NVarChar).Value = state;

                                    Session["UserState"] = state;
                                    Session["UserCity"] = CityTextBox;
                                    Session["UserCity"] = CatZipTextBox.Text.Trim();

                                    cmd.ExecuteNonQuery();
                                    conn.Close();

                                    dat.WhatHappensOnUserLogin(ds);

                                    //Send out welcome email
                                    dat.SendWelcome();

                                    Response.Redirect("my-account");

                                }
                            }

                        }

                    }
                    else
                    {
                        MessageLabel.Text = message;
                    }
                }
                else
                    MessageLabel.Text = "User Name can only contain letter and numbers.";
            }
            else
                MessageLabel.Text = "All fields with * must be filled in. If you include First and Last name, these cannot have any special keys, only letters. If you include one of the names, you must include the other.";
        }
        catch (Exception ex)
        {
            MessageLabel.Text = ex.ToString();
        }
    }
    protected void SaveLocation(object sender, EventArgs e)
    {
        try
        {
            HttpCookie cookie = Request.Cookies["BrowserDate"];
            DateTime isn = DateTime.Now;

            DateTime.TryParse(cookie.Value.ToString().Replace("%20", " ").Replace("%3A", ":"), out isn);

            Data dat = new Data(isn);
            if ((StateTextBoxPanel.Visible && StateTextBox.Text.Trim() != "") ||
                (!StateTextBoxPanel.Visible && StateDropDown.SelectedItem.Text != "State"))
            {
                if (CityTextBox.Text.Trim() != "")
                {
                    CityTextBox.Text = dat.stripHTML(CityTextBox.Text.Trim());
                    Session["LocCountry"] = CountryDropDown.SelectedItem.Value.Trim();
                    string state = "";
                    if (StateTextBoxPanel.Visible)
                    {
                        Session["LocState"] = StateTextBox.Text.Trim();
                        state = StateTextBox.Text.Trim();
                    }
                    else
                    {
                        Session["LocState"] = StateDropDown.SelectedItem.Text.Trim();
                        state = StateDropDown.SelectedItem.Text.Trim();
                    }

                    Session["LocCity"] = CityTextBox.Text.Trim();

                    if (CountryDropDown.SelectedValue == "223")
                    {
                        DataView dvCity = dat.GetDataDV("SELECT * FROM MajorZips MZ, MajorCities MC, State S WHERE " +
                        "MZ.MajorCityID=MC.ID AND S.state_2_code='" + state +
                        "' AND S.state_name=State AND MajorCity='" + CityTextBox.Text.Trim() + "'");

                        //ErrorLabel.Text = "SELECT * FROM MajorZips MZ, MajorCities MC, State S WHERE " +
                        //"MZ.MajorCityID=MC.ID AND S.state_2_code='" + state +
                        //"' AND S.state_name=State AND MajorCity='" + CityTextBox.Text.Trim() + "'";

                        string zip = "";

                        if (dvCity.Count == 0)
                        {
                            dvCity = dat.GetDataDV("SELECT * FROM MajorZips MZ, MajorCities MC, State S WHERE " +
                                "MZ.MajorCityID=MC.ID AND S.state_2_code='" + state +
                                "' AND S.state_name=State");
                            zip = dvCity[0]["MajorCityZip"].ToString();
                        }
                        else
                        {
                            zip = dvCity[0]["MajorCityZip"].ToString();
                        }

                        DataView dvZip = dat.GetDataDV("SELECT * FROM ZipCodes WHERE Zip=" + zip);
                        int count = 1;
                        while (dvZip.Count == 0)
                        {
                            if (dvCity.Count >= count + 1)
                            {
                                zip = dvCity[count]["MajorCityZip"].ToString();
                                count++;
                                dvZip = dat.GetDataDV("SELECT * FROM ZipCodes WHERE Zip=" + zip);
                            }
                            else
                            {
                                break;
                            }
                        }

                        if (dvZip.Count != 0)
                        {
                            Session["LocLat"] = dvZip[0]["Latitude"].ToString();
                            Session["LocLong"] = dvZip[0]["Longitude"].ToString();
                        }
                    }

                    DataView dvCheck = dat.GetDataDV("SELECT * FROM IpToLocation WHERE IP='" + dat.GetIP() + "'");

                    if (dvCheck.Count > 0)
                    {
                        dat.Execute("UPDATE IpToLocation SET State = '" + Session["LocState"].ToString() +
                            "', City = '" + Session["LocCity"].ToString() + "', Country = '" + Session["LocCountry"].ToString() + "' WHERE IP='" + dat.GetIP() + "'");
                    }
                    else
                    {
                        dat.Execute("INSERT INTO IpToLocation (State, City, Country, IP) VALUES ('" + Session["LocState"].ToString() +
                            "', '" + Session["LocCity"].ToString() + "', '" + Session["LocCountry"].ToString() + "','" + dat.GetIP() + "')");
                    }

                    BottomScript.Text = "<script type=\"text/javascript\">Search('anything');</script>";
                }
                else
                {
                    ErrorLabel.Text = "<br />Please Include the City.<br /><br />";
                }
            }
            else
            {
                ErrorLabel.Text = "<br />Please Include the State.<br /><br />";
            }
        }
        catch (Exception ex)
        {
            ErrorLabel.Text += ex.ToString();
        }
    }
    protected void PostIt(object sender, EventArgs e)
    {
        MessagePanel.Visible = false;
        YourMessagesLabel.Text = "";

        string problem = "";
        bool hasEditChanged = false;
        bool chargeCard = false;
        AuthorizePayPal d = new AuthorizePayPal();
        HttpCookie cookie = Request.Cookies["BrowserDate"];

        DateTime isn = DateTime.Now;

        if (!DateTime.TryParse(cookie.Value.ToString().Replace("%20", " ").Replace("%3A", ":"), out isn))
            isn = DateTime.Now;
        DateTime isNow = isn;
        Data dat = new Data(isn); string email = "";
        try
        {
            if (OnwardsIT())
            {
                //Add case for if Paypal is filled in...
                //Authorize Credit Card
                bool goOn = false;
                string message = "";
                decimal price = 0.00M;
                string transactionID = "";

                if (AgreeCheckBox.Checked)
                {
                    if (TotalLabel.Text.Trim() != "")
                    {
                        if (decimal.TryParse(TotalLabel.Text.Trim(), out price))
                        {
                            if (price != 0.00M)
                            {
                                if (FirstNameTextBox.Text.Trim() == "" || LastNameTextBoxtBox.Text.Trim() == "" ||
                                   BillingStreetAddressTextBox.Text.Trim() == "" || BillingCityTextBox.Text.Trim() == "" ||
                                   BillingZipCodeTextBox.Text.Trim() == "" || BillingStateTextBox.Text.Trim() == "" ||
                                   CardNumberTextBox.Text.Trim() == "" || CSVTextBox.Text.Trim() == "")
                                {
                                    goOn = false;
                                    Session["Featured"] = false;
                                    message = "Please fill in all of the billing information.";
                                }
                                else
                                {
                                    goOn = false;
                                    Session["Featured"] = false;
                                    string country = dat.GetDataDV("SELECT country_2_code FROM Countries WHERE country_id=" + BillingCountry.SelectedValue)[0]["country_2_code"].ToString();

                                    com.paypal.sdk.util.NVPCodec status = d.DoPayment("Authorization", TotalLabel.Text, CardTypeDropDown.SelectedValue, CardNumberTextBox.Text.Trim(),
                                        ExpirationMonth.SelectedItem.Text, ExpirationYear.SelectedItem.Text, CSVTextBox.Text.Trim(), FirstNameTextBox.Text.Trim(), LastNameTextBoxtBox.Text.Trim(),
                                        BillingStreetAddressTextBox.Text.Trim(), BillingCityTextBox.Text, BillingStateTextBox.Text, country, BillingZipCodeTextBox.Text.Trim(), dat.GetIP());
                                    message = status.ToString();
                                    string successORFailure = status["ACK"];

                                    switch (successORFailure.ToLower())
                                    {
                                        case "failure":
                                            goOn = false;
                                            Session["Featured"] = false;
                                            message = status["L_LONGMESSAGE0"];
                                            break;
                                        case "successwithwarning":
                                            goOn = false;
                                            Session["Featured"] = false;
                                            message = status["L_SHORTMESSAGE0"];
                                            if (message == "Transaction approved but with invalid CSC format.")
                                                message = "Your CVC/CSV format for this card is not valid.";
                                            break;
                                        case "success":
                                            chargeCard = true;
                                            transactionID = status["TRANSACTIONID"];
                                            Session["TransID"] = transactionID;
                                            goOn = true;
                                            Session["Featured"] = true;
                                            break;
                                        default:
                                            goOn = false;
                                            Session["Featured"] = false;
                                            message = "There was an internal problem. Please contact support at: [email protected]. Please include as much detail as possible about what you are trying to do.";
                                            foreach (string key in status.Keys)
                                            {
                                                message += "key: " + key.ToString() + ", value: " + status[key].ToString() + "<br/>";
                                            }
                                            break;
                                    }
                                }
                            }
                            else
                            {
                                goOn = true;
                                Session["Featrued"] = false;
                            }
                        }
                        else
                        {
                            goOn = true;
                            Session["Featured"] = false;
                        }
                    }
                    else
                    {
                        goOn = true;
                        Session["Featured"] = false;
                    }

                    if (goOn)
                    {

                        string textEmail = "";
                        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ToString());
                        conn.Open();

                        string mediaCat = "0";
                        if (PictureCheckList.Items.Count > 0)
                            mediaCat = "1";

                        bool isOwner = false;

                        string ownerID = "";
                        bool ownerUpForGrabs = false;
                        bool wasFeatured = false;
                        bool isEditing = false;
                        if (isEdit.Text != "")
                        {
                            isEditing = bool.Parse(isEdit.Text);
                            ownerUpForGrabs = dat.IsOwnerUpForGrabs(Request.QueryString["ID"].ToString(),
                                ref ownerID, ref isOwner, false);
                        }

                        bool hadSongs = false;
                        DataSet dsEvent = new DataSet();
                        DataView dvEvent = new DataView();
                        string theCat = "NULL";
                        if (isEditing)
                        {
                            dsEvent = dat.GetData("SELECT * FROM Events WHERE ID=" + eventID.Text);
                            dvEvent = dat.GetDataDV("SELECT * FROM Events WHERE ID=" + eventID.Text);
                            wasFeatured = bool.Parse(dsEvent.Tables[0].Rows[0]["Featured"].ToString());

                            hadSongs = bool.Parse(dsEvent.Tables[0].Rows[0]["hasSongs"].ToString());

                            if (dsEvent.Tables[0].Rows[0]["MediaCategory"].ToString() != mediaCat)
                            {
                                theCat = mediaCat;
                                hasEditChanged = true;
                            }
                        }

                        string addAdressBeg = "";
                        string addAddressEnd = "";
                        string addAddressUpdate = "";

                        string privInsertBeg = ", Private ";
                        string privInsertEnd = ", 'False' ";
                        string privUpdate = ", Private = 'False' ";

                        if (LocaleRadioButtonList.SelectedValue == "1")
                        {
                            addAdressBeg = ", Address ";
                            addAddressEnd = ", @address";
                            addAddressUpdate = ", Address = @address ";

                            privInsertBeg = ", Private ";
                            privInsertEnd = ", 'True' ";
                            privUpdate = ", Private = 'True' ";

                        }

                        string command = "";
                        if (isEditing)
                        {
                            if (isOwner || ownerUpForGrabs)
                            {
                                string sngs = "";
                                if (!hadSongs)
                                    sngs = "hasSongs=@songs,";

                                command = "UPDATE Events SET DaysFeatured=@daysFet, " + addAddressUpdate + privUpdate + "Featured=@fet, MinPrice=@min, MaxPrice=@max, Owner=@owner, [Content]=@content, Header=@header, " +
                                    "Venue=@venue,SponsorPresenter=@sponsor, " + sngs + " mediaCategory=" + mediaCat + ", " +
                                    "ShortDescription=@shortDescription, Country=@country, State=@state, " +
                                    "Zip=@zip, City=@city, LastEditOn=@dateP WHERE ID=" + Request.QueryString["ID"].ToString();
                            }
                            else
                            {
                                command = "INSERT INTO EventRevisions (DaysFeatured," + addAdressBeg + privInsertBeg + "Featured,MinPrice, MaxPrice, EventID, [Content], " +
                                    "Header, Venue, modifierID, "
                                + "ShortDescription, Country, State, Zip, City, DATE)"
                                    + " VALUES(@daysFet, " + addAddressEnd + privInsertEnd + "@fet,@min, @max, " + eventID.Text + ", @content,@header, @venue, @userName, @shortDescription"
                                + ", @country, @state, @zip, @city, '" + isn.ToString() + "')";

                                dsEvent = dat.GetData("SELECT * FROM Events WHERE ID=" + eventID.Text);
                            }
                        }
                        else
                        {
                            command = "INSERT INTO Events (DaysFeatured" + addAdressBeg + privInsertBeg + ", Featured,MinPrice, MaxPrice, Owner, [Content], " +
                                 "Header, Venue, EventGoersCount, SponsorPresenter, hasSongs, mediaCategory, UserName, "
                             + "ShortDescription, Country, State, Zip, City, StarRating, PostedOn, LastEditOn)"
                                 + " VALUES(@daysFet" + addAddressEnd + privInsertEnd + ", @fet, @min, @max, @owner, @content, @header, @venue, "
                                 + " @eventGoers, @sponsor, @songs, " + mediaCat + ", @userName, @shortDescription"
                             + ", @country, @state, @zip, @city, 0, @dateP, @dateP)";
                        }

                        SqlCommand cmd = new SqlCommand(command, conn);
                        cmd.CommandType = CommandType.Text;
                        cmd.Parameters.Add("@dateP", SqlDbType.DateTime).Value = DateTime.Now;

                        string fetDays = "";
                        foreach (ListItem item in FeatureDatesListBox.Items)
                        {
                            fetDays += ";" + item.Text + ";";
                        }

                        if (wasFeatured)
                        {
                            cmd.Parameters.Add("@fet", SqlDbType.Bit).Value = true;

                            if (FeaturePanel.Visible)
                            {
                                cmd.Parameters.Add("@daysFet", SqlDbType.NVarChar).Value = fetDays;
                            }
                            else
                                cmd.Parameters.Add("@daysFet", SqlDbType.NVarChar).Value = dvEvent[0]["DaysFeatured"].ToString();
                        }
                        else
                        {
                            cmd.Parameters.Add("@fet", SqlDbType.Bit).Value = FeaturePanel.Visible;
                            if (FeaturePanel.Visible)
                            {
                                cmd.Parameters.Add("@daysFet", SqlDbType.NVarChar).Value = fetDays;
                            }
                            else
                            {
                                cmd.Parameters.Add("@daysFet", SqlDbType.NVarChar).Value = DBNull.Value;
                            }
                        }

                        if (MinTextBox.Text.Trim() != "")
                        {
                            cmd.Parameters.Add("@min", SqlDbType.Decimal).Value = decimal.Parse(MinTextBox.Text.Trim());
                        }
                        else
                        {
                            cmd.Parameters.Add("@min", SqlDbType.Decimal).Value = DBNull.Value;
                        }

                        if (MaxTextBox.Text.Trim() != "")
                        {
                            cmd.Parameters.Add("@max", SqlDbType.Decimal).Value = decimal.Parse(MaxTextBox.Text.Trim());
                        }
                        else
                        {
                            cmd.Parameters.Add("@max", SqlDbType.Decimal).Value = DBNull.Value;
                        }

                        if (isEditing && !isOwner)
                        {
                            if (ownerUpForGrabs)
                            {
                                if (OwnerCheckBox.Checked)
                                {
                                    hasEditChanged = true;
                                    cmd.Parameters.Add("@owner", SqlDbType.Int).Value = Session["User"].ToString();
                                    dat.Execute("INSERT INTO EventOwnerHistory (EventID, OwnerID, DateCreatedOwnership) " +
                                        "VALUES(" + eventID.Text + ", " + Session["User"].ToString() + ", '" + isn.ToString() + "')");
                                }
                                else
                                {
                                    if (ownerUpForGrabs)
                                    {
                                        cmd.Parameters.Add("@owner", SqlDbType.Int).Value = DBNull.Value;
                                    }
                                }
                            }
                            else
                            {

                            }

                            if (dsEvent.Tables[0].Rows[0]["Content"].ToString() != DescriptionTextBox.Content)
                            {
                                cmd.Parameters.Add("@content", SqlDbType.NVarChar).Value = DescriptionTextBox.Content;
                                hasEditChanged = true;
                            }
                            else
                            {
                                if (ownerUpForGrabs)
                                {
                                    cmd.Parameters.Add("@content", SqlDbType.NVarChar).Value = dsEvent.Tables[0].Rows[0]["Content"].ToString();
                                }
                                else
                                {
                                    cmd.Parameters.Add("@content", SqlDbType.NVarChar).Value = DBNull.Value;
                                }
                            }

                            if (dsEvent.Tables[0].Rows[0]["Header"].ToString() != EventNameTextBox.Text)
                            {
                                cmd.Parameters.Add("@header", SqlDbType.NVarChar).Value = EventNameTextBox.Text;
                                hasEditChanged = true;
                            }
                            else
                            {
                                if (ownerUpForGrabs)
                                {
                                    hasEditChanged = true;
                                    cmd.Parameters.Add("@header", SqlDbType.NVarChar).Value = dsEvent.Tables[0].Rows[0]["Header"].ToString();
                                }
                                else
                                {
                                    cmd.Parameters.Add("@header", SqlDbType.NVarChar).Value = DBNull.Value;
                                }
                            }

                            string shortDesc = DescriptionTextBox.Text;
                            if (shortDesc.Length > 150)
                                shortDesc = shortDesc.Substring(0, 150);

                            if (dsEvent.Tables[0].Rows[0]["ShortDescription"].ToString() != shortDesc)
                            {
                                cmd.Parameters.Add("@shortDescription", SqlDbType.NVarChar).Value = shortDesc;
                                hasEditChanged = true;
                            }
                            else
                            {
                                if (ownerUpForGrabs)
                                {
                                    cmd.Parameters.Add("@shortDescription", SqlDbType.NVarChar).Value =
                                        dsEvent.Tables[0].Rows[0]["ShortDescription"].ToString();
                                    hasEditChanged = true;
                                }
                                else
                                {
                                    cmd.Parameters.Add("@shortDescription", SqlDbType.NVarChar).Value = DBNull.Value;
                                }
                            }

                            //users that are not the owner are not allowed to delete songs or other media
                            //therefore, users can only change the state of 'hasSongs' to 'true', never to 'false'
                            if (ownerUpForGrabs && MusicCheckBox.Checked)
                            {
                                cmd.Parameters.Add("@songs", SqlDbType.Bit).Value = MusicCheckBox.Checked;
                                hasEditChanged = true;
                            }
                            else
                            {
                                cmd.Parameters.Add("@songs", SqlDbType.Bit).Value = dsEvent.Tables[0].Rows[0]["hasSongs"].ToString();
                            }

                            cmd.Parameters.Add("@sponsor", SqlDbType.NVarChar).Value = DBNull.Value;
                        }
                        else
                        {
                            string shortDesc = DescriptionTextBox.Text;
                            if (shortDesc.Length > 150)
                                shortDesc = shortDesc.Substring(0, 150);

                            hasEditChanged = true;
                            cmd.Parameters.Add("@content", SqlDbType.NVarChar).Value = DescriptionTextBox.Content;
                            cmd.Parameters.Add("@header", SqlDbType.NVarChar).Value = EventNameTextBox.Text;
                            cmd.Parameters.Add("@shortDescription", SqlDbType.NVarChar).Value = shortDesc;
                            cmd.Parameters.Add("@songs", SqlDbType.Bit).Value = MusicCheckBox.Checked;

                            if (!isEditing)
                            {
                                cmd.Parameters.Add("@rating", SqlDbType.Int).Value = 0;
                                cmd.Parameters.Add("@userName", SqlDbType.NVarChar).Value = Session["UserName"].ToString();
                                cmd.Parameters.Add("@eventGoers", SqlDbType.Int).Value = 0;
                                if (OwnerCheckBox.Checked)
                                {
                                    cmd.Parameters.Add("@owner", SqlDbType.Int).Value = Session["User"].ToString();
                                }
                                else
                                {
                                    cmd.Parameters.Add("@owner", SqlDbType.Int).Value = DBNull.Value;
                                }
                            }
                            else
                            {
                                if (isOwner)
                                {
                                    if (OwnerCheckBox.Checked)
                                        cmd.Parameters.Add("@owner", SqlDbType.NVarChar).Value = Session["User"].ToString();
                                    else
                                        cmd.Parameters.Add("@owner", SqlDbType.NVarChar).Value = DBNull.Value;
                                }
                            }

                            cmd.Parameters.Add("@sponsor", SqlDbType.NVarChar).Value = DBNull.Value;
                        }

                        #region Create/Assign Venue
                        string country = "";
                        string state1 = "";
                        string venue = "";
                        bool isNewVenue = false;
                        int venueID = 0;
                        if (LocaleRadioButtonList.SelectedValue == "0")
                        {
                            //Need to check if the user is creating a new venue.
                            //First If statement is if a user chose existing venue from dropdown
                            //The Else statement if for the new venue.

                            venueID = int.Parse(Session["NewVenue"].ToString());
                            DataSet dsVenue = dat.GetData("SELECT * FROM Venues WHERE ID=" + venueID.ToString());
                            venue = dsVenue.Tables[0].Rows[0]["Name"].ToString();
                            if (isEditing && !isOwner)
                            {
                                if (dsEvent.Tables[0].Rows[0]["Venue"].ToString() != venueID.ToString())
                                {
                                    hasEditChanged = true;
                                    cmd.Parameters.Add("@venue", SqlDbType.Int).Value = venueID;

                                    if (dsEvent.Tables[0].Rows[0]["Country"].ToString() != dsVenue.Tables[0].Rows[0]["Country"].ToString())
                                        cmd.Parameters.Add("@country", SqlDbType.Int).Value = dsVenue.Tables[0].Rows[0]["Country"].ToString();
                                    else
                                    {
                                        if (ownerUpForGrabs)
                                        {
                                            cmd.Parameters.Add("@country", SqlDbType.Int).Value = dsEvent.Tables[0].Rows[0]["Country"].ToString();
                                        }
                                        else
                                        {
                                            cmd.Parameters.Add("@country", SqlDbType.Int).Value = DBNull.Value;
                                        }
                                    }

                                    if (dsEvent.Tables[0].Rows[0]["State"].ToString() != dsVenue.Tables[0].Rows[0]["State"].ToString())
                                        cmd.Parameters.Add("@state", SqlDbType.NVarChar).Value = dsVenue.Tables[0].Rows[0]["State"].ToString();
                                    else
                                    {
                                        if (ownerUpForGrabs)
                                        {
                                            cmd.Parameters.Add("@state", SqlDbType.NVarChar).Value = dsEvent.Tables[0].Rows[0]["State"].ToString();
                                        }
                                        else
                                        {
                                            cmd.Parameters.Add("@state", SqlDbType.NVarChar).Value = DBNull.Value;
                                        }
                                    }
                                    if (dsEvent.Tables[0].Rows[0]["City"].ToString() != dsVenue.Tables[0].Rows[0]["City"].ToString())
                                        cmd.Parameters.Add("@city", SqlDbType.NVarChar).Value = dsVenue.Tables[0].Rows[0]["City"].ToString();
                                    else
                                    {
                                        if (ownerUpForGrabs)
                                        {
                                            cmd.Parameters.Add("@city", SqlDbType.NVarChar).Value = dsEvent.Tables[0].Rows[0]["City"].ToString();
                                        }
                                        else
                                        {
                                            cmd.Parameters.Add("@city", SqlDbType.NVarChar).Value = DBNull.Value;
                                        }

                                    }

                                    if (dsEvent.Tables[0].Rows[0]["Zip"].ToString() != dsVenue.Tables[0].Rows[0]["Zip"].ToString())
                                        cmd.Parameters.Add("@zip", SqlDbType.NVarChar).Value = dsVenue.Tables[0].Rows[0]["Zip"].ToString();
                                    else
                                    {
                                        if (ownerUpForGrabs)
                                        {
                                            cmd.Parameters.Add("@zip", SqlDbType.NVarChar).Value = dsEvent.Tables[0].Rows[0]["Zip"].ToString();
                                        }
                                        else
                                        {
                                            cmd.Parameters.Add("@zip", SqlDbType.NVarChar).Value = DBNull.Value;
                                        }
                                    }
                                }
                                else
                                {
                                    if (ownerUpForGrabs)
                                    {
                                        cmd.Parameters.Add("@venue", SqlDbType.Int).Value = dsEvent.Tables[0].Rows[0]["Venue"].ToString();
                                        cmd.Parameters.Add("@country", SqlDbType.Int).Value = dsEvent.Tables[0].Rows[0]["Country"].ToString();
                                        cmd.Parameters.Add("@state", SqlDbType.NVarChar).Value = dsEvent.Tables[0].Rows[0]["State"].ToString();
                                        cmd.Parameters.Add("@city", SqlDbType.NVarChar).Value = dsEvent.Tables[0].Rows[0]["City"].ToString();
                                        cmd.Parameters.Add("@zip", SqlDbType.NVarChar).Value = dsEvent.Tables[0].Rows[0]["Zip"].ToString();
                                    }
                                    else
                                    {
                                        cmd.Parameters.Add("@venue", SqlDbType.Int).Value = DBNull.Value;
                                        cmd.Parameters.Add("@country", SqlDbType.Int).Value = DBNull.Value;
                                        cmd.Parameters.Add("@state", SqlDbType.NVarChar).Value = DBNull.Value;
                                        cmd.Parameters.Add("@city", SqlDbType.NVarChar).Value = DBNull.Value;
                                        cmd.Parameters.Add("@zip", SqlDbType.NVarChar).Value = DBNull.Value;
                                    }
                                }
                            }
                            else
                            {
                                cmd.Parameters.Add("@venue", SqlDbType.Int).Value = venueID;
                                cmd.Parameters.Add("@country", SqlDbType.Int).Value = dsVenue.Tables[0].Rows[0]["Country"].ToString();
                                cmd.Parameters.Add("@state", SqlDbType.NVarChar).Value = dsVenue.Tables[0].Rows[0]["State"].ToString();
                                cmd.Parameters.Add("@city", SqlDbType.NVarChar).Value = dsVenue.Tables[0].Rows[0]["City"].ToString();
                                cmd.Parameters.Add("@zip", SqlDbType.NVarChar).Value = dsVenue.Tables[0].Rows[0]["Zip"].ToString();
                            }

                            country = dsVenue.Tables[0].Rows[0]["Country"].ToString();
                            state1 = dsVenue.Tables[0].Rows[0]["State"].ToString();
                        }
                        else
                        {
                            venue = dat.stripHTML(addressTextBox.Text.Trim());
                            string privState = "";
                            if (privateStateDropDown.Visible)
                                privState = privateStateDropDown.SelectedItem.Text;
                            else
                                privState = dat.stripHTML(privateStateTextBox.Text.Trim());

                            cmd.Parameters.Add("@venue", SqlDbType.NVarChar).Value = DBNull.Value;
                            cmd.Parameters.Add("@address", SqlDbType.NVarChar).Value = dat.stripHTML(addressTextBox.Text.Trim());
                            cmd.Parameters.Add("@country", SqlDbType.Int).Value = privateCountryDropDown.SelectedValue;
                            cmd.Parameters.Add("@state", SqlDbType.NVarChar).Value = privState;
                            cmd.Parameters.Add("@city", SqlDbType.NVarChar).Value = dat.stripHTML(cityTextBox.Text.Trim());
                            cmd.Parameters.Add("@zip", SqlDbType.NVarChar).Value = dat.stripHTML(ZipTextBox.Text.Trim());

                            country = privateCountryDropDown.SelectedValue;
                            state1 = privState;
                        }

                        #endregion

                        if (isEditing)
                        {
                            cmd.ExecuteNonQuery();
                        }

                        if (!isEditing || isOwner)
                        {
                            cmd.ExecuteNonQuery();
                        }

                        bool songsChanged = false;
                        bool mediaChanged = false;
                        bool occuranceChanged = false;

                        cmd = new SqlCommand("SELECT @@IDENTITY AS ID", conn);
                        SqlDataAdapter da2 = new SqlDataAdapter(cmd);
                        DataSet ds3 = new DataSet();
                        da2.Fill(ds3);

                        string revisionID = "";
                        if (isEditing && !isOwner && !ownerUpForGrabs)
                        {
                            revisionID = ds3.Tables[0].Rows[0]["ID"].ToString();
                        }
                        string ID = ds3.Tables[0].Rows[0]["ID"].ToString();

                        if (!isEditing)
                        {
                            if (OwnerCheckBox.Checked)
                            {
                                dat.Execute("INSERT INTO EventOwnerHistory (EventID, OwnerID, DateCreatedOwnership) " +
                                    "VALUES(" + ID + ", " + Session["User"].ToString() + ", '" + isn.ToString() + "')");
                            }
                        }

                        string firstStartDate = DateSelectionsListBox.Items[0].Text;

                        email += "<br/><br/><a href=\"http://HippoHappenings.com/" + dat.MakeNiceName(EventNameTextBox.Text) + "_" + ID +
                            "_Event\">" + EventNameTextBox.Text + "</a><br/><br/>" + venue + "<br/><br/>First Dates: " +
                            firstStartDate + "<br/><br/>" + DescriptionTextBox.Content;

                        textEmail = ". Name: " + EventNameTextBox.Text + ". Venue: " + venue + ". First Date: " +
                            firstStartDate +
                            ". Link: http://HippoHappenings.com/" + dat.MakeNiceName(EventNameTextBox.Text) + "_" + ID +
                            "_Event";

                        string temporaryID = "";
                        if (isEditing)
                        {
                            temporaryID = eventID.Text;
                        }
                        else
                        {

                            temporaryID = ID;
                        }

                        string categories =
                            CreateCategories(temporaryID, isOwner, isEditing, revisionID, ownerUpForGrabs);

                        if (isEditing)
                            ID = Request.QueryString["ID"].ToString();

                        //string temp = categories;

                        //if (categories != "")
                        //    temp += " OR ";
                        //temp += "UV.VenueID=" + venueID;

                        #region Take Care of Media

                        if (MusicCheckBox.Checked || hadSongs)
                        {
                            for (int i = 0; i < SongCheckList.Items.Count; i++)
                            {
                                if (isEditing)
                                {
                                    if (SongCheckList.Items[i].Enabled)
                                    {
                                        if (revisionID != "" && !isOwner && !ownerUpForGrabs)
                                        {
                                            cmd = new SqlCommand("INSERT INTO EventRevisions_Song_Mapping (RevisionID, EventID, SongName) " +
                                                "VALUES(" + revisionID + ",@eventID, @songName)", conn);
                                            cmd.Parameters.Add("@eventID", SqlDbType.Int).Value = int.Parse(eventID.Text);
                                            cmd.Parameters.Add("@songName", SqlDbType.NVarChar).Value = SongCheckList.Items[i].Value.ToString();
                                            cmd.ExecuteNonQuery();
                                        }
                                        songsChanged = true;

                                        dat.Execute("UPDATE Events SET hasSongs='True' WHERE ID=" + eventID.Text);

                                        if (i == 0)
                                            dat.Execute("DELETE FROM Event_Song_Mapping WHERE EventID=" + eventID.Text);

                                        cmd = new SqlCommand("INSERT INTO Event_Song_Mapping (EventID, SongName, SongTitle) " +
                                            "VALUES(@eventID, @songName, @songTitle)", conn);
                                        cmd.Parameters.Add("@eventID", SqlDbType.Int).Value = int.Parse(eventID.Text);
                                        cmd.Parameters.Add("@songName", SqlDbType.NVarChar).Value = SongCheckList.Items[i].Value.ToString();
                                        cmd.Parameters.Add("@songTitle", SqlDbType.NVarChar).Value = SongCheckList.Items[i].Text;
                                        cmd.ExecuteNonQuery();
                                    }
                                }
                                else
                                {
                                    dat.Execute("UPDATE Events SET hasSongs='True' WHERE ID=" + ID);

                                    cmd = new SqlCommand("INSERT INTO Event_Song_Mapping (EventID, SongName, SongTitle) " +
                                        "VALUES(@eventID, @songName, @songTitle)", conn);
                                    cmd.Parameters.Add("@eventID", SqlDbType.Int).Value = int.Parse(ID);
                                    cmd.Parameters.Add("@songName", SqlDbType.NVarChar).Value = SongCheckList.Items[i].Value.ToString();
                                    cmd.Parameters.Add("@songTitle", SqlDbType.NVarChar).Value = SongCheckList.Items[i].Text;
                                    cmd.ExecuteNonQuery();
                                }

                            }
                        }

                        //Media Categories: NONE: 0, Picture: 1, Video: 2, YouTubeVideo: 3, Slider: 4
                        bool isSlider = false;
                        if (PictureCheckList.Items.Count > 0)
                            isSlider = true;

                        string tempID = ID;
                        if (isEditing)
                        {
                            tempID = eventID.Text;
                        }

                        if (isSlider)
                        {

                            char[] delim2 = { '\\' };
                            string[] fileArray = System.IO.Directory.GetFiles(MapPath(".") + "\\UserFiles\\" + Session["EffectiveUserName"].ToString() + "\\Slider\\");

                            if (!System.IO.Directory.Exists(MapPath(".") + "\\UserFiles"))
                            {
                                System.IO.Directory.CreateDirectory(MapPath(".") + "\\UserFiles");
                                System.IO.Directory.CreateDirectory(MapPath(".") + "\\UserFiles\\Events\\");
                                System.IO.Directory.CreateDirectory(MapPath(".") + "\\UserFiles\\Events\\" + tempID);
                                System.IO.Directory.CreateDirectory(MapPath(".") + "\\UserFiles\\Events\\" + tempID + "\\Slider\\");
                            }
                            else
                            {
                                if (!System.IO.Directory.Exists(MapPath(".") + "\\UserFiles\\Events\\"))
                                {
                                    System.IO.Directory.CreateDirectory(MapPath(".") + "\\UserFiles\\Events\\");
                                    System.IO.Directory.CreateDirectory(MapPath(".") + "\\UserFiles\\Events\\" + tempID);
                                    System.IO.Directory.CreateDirectory(MapPath(".") + "\\UserFiles\\Events\\" + tempID + "\\Slider\\");
                                }
                                else
                                {
                                    if (!System.IO.Directory.Exists(MapPath(".") + "\\UserFiles\\Events\\" + tempID))
                                    {
                                        System.IO.Directory.CreateDirectory(MapPath(".") + "\\UserFiles\\Events\\" + tempID);
                                        System.IO.Directory.CreateDirectory(MapPath(".") + "\\UserFiles\\Events\\" + tempID + "\\Slider\\");
                                    }
                                    else
                                    {
                                        if (!System.IO.Directory.Exists(MapPath(".") + "\\UserFiles\\Events\\" + tempID + "\\Slider\\"))
                                        {
                                            System.IO.Directory.CreateDirectory(MapPath(".") + "\\UserFiles\\Events\\" + tempID + "\\Slider\\");
                                        }
                                    }
                                }
                            }

                            string YouTubeStr = "";
                            char[] delim3 = { '.' };
                            bool isPathAbsolute = false;
                            for (int i = 0; i < PictureCheckList.Items.Count; i++)
                            {
                                //int length = fileArray[i].Split(delim2).Length;
                                if (PictureCheckList.Items[i].Value == "ImgPathAbsolute")
                                    isPathAbsolute = true;
                                else
                                    isPathAbsolute = false;

                                if (isPathAbsolute)
                                {
                                    cmd = new SqlCommand("INSERT INTO Event_Slider_Mapping (EventID, PictureName, RealPictureName, ImgPathAbsolute) " +
                                                    "VALUES(@eventID, @picName, @realName, 'True')", conn);
                                    cmd.Parameters.Add("@eventID", SqlDbType.Int).Value = tempID;
                                    cmd.Parameters.Add("@picName", SqlDbType.NVarChar).Value = PictureCheckList.Items[i].Text;
                                    cmd.Parameters.Add("@realName", SqlDbType.NVarChar).Value = PictureCheckList.Items[i].Text;
                                    cmd.ExecuteNonQuery();
                                }
                                else
                                {
                                    string[] tokens = PictureCheckList.Items[i].Value.ToString().Split(delim3);

                                    if (tokens.Length >= 2)
                                    {
                                        if (tokens[1].ToUpper() == "JPG" || tokens[1].ToUpper() == "JPEG" || tokens[1].ToUpper() == "GIF" || tokens[1].ToUpper() == "PNG")
                                        {
                                            if (!System.IO.File.Exists(MapPath(".") + "\\UserFiles\\Events\\" + tempID + "\\Slider\\" + PictureCheckList.Items[i].Value))
                                            {
                                                System.IO.File.Copy(MapPath(".") + "\\UserFiles\\" + Session["EffectiveUserName"].ToString() +
                                                                        "\\Slider\\" + PictureCheckList.Items[i].Value,
                                                                        MapPath(".") + "\\UserFiles\\Events\\" + tempID + "\\Slider\\" + PictureCheckList.Items[i].Value);
                                            }

                                            if (isEditing)
                                            {

                                                if (revisionID != "" && !isOwner && !ownerUpForGrabs)
                                                {
                                                    if (PictureCheckList.Items[i].Enabled)
                                                    {
                                                        cmd = new SqlCommand("INSERT INTO EventRevisions_Slider_Mapping (RevisionID, EventID, " +
                                                            "PictureName) VALUES(" + revisionID + ",@eventID, @picName)", conn);
                                                        cmd.Parameters.Add("@eventID", SqlDbType.Int).Value = tempID;
                                                        cmd.Parameters.Add("@picName", SqlDbType.NVarChar).Value = PictureCheckList.Items[i].Value;
                                                        cmd.ExecuteNonQuery();
                                                    }
                                                }
                                                mediaChanged = true;

                                                if (i == 0)
                                                    dat.Execute("DELETE FROM Event_Slider_Mapping WHERE EventID=" + eventID.Text);

                                                dat.Execute("UPDATE Events SET mediaCategory=" + mediaCat + " WHERE ID=" + tempID);

                                                cmd = new SqlCommand("INSERT INTO Event_Slider_Mapping (EventID, PictureName, RealPictureName) " +
                                                    "VALUES(@eventID, @picName, @realName)", conn);
                                                cmd.Parameters.Add("@eventID", SqlDbType.Int).Value = tempID;
                                                cmd.Parameters.Add("@picName", SqlDbType.NVarChar).Value = PictureCheckList.Items[i].Value;
                                                cmd.Parameters.Add("@realName", SqlDbType.NVarChar).Value = PictureCheckList.Items[i].Text;
                                                cmd.ExecuteNonQuery();

                                            }
                                            else
                                            {
                                                cmd = new SqlCommand("INSERT INTO Event_Slider_Mapping (EventID, PictureName, RealPicturename) " +
                                                    "VALUES(@eventID, @picName, @realName)", conn);
                                                cmd.Parameters.Add("@eventID", SqlDbType.Int).Value = tempID;
                                                cmd.Parameters.Add("@picName", SqlDbType.NVarChar).Value = PictureCheckList.Items[i].Value;
                                                cmd.Parameters.Add("@realName", SqlDbType.NVarChar).Value = PictureCheckList.Items[i].Text;
                                                cmd.ExecuteNonQuery();
                                            }

                                        }
                                        //WE NO LONGER ALLOW Videos to be uploaded to the site itself. Only YouTube videos allowed.
                                        //else if (tokens[1].ToUpper() == "WMV")
                                        //{
                                        //    if (!System.IO.File.Exists(MapPath(".") + "\\UserFiles\\Events\\" + tempID + "\\Slider\\" + PictureCheckList.Items[i].Value))
                                        //    {
                                        //        System.IO.File.Copy(MapPath(".") + "\\UserFiles\\" + Session["UserName"].ToString() +
                                        //             "\\Slider\\" + PictureCheckList.Items[i].Value,
                                        //             MapPath(".") + "\\UserFiles\\Events\\" + tempID + "\\Slider\\" + PictureCheckList.Items[i].Value);
                                        //    }
                                        //    if (isEditing)
                                        //    {
                                        //        if (PictureCheckList.Items[i].Enabled)
                                        //        {
                                        //            cmd = new SqlCommand("INSERT INTO EventRevisions_Slider_Mapping (modifierID, EventID, PictureName) VALUES("+Session["User"].ToString()+",@eventID, @picName)", conn);
                                        //            cmd.Parameters.Add("@eventID", SqlDbType.Int).Value = tempID;
                                        //            cmd.Parameters.Add("@picName", SqlDbType.NVarChar).Value = PictureCheckList.Items[i].Value;
                                        //            cmd.ExecuteNonQuery();

                                        //            mediaChanged = true;

                                        //            cmd = new SqlCommand("INSERT INTO Event_Slider_Mapping (EventID, PictureName) VALUES(@eventID, @picName)", conn);
                                        //            cmd.Parameters.Add("@eventID", SqlDbType.Int).Value = tempID;
                                        //            cmd.Parameters.Add("@picName", SqlDbType.NVarChar).Value = PictureCheckList.Items[i].Value;
                                        //            cmd.ExecuteNonQuery();
                                        //        }
                                        //    }
                                        //    else
                                        //    {
                                        //        cmd = new SqlCommand("INSERT INTO Event_Slider_Mapping (EventID, PictureName) VALUES(@eventID, @picName)", conn);
                                        //        cmd.Parameters.Add("@eventID", SqlDbType.Int).Value = tempID;
                                        //        cmd.Parameters.Add("@picName", SqlDbType.NVarChar).Value = PictureCheckList.Items[i].Value;
                                        //        cmd.ExecuteNonQuery();
                                        //    }

                                        //}
                                    }
                                    else
                                    {
                                        mediaChanged = true;
                                        YouTubeStr += PictureCheckList.Items[i].Value + ";";
                                    }
                                }
                            }

                            if (YouTubeStr != "")
                                if (isEditing)
                                {
                                    if (dsEvent.Tables[0].Rows[0]["YouTubeVideo"].ToString() != YouTubeStr && !isOwner && !ownerUpForGrabs)
                                    {
                                        dat.Execute("INSERT INTO EventRevisions_YouTube (EventID, YouTubeStr, RevisionID) " +
                                            "VALUES(" + ID + ", '" + YouTubeStr + "', " + revisionID + ")");
                                    }

                                    dat.Execute("UPDATE Events SET mediaCategory=" + mediaCat + ", YouTubeVideo='" + YouTubeStr + "' WHERE ID=" + tempID);
                                }
                                else
                                {
                                    dat.Execute("UPDATE Events SET mediaCategory=" + mediaCat + ", YouTubeVideo='" + YouTubeStr + "' WHERE ID=" + ID);
                                }

                        }

                        #endregion

                        #region Take Care of Event Occurance
                        DataSet dsEOccur = dat.GetData("SELECT * FROM Event_Occurance WHERE EventID=" + tempID);
                        DataView dvEOccur = new DataView(dsEOccur.Tables[0], "", "", DataViewRowState.CurrentRows);

                        //if (isEditing && (!isOwner || ownerUpForGrabs))
                        //{
                        //    dvEOccur.RowFilter = "DateTimeStart = '" + StartDateTimePicker.DbSelectedDate.ToString() + "' AND " +
                        //        "DateTimeEnd = '" + EndDateTimePicker.DbSelectedDate.ToString() + "'";

                        //    if (dvEOccur.Count == 0)
                        //    {
                        //        occuranceChanged = true;
                        //        hasEditChanged = true;
                        //        cmd = new SqlCommand("INSERT INTO EventRevisions_Occurance (EventID, DateTimeStart, DateTimeEnd, RevisionID, DATE) " +
                        //            "VALUES(@eventID, @dateStart, @dateEnd, " + temporaryID + ", '"+DateTime.Parse(cookie.Value.ToString().Replace("%20", " ").Replace("%3A", ":")).ToString()+"')", conn);
                        //        cmd.Parameters.Add("@eventID", SqlDbType.Int).Value = tempID;
                        //        cmd.Parameters.Add("@dateStart", SqlDbType.DateTime).Value = StartDateTimePicker.DbSelectedDate.ToString();
                        //        if (EndDateTimePicker.DbSelectedDate != null)
                        //            cmd.Parameters.Add("@dateEnd", SqlDbType.DateTime).Value = EndDateTimePicker.DbSelectedDate.ToString();
                        //        else
                        //            cmd.Parameters.Add("@dateEnd", SqlDbType.DateTime).Value = DBNull.Value;
                        //        cmd.ExecuteNonQuery();
                        //    }
                        //}
                        //else
                        //{
                        //    dat.Execute("DELETE FROM Event_Occurance WHERE EventID="+temporaryID);
                        //    cmd = new SqlCommand("INSERT INTO Event_Occurance (EventID, DateTimeStart, DateTimeEnd) VALUES(@eventID, @dateStart, @dateEnd)", conn);
                        //    cmd.Parameters.Add("@eventID", SqlDbType.Int).Value = tempID;
                        //    cmd.Parameters.Add("@dateStart", SqlDbType.DateTime).Value = StartDateTimePicker.DbSelectedDate.ToString();
                        //    if (EndDateTimePicker.DbSelectedDate != null)
                        //        cmd.Parameters.Add("@dateEnd", SqlDbType.DateTime).Value = EndDateTimePicker.DbSelectedDate.ToString();
                        //    else
                        //        cmd.Parameters.Add("@dateEnd", SqlDbType.DateTime).Value = DBNull.Value;
                        //    cmd.ExecuteNonQuery();
                        //}

                        //DateTime a = DateTime.Parse(EndDateTimePicker.DbSelectedDate.ToString());
                        //TimeSpan b = a.Subtract(DateTime.Parse(StartDateTimePicker.DbSelectedDate.ToString()));

                        string[] delimStr = { " -- " };

                        dat.Execute("DELETE FROM Event_Occurance WHERE EventID=" + tempID);

                        for (int i = 0; i < DateSelectionsListBox.Items.Count; i++)
                        {
                            if (isEditing)
                            {

                                string[] tokensStr = DateSelectionsListBox.Items[i].Text.Split(delimStr,
                                        StringSplitOptions.RemoveEmptyEntries);

                                //if (dvEOccur.Count == 0)
                                //{
                                occuranceChanged = true;
                                hasEditChanged = true;

                                if (!ownerUpForGrabs && !isOwner)
                                {

                                    cmd = new SqlCommand("INSERT INTO EventRevisions_Occurance (EventID, DateTimeStart, DateTimeEnd, RevisionID, DATE)" +
                                        "VALUES(@eventID, @dateStart, @dateEnd, " + temporaryID + ", '" + isn.ToString() + "')", conn);
                                    cmd.Parameters.Add("@eventID", SqlDbType.Int).Value = tempID;
                                    cmd.Parameters.Add("@dateStart", SqlDbType.DateTime).Value = tokensStr[0];
                                    cmd.Parameters.Add("@dateEnd", SqlDbType.DateTime).Value = tokensStr[1];
                                    cmd.ExecuteNonQuery();
                                }
                                else
                                {
                                    cmd = new SqlCommand("INSERT INTO Event_Occurance (EventID, DateTimeStart, DateTimeEnd) VALUES(@eventID, @dateStart, @dateEnd)", conn);
                                    cmd.Parameters.Add("@eventID", SqlDbType.Int).Value = tempID;
                                    cmd.Parameters.Add("@dateStart", SqlDbType.DateTime).Value = tokensStr[0];
                                    cmd.Parameters.Add("@dateEnd", SqlDbType.DateTime).Value = tokensStr[1];
                                    cmd.ExecuteNonQuery();
                                }
                                //}
                            }
                            else
                            {
                                string[] tokensStr = DateSelectionsListBox.Items[i].Text.Split(delimStr, StringSplitOptions.RemoveEmptyEntries);

                                cmd = new SqlCommand("INSERT INTO Event_Occurance (EventID, DateTimeStart, DateTimeEnd) VALUES(@eventID, @dateStart, @dateEnd)", conn);
                                cmd.Parameters.Add("@eventID", SqlDbType.Int).Value = tempID;
                                cmd.Parameters.Add("@dateStart", SqlDbType.DateTime).Value = tokensStr[0];
                                cmd.Parameters.Add("@dateEnd", SqlDbType.DateTime).Value = tokensStr[1];
                                cmd.ExecuteNonQuery();
                            }

                        }

                        #endregion

                        conn.Close();

                        #region Take care of search terms
                        if (FeaturePanel.Visible)
                        {
                            string terms = "";
                            foreach (ListItem item in SearchTermsListBox.Items)
                            {
                                terms += ";" + item.Text + ";";
                            }
                            foreach (ListItem item in FeatureDatesListBox.Items)
                            {
                                if (item.Value != "Disabled")
                                    dat.Execute("INSERT INTO EventSearchTerms (EventID, SearchTerms, SearchDate) VALUES(" + ID +
                                        ", '" + terms.Replace("'", "''") + "', '" + item.Text + "')");
                            }
                        }
                        #endregion

                        try
                        {
                            if (chargeCard)
                            {
                                Encryption encrypt = new Encryption();

                                //Charge Card though Capture
                                country = dat.GetDataDV("SELECT country_2_code FROM Countries WHERE country_id=" + BillingCountry.SelectedValue)[0]["country_2_code"].ToString();
                                com.paypal.sdk.util.NVPCodec status = d.DoCaptureCode(transactionID, price.ToString(),
                                    "E" + temporaryID + isn.ToString(), "Capture Transaction for Featuring Event '" +
                                    dat.MakeNiceNameFull(EventNameTextBox.Text) + "'");
                                //message = status.ToString();
                                string successORFailure = status["ACK"];
                                switch (successORFailure.ToLower())
                                {
                                    case "failure":
                                        MessagePanel.Visible = true;
                                        YourMessagesLabel.Text = status["L_LONGMESSAGE0"];
                                        //MessagePanel.Visible = true;
                                        //foreach (string key in status.Keys)
                                        //{
                                        //    YourMessagesLabel.Text += "key: '" + key + "', value: '" + status[key] + "' <br/>";
                                        //}
                                        break;
                                    case "success":
                                        //MessagePanel.Visible = true;
                                        //foreach (string key in status.Keys)
                                        //{
                                        //    YourMessagesLabel.Text += "key: '" + key + "', value: '" + status[key] + "' <br/>";
                                        //}
                                        TakeCareOfPostEmail(isEditing, isOwner, isNewVenue, ownerUpForGrabs,
                                        temporaryID, venueID.ToString(), tempID, revisionID, ownerID);
                                        break;
                                    default:
                                        MessagePanel.Visible = true;
                                        foreach (string key in status.Keys)
                                        {
                                            YourMessagesLabel.Text += "key: '" + key + "', value: '" + status[key] + "' <br/>";
                                        }
                                        break;
                                }
                            }
                            else
                            {
                                //MessagePanel.Visible = true;
                                //YourMessagesLabel.Text = "no charge here";
                                TakeCareOfPostEmail(isEditing, isOwner, isNewVenue, ownerUpForGrabs,
                                    temporaryID, venueID.ToString(), tempID, revisionID, ownerID);
                            }
                        }
                        catch (Exception ex)
                        {
                            MessagePanel.Visible = true;
                            YourMessagesLabel.Text = "problem: " + problem + ex.ToString();
                        }

                    }
                    else
                    {
                        MessagePanel.Visible = true;
                        YourMessagesLabel.Text = "" + message;
                    }
                }
                else
                {
                    MessagePanel.Visible = true;
                    YourMessagesLabel.Text = "You must agree to the terms and conditions.";
                }
            }
        }
        catch (Exception ex)
        {
            MessagePanel.Visible = true;
            YourMessagesLabel.Text = "problem: " + problem + ex.ToString() + ", command: ";
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        HttpCookie cookie = Request.Cookies["BrowserDate"];
        if (cookie == null)
        {
            cookie = new HttpCookie("BrowserDate");
            cookie.Value = DateTime.Now.ToString();
            cookie.Expires = DateTime.Now.AddDays(22);
            Response.Cookies.Add(cookie);
        }
        DateTime today = DateTime.Parse(cookie.Value.ToString().Replace("%20", " ").Replace("%3A", ":"));
        Data dat = new Data(today);
        DataSet ds;
        if (Request.QueryString["ID"] != null)
        {
            string catID = Request.QueryString["ID"].ToString();

            string location = "";

            //Get the location
            if (Session["User"] != null)
            {
                DataView dvPrefs = dat.GetDataDV("SELECT * FROM UserPreferences WHERE UserID=" + Session["User"].ToString());
                location = " AND V.State='" + dvPrefs[0]["CatState"].ToString() + "' AND V.City='" + dvPrefs[0]["CatCity"].ToString() + "'";
            }
            else
            {
                DataView dvIP = dat.GetDataDV("SELECT * FROM Users U, UserPreferences UP WHERE UP.UserID=U.User_ID AND U.IPs LIKE '%;" + dat.GetIP() + ";%'");

                //If one or multiple found, look up ads on city and state of the first record
                if (dvIP.Count > 0)
                {
                    location = " AND V.State='" + dvIP[0]["CatState"].ToString() +
                        "' AND V.City='" + dvIP[0]["CatCity"].ToString() + "'";
                }
                //If not found look in searches table, get the city and state
                else
                {
                    DataView dvSearch = dat.GetDataDV("SELECT * FROM SearchIPs WHERE IP='" + dat.GetIP() + "'");
                    location = " AND V.State='" + dvSearch[0]["State"].ToString() +
                        "' AND V.City='" + dvSearch[0]["City"].ToString() + "'";
                }
            }

            //get only events after today, since showing all events might be too much
            string timeline = " AND EO.DateTimeStart >= CONVERT(DATETIME, '" + today.Month.ToString() + "/" + today.Day.ToString() + "/" + today.Year.ToString() + "')";

            string command = "SELECT E.ID AS EID, EO.ID AS ReoccurrID, EO.DateTimeStart, 'False' AS isGroup, CONVERT(NVARCHAR, E.ID)+'E' AS HashID, C.Name AS CategoryName, V.ID AS VID, * " +
                "FROM Event_Occurance EO, Event_Category_Mapping ECM, Events E, Venues V, EventCategories C " +
                "WHERE EO.EventID=E.ID AND C.ID=ECM.CategoryID AND E.Venue=V.ID AND ECM.EventID=E.ID AND " +
                "ECM.CategoryID=" + catID + location + timeline;

            ds = dat.GetData(command);
            SearchElements.EVENTS_DS = ds;
            SearchElements.DataBind2();

            NumResultsLabel.Text = "(" + ds.Tables[0].Rows.Count + " Records Found)";

            DataView dvName = dat.GetDataDV("SELECT * FROM EventCategories WHERE ID=" + catID);

            HtmlHead head = (HtmlHead)Page.Header;

            string theLink = "http://" + Request.Url.Authority + "/" +
               dvName[0]["Name"].ToString() + "_Event_Category";

            HtmlLink lk = new HtmlLink();
            lk.Href = theLink;
            lk.Attributes.Add("rel", "bookmark");
            head.Controls.AddAt(0, lk);

            HtmlMeta hm = new HtmlMeta();
            HtmlMeta kw = new HtmlMeta();
            HtmlMeta dc = new HtmlMeta();

            kw.Name = "keywords";
            kw.Content = dvName[0]["Name"].ToString() + " event Category";

            head.Controls.AddAt(0, kw);

            dc.Name = "description";
            dc.Content = "Results for event category: " + dvName[0]["Name"].ToString();

            head.Controls.AddAt(0, dc);

            SearchResultsTitleLabel.Text = "<a href=\"" + theLink +
                "\" style=\"text-decoration: none; color: white;\" >Events in '" +
                dvName[0]["Name"].ToString() + "' Category</a>";

        }else
        {
            Response.Redirect("Home.aspx");
        }
    }
Example #11
0
    protected void Page_Load(object sender, EventArgs e)
    {
        //Page.Trace.IsEnabled = true;
        //Page.Trace.TraceMode = TraceMode.SortByTime;
        HttpCookie cookie = Request.Cookies["BrowserDate"];
        if (cookie == null)
        {
            cookie = new HttpCookie("BrowserDate");
            cookie.Value = DateTime.Now.Date.ToString();
            cookie.Expires = DateTime.Now.AddDays(22);
            Response.Cookies.Add(cookie);
        }
        bool fillUserData = false;
        Data dat = new Data(DateTime.Parse(cookie.Value.ToString().Replace("%20", " ").Replace("%3A", ":").Replace("%28", "(").Replace("%29", ")")));

        if (!IsPostBack)
        {
            try
            {
                HtmlMeta hm = new HtmlMeta();
                HtmlMeta kw = new HtmlMeta();

                HtmlHead head = (HtmlHead)Page.Header;

                hm.Name = "Description";
                hm.Content = "Find your local events, venues and classifieds all while " +
                         "ads from your peers, neighborhood, and community are displayed "+
                         "to you purely based on your interests." +
                         "Large corporations are not welcome!";
                head.Controls.AddAt(0, hm);

                HtmlMeta nMT = new HtmlMeta();
                nMT.Name = "google-site-verification";
                nMT.Content = "tw8rmOWW-DlZa-H4DZdGr201J5kC7NVLXUmk5oN8vFM";

                head.Controls.Add(nMT);

                HtmlLink lkl = new HtmlLink();
                lkl.Href = "ror.xml";
                lkl.Attributes.Add("rel", "alternate");
                lkl.Attributes.Add("type", "application/xml");
                lkl.Attributes.Add("title", "ROR");

                head.Controls.Add(lkl);

                kw.Name = "keywords";
                kw.Content = "events, ads, venues, post, search, find, local events, concerts, festivals, world, theatre, technology, " +
                    "family, peers, neighborhood, classifieds";

                //DataView dvCats = dat.GetDataDV("SELECT * FROM AdCategories");

                //for (int i = 0; i < dvCats.Count; i++)
                //{
                //    kw.Content += ", " + dvCats[i]["Name"].ToString();
                //}

                //dvCats = dat.GetDataDV("SELECT * FROM EventCategories");

                //for (int i = 0; i < dvCats.Count; i++)
                //{
                //    kw.Content += ", " + dvCats[i]["Name"].ToString();
                //}

                //dvCats = dat.GetDataDV("SELECT * FROM VenueCategories");

                //for (int i = 0; i < dvCats.Count; i++)
                //{
                //    kw.Content += ", " + dvCats[i]["Name"].ToString();
                //}

                head.Controls.AddAt(0, kw);

                //logInPanel.Visible = Session["User"] == null;
                //loggedInPanel.Visible = Session["User"] != null;

                //Fill the home mission
                //if (!IsPostBack)
                //{
                //    ChangeMission(MissionTimer, new EventArgs());
                //}

                string country = "";
                string state = "";
                string city = "";
                string countryID = "";
                string stateID = "";
                string cityID = "";
                try
                {
                    if (Session["User"] != null)
                    {
                        DataSet ds1 = dat.GetData("SELECT * FROM Users U, UserPreferences UP WHERE U.User_ID=" +
                            Session["User"].ToString() + " AND U.User_ID=UP.UserID ");

                        country = ds1.Tables[0].Rows[0]["CatCountry"].ToString();
                        countryID = country;

                        state = ds1.Tables[0].Rows[0]["CatState"].ToString();
                        city = ds1.Tables[0].Rows[0]["CatCity"].ToString();
                        stateID = state;
                        cityID = city;

                        //DataSet ds2 = dat.RetrieveAds(Session["User"].ToString(), false);
                        //DataSet dsMain = dat.RetrieveMainAds(Session["User"].ToString());
                        //Ads1.DATA_SET = ds2;
                        //Ads1.MAIN_AD_DATA_SET = dsMain;

                        fillUserData = true;
                    }
                    else
                    {
                        DataSet ds1 = dat.GetData("SELECT * FROM Users U, UserPreferences UP WHERE " +
                                " U.User_ID=UP.UserID AND U.IPs LIKE '%" + dat.GetIP() + "%'");

                        bool getAnotherDs1 = false;
                        if (ds1.Tables.Count > 0)
                            if (ds1.Tables[0].Rows.Count > 0)
                            {
                                country = ds1.Tables[0].Rows[0]["CatCountry"].ToString();
                                countryID = country;
                                state = ds1.Tables[0].Rows[0]["CatState"].ToString();
                                city = ds1.Tables[0].Rows[0]["CatCity"].ToString();
                                stateID = state;
                                cityID = city;
                            }
                            else
                            {
                                getAnotherDs1 = true;
                            }
                        else
                        {
                            getAnotherDs1 = true;
                        }

                        if (getAnotherDs1)
                        {
                            ds1 = dat.GetData("SELECT * FROM SearchIPs WHERE IP='" + dat.GetIP() + "'");

                            if (ds1.Tables.Count > 0)
                            {
                                if (ds1.Tables[0].Rows.Count > 0)
                                {
                                    country = ds1.Tables[0].Rows[0]["Country"].ToString();
                                    countryID = country;
                                    state = ds1.Tables[0].Rows[0]["State"].ToString();
                                    city = ds1.Tables[0].Rows[0]["City"].ToString();
                                    stateID = state;
                                    cityID = city;
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {

                }

                #region Take care of group activity

                if (country != "" && state != "")
                {
                    //Get Latest Group activity from Public groups
                    //GroupEvents
                    //    -posted on
                    //    -last edited

                    string thePlace = " AND G.Country=" + country + " AND G.State='" + state + "' ";
                    if (city != "")
                        thePlace += " AND G.City = '" + city.Replace("'", "''") + "'";

                    DataView dvTopGroupActivity = GetTheActivity(thePlace);

                    //Find the top 5 most recent
                    if (dvTopGroupActivity.Count > 0)
                    {
                        dvTopGroupActivity.Sort = "TheDate DESC";
                    }
                    int countIndex = 5;
                    if (dvTopGroupActivity.Count < 5)
                        countIndex = dvTopGroupActivity.Count;

                    string theType = "";
                    Literal theLit = new Literal();
                    GroupsPanel.Controls.Clear();
                    string userID = "";
                    string content = "";
                    DataView dvUser = new DataView();
                    DataView dv = new DataView();
                    DataView dvGroup = new DataView();
                    DataView dvG = new DataView();
                    if (dvTopGroupActivity.Count > 0)
                    {
                        for (int i = 0; i < countIndex; i++)
                        {
                            theType = dvTopGroupActivity[i]["Type"].ToString();
                            //<div style=\"width: 388px;background-repeat: repeat-y; background-image: url(images/ActCommentMiddle.png);\" class=\"topDiv\">
                            theLit.Text += "<div " +
                                "class=\"topDiv\" style=\"width: 378px;height: 143px;padding-left: 10px;padding-top: 10px; background-image: "+
                                "url(images/ActCommentTopPurple10.png); background-repeat: no-repeat; \"><div style=\"float: left;\"><img src=\"images/QuoteTop.png\" /></div><div style=\"float: left; width: 350px; padding-bottom: 5px;\">";

                            DateTime theDate = DateTime.Parse(dvTopGroupActivity[i]["TheDate"].ToString());
                            string postedText = "<div style=\"clear: both;\"><div style=\"float: left;\"><span " +
                                "style=\"font-size: 12px; font-style: italic; font-family: arial; color: #a5c13a;\">Posted " +
                                dat.GetMonth(theDate.Month.ToString()) + " " +
                                        theDate.Day.ToString() + ", " + theDate.Year.ToString() + "</span><br/>";
                            switch (theType)
                            {
                                case "GEP":
                                    dv = dat.GetDataDV("SELECT *, GEO.ID AS GEOID FROM GroupEvents GE, " +
                                        "GroupEvent_Occurance GEO WHERE GE.ID=GEO.GroupEventID AND GE.ID=" +
                                        dvTopGroupActivity[i]["TheID"].ToString());
                                    userID = dv[0]["UserID"].ToString();
                                    dvGroup = dat.GetDataDV("SELECT * FROM Groups WHERE ID=" + dv[0]["GroupID"].ToString());
                                    dvUser = dat.GetDataDV("SELECT * FROM UserPreferences UP, Users U " +
                                        "WHERE UP.UserID=U.User_ID AND UP.UserID=" + userID);

                                    theLit.Text += "<div style=\"float: left; padding-right: 10px; padding-left: " +
                                        "10px; padding-bottom: 5px; padding-top: 5px;\">" + getUserProfile(userID) + "</div>";

                                    content = dat.stripHTML(dv[0]["Content"].ToString());
                                    if (content.Length > 170)
                                        content = content.Substring(0, 170) + "...";

                                    theLit.Text += "<div style=\"padding-top: 5px;font-family: Arial; font-size: 12px; color: " +
                                        "#cccccc; font-style: italic;\">" + content + "&nbsp<a style=\"text-decoration: none;\" href=\"" +
                                        dat.MakeNiceName(dv[0]["Name"].ToString()) + "_" +
                                        dv[0]["GEOID"].ToString() + "_" + dvTopGroupActivity[i]["TheID"].ToString() +
                                        "_GroupEvent\"><span class=\"AddPurpleLink\">Read More</span></a></div>";
                                    theLit.Text += postedText;
                                    theLit.Text += "<span style=\"font-size: 12px; font-family: arial; color: #cccccc;\">posted by <a href=\"" + dvUser[0]["UserName"].ToString() +
                                        "_Friend\" class=\"AddLink\">" + dvUser[0]["UserName"].ToString() +
                                        "</a></span> <br/>";
                                    theLit.Text += "<a href=\"" + dat.MakeNiceName(dvGroup[0]["Header"].ToString()) +
                                        "_" + dvGroup[0]["ID"].ToString() + "_Group\" class=\"AddPurpleLink\">" +
                                        dvGroup[0]["Header"].ToString() + " Group</a></div><div style=\"float: right;\"><img src=\"images/QuoteBottom.png\" /></div></div>";
                                    break;
                                case "GEE":
                                    dv = dat.GetDataDV("SELECT *, GEO.ID AS GEOID FROM GroupEvents GE, " +
                                        "GroupEvent_Occurance GEO WHERE GE.ID=GEO.GroupEventID AND GE.ID=" +
                                        dvTopGroupActivity[i]["TheID"].ToString());
                                    userID = dv[0]["UserID"].ToString();
                                    dvGroup = dat.GetDataDV("SELECT * FROM Groups WHERE ID=" + dv[0]["GroupID"].ToString());
                                    dvUser = dat.GetDataDV("SELECT * FROM UserPreferences UP, Users U " +
                                        "WHERE UP.UserID=U.User_ID AND UP.UserID=" + userID);

                                    theLit.Text += "<div style=\"float: left; padding-right: 10px; padding-left: " +
                                        "10px; padding-bottom: 5px; padding-top: 5px;\">" + getUserProfile(userID) + "</div>";

                                    content = dat.stripHTML(dv[0]["Content"].ToString());
                                    if (content.Length > 170)
                                        content = content.Substring(0, 170) + "...";

                                    theLit.Text += "<div style=\"padding-top: 5px;font-family: Arial; font-size: 12px; color: " +
                                        "#cccccc; font-style: italic;\">" + content + "&nbsp<a style=\"text-decoration: none;\" href=\"" +
                                        dat.MakeNiceName(dv[0]["Name"].ToString()) + "_" +
                                        dv[0]["GEOID"].ToString() + "_" + dvTopGroupActivity[i]["TheID"].ToString() +
                                        "_GroupEvent\"><span class=\"AddPurpleLink\">Read More</span></a></div>";
                                    theLit.Text += postedText;
                                    theLit.Text += "<span style=\"font-size: 12px; font-family: arial; color: #cccccc;\">edited by <a href=\"" + dvUser[0]["UserName"].ToString() +
                                        "_Friend\" class=\"AddLink\">" + dvUser[0]["UserName"].ToString() +
                                        "</a></span> <br/>";
                                    theLit.Text += "<a href=\"" + dat.MakeNiceName(dvGroup[0]["Header"].ToString()) +
                                        "_" + dvGroup[0]["ID"].ToString() + "_Group\" class=\"AddPurpleLink\">" +
                                        dvGroup[0]["Header"].ToString() + " Group</a></div><div style=\"float: right;\"><img src=\"images/QuoteBottom.png\" /></div></div>";
                                    break;
                                case "GEM":
                                    dv = dat.GetDataDV("SELECT *, GEM.UserID AS TheUser, GEO.ID AS GEOID, GE.ID AS EID, GEM.Content AS TheContent FROM GroupEvents GE, " +
                                        "GroupEvent_Occurance GEO, GroupEventMessages GEM WHERE GEM.GroupEventID=GE.ID AND " +
                                        "GE.ID=GEO.GroupEventID AND GEM.ID=" + dvTopGroupActivity[i]["TheID"].ToString());
                                    userID = dv[0]["TheUser"].ToString();
                                    dvGroup = dat.GetDataDV("SELECT * FROM Groups WHERE ID=" + dv[0]["GroupID"].ToString());
                                    dvUser = dat.GetDataDV("SELECT * FROM UserPreferences UP, Users U " +
                                        "WHERE UP.UserID=U.User_ID AND UP.UserID=" + userID);

                                    theLit.Text += "<div style=\"float: left; padding-right: 10px; padding-left: " +
                                        "10px; padding-bottom: 5px; padding-top: 5px;\">" + getUserProfile(userID) + "</div>";

                                    content = dat.stripHTML(dv[0]["TheContent"].ToString());
                                    if (content.Length > 170)
                                        content = content.Substring(0, 170) + "...";

                                    theLit.Text += "<div style=\"padding-top: 5px;font-family: Arial; font-size: 12px; color: " +
                                        "#cccccc; font-style: italic;\">" + content + "&nbsp<a style=\"text-decoration: none;\" href=\"" +
                                        dat.MakeNiceName(dv[0]["Name"].ToString()) + "_" +
                                        dv[0]["GEOID"].ToString() + "_" + dv[0]["EID"].ToString() +
                                        "_GroupEvent\"><span class=\"AddPurpleLink\">Read More</span></a></div>";
                                    theLit.Text += postedText;
                                    theLit.Text += "<span style=\"font-size: 12px; font-family: arial; color: #cccccc;\">posted by <a href=\"" + dvUser[0]["UserName"].ToString() +
                                        "_Friend\" class=\"AddLink\">" + dvUser[0]["UserName"].ToString() +
                                        "</a></span> <br/>";
                                    theLit.Text += "<a href=\"" + dat.MakeNiceName(dvGroup[0]["Header"].ToString()) +
                                        "_" + dvGroup[0]["ID"].ToString() + "_Group\" class=\"AddPurpleLink\">" +
                                        dvGroup[0]["Header"].ToString() + " Group</a></div><div style=\"float: right;\"><img src=\"images/QuoteBottom.png\" /></div></div>";
                                    break;
                                case "GP":
                                    dvG = dat.GetDataDV("SELECT *  FROM Groups G WHERE ID=" +
                                        dvTopGroupActivity[i]["TheID"].ToString());
                                    userID = dvG[0]["Host"].ToString();
                                    dvUser = dat.GetDataDV("SELECT * FROM UserPreferences UP, Users U " +
                                        "WHERE UP.UserID=U.User_ID AND UP.UserID=" + userID);

                                    theLit.Text += "<div style=\"float: left; padding-right: 10px; padding-left: " +
                                        "10px; padding-bottom: 5px; padding-top: 5px;\">" + getUserProfile(userID) + "</div>";

                                    content = dat.stripHTML(dvG[0]["Content"].ToString());
                                    if (content.Length > 170)
                                        content = content.Substring(0, 170) + "...";

                                    theLit.Text += "<div style=\"padding-top: 5px;font-family: Arial; font-size: 12px; color: " +
                                        "#cccccc; font-style: italic;\">" + content + "&nbsp;<a style=\"text-decoration: none;\" href=\"" +
                                        dat.MakeNiceName(dvG[0]["Header"].ToString()) + "_" +
                                        dvTopGroupActivity[i]["TheID"].ToString() +
                                        "_Group\"><span class=\"AddPurpleLink\">Read More</span></a></div>";
                                    theLit.Text += postedText;
                                    theLit.Text += "<span style=\"font-size: 12px; font-family: arial; color: #cccccc;\">posted by <a href=\"" + dvUser[0]["UserName"].ToString() +
                                        "_Friend\" class=\"AddLink\">" + dvUser[0]["UserName"].ToString() +
                                        "</a></span> <br/>";
                                    theLit.Text += "<a href=\"" + dat.MakeNiceName(dvG[0]["Header"].ToString()) +
                                        "_" + dvG[0]["ID"].ToString() + "_Group\" class=\"AddPurpleLink\">" +
                                        dvG[0]["Header"].ToString() + " Group </a></div><div style=\"float: right;\"><img src=\"images/QuoteBottom.png\" /></div></div>";
                                    break;
                                case "GE":

                                    dvG = dat.GetDataDV("SELECT *  FROM Groups G WHERE ID=" +
                                        dvTopGroupActivity[i]["TheID"].ToString());
                                    userID = dvG[0]["Host"].ToString();
                                    dvUser = dat.GetDataDV("SELECT * FROM UserPreferences UP, Users U " +
                                        "WHERE UP.UserID=U.User_ID AND UP.UserID=" + userID);

                                    theLit.Text += "<div style=\"float: left; padding-right: 10px; padding-left: " +
                                        "10px; padding-bottom: 5px; padding-top: 5px;\">" + getUserProfile(userID) + "</div>";

                                    content = dat.stripHTML(dvG[0]["Content"].ToString());
                                    if (content.Length > 170)
                                        content = content.Substring(0, 170) + "...";

                                    theLit.Text += "<div style=\"padding-top: 5px;font-family: Arial; font-size: 12px; color: " +
                                        "#cccccc; font-style: italic;\">" + content + "&nbsp;<a style=\"text-decoration: none;\" href=\"" +
                                        dat.MakeNiceName(dvG[0]["Header"].ToString()) + "_" +
                                        dvTopGroupActivity[i]["TheID"].ToString() +
                                        "_Group\"><span class=\"AddPurpleLink\">Read More</span></a></div>";
                                    theLit.Text += postedText;
                                    theLit.Text += "<span style=\"font-size: 12px; font-family: arial; color: #cccccc;\">edited by <a href=\"" + dvUser[0]["UserName"].ToString() +
                                        "_Friend\" class=\"AddLink\">" + dvUser[0]["UserName"].ToString() +
                                        "</a></span> <br/>";
                                    theLit.Text += "<a href=\"" + dat.MakeNiceName(dvG[0]["Header"].ToString()) +
                                        "_" + dvG[0]["ID"].ToString() + "_Group\" class=\"AddPurpleLink\">" +
                                        dvG[0]["Header"].ToString() + " Group </a></div><div style=\"float: right;\"><img src=\"images/QuoteBottom.png\" /></div></div>";
                                    break;
                                case "GT":
                                    dvG = dat.GetDataDV("SELECT *, G.ID AS GID FROM Groups G, GroupThreads GT WHERE G.ID=GT.GroupID AND GT.ID=" +
                                        dvTopGroupActivity[i]["TheID"].ToString());
                                    userID = dvG[0]["StartedBy"].ToString();
                                    dvUser = dat.GetDataDV("SELECT * FROM UserPreferences UP, Users U " +
                                        "WHERE UP.UserID=U.User_ID AND UP.UserID=" + userID);

                                    theLit.Text += "<div style=\"float: left; padding-right: 10px; padding-left: " +
                                        "10px; padding-bottom: 5px; padding-top: 5px;\">" + getUserProfile(userID) + "</div>";

                                    content = dat.stripHTML("Thread added to the group: " + dvG[0]["ThreadName"].ToString());
                                    if (content.Length > 170)
                                        content = content.Substring(0, 170) + "...";

                                    theLit.Text += "<div style=\"padding-top: 5px;font-family: Arial; font-size: 12px; color: " +
                                        "#cccccc; font-style: italic;\">" + content + "&nbsp;<a style=\"text-decoration: none;\" href=\"" +
                                        dat.MakeNiceName(dvG[0]["Header"].ToString()) + "_" +
                                        dvG[0]["GID"].ToString() +
                                        "_Group\"><span class=\"AddPurpleLink\">Read More</span></a></div>";
                                    theLit.Text += postedText;
                                    theLit.Text += "<span style=\"font-size: 12px; font-family: arial; color: #cccccc;\">added by <a href=\"" + dvUser[0]["UserName"].ToString() +
                                        "_Friend\" class=\"AddLink\">" + dvUser[0]["UserName"].ToString() +
                                        "</a></span> <br/>";
                                    theLit.Text += "<a href=\"" + dat.MakeNiceName(dvG[0]["Header"].ToString()) +
                                        "_" + dvG[0]["GID"].ToString() + "_Group\" class=\"AddPurpleLink\">" +
                                        dvG[0]["Header"].ToString() + " Group </a></div><div style=\"float: right;\"><img src=\"images/QuoteBottom.png\" /></div></div>";
                                    break;
                                case "GTC":
                                    dvG = dat.GetDataDV("SELECT *, GTC.Content AS TheContent, G.ID AS GID FROM Groups G, " +
                                        "GroupThreads GT, GroupThreads_Comments GTC " +
                                        "WHERE GTC.ThreadID=GT.ID AND G.ID=GT.GroupID AND GTC.ID=" +
                                        dvTopGroupActivity[i]["TheID"].ToString());
                                    userID = dvG[0]["UserID"].ToString();
                                    dvUser = dat.GetDataDV("SELECT * FROM UserPreferences UP, Users U " +
                                        "WHERE UP.UserID=U.User_ID AND UP.UserID=" + userID);

                                    theLit.Text += "<div style=\"float: left; padding-right: 10px; padding-left: " +
                                        "10px; padding-bottom: 5px; padding-top: 5px;\">" + getUserProfile(userID) + "</div>";

                                    content = dat.stripHTML(dvG[0]["TheContent"].ToString());
                                    if (content.Length > 170)
                                        content = content.Substring(0, 170) + "...";

                                    theLit.Text += "<div style=\"padding-top: 5px;font-family: Arial; font-size: 12px; color: " +
                                        "#cccccc; font-style: italic;\">" + content + "&nbsp;<a style=\"text-decoration: none;\" href=\"" +
                                        dat.MakeNiceName(dvG[0]["Header"].ToString()) + "_" +
                                        dvG[0]["GID"].ToString() +
                                        "_Group\"><span class=\"AddPurpleLink\">Read More</span></a></div>";
                                    theLit.Text += postedText;
                                    theLit.Text += "<span style=\"font-size: 12px; font-family: arial; color: #cccccc;\">comment by <a href=\"" + dvUser[0]["UserName"].ToString() +
                                        "_Friend\" class=\"AddLink\">" + dvUser[0]["UserName"].ToString() +
                                        "</a></span> <br/>";
                                    theLit.Text += "<a href=\"" + dat.MakeNiceName(dvG[0]["Header"].ToString()) +
                                        "_" + dvG[0]["GID"].ToString() + "_Group\" class=\"AddPurpleLink\">" +
                                        dvG[0]["Header"].ToString() + " Group </a></div><div style=\"float: right;\"><img src=\"images/QuoteBottom.png\" /></div></div>";
                                    break;
                                case "GM":
                                    dvG = dat.GetDataDV("SELECT *, G.ID AS GID, GM.Content AS TheContent FROM GroupMessages GM, Groups G WHERE G.ID=GM.GroupID AND GM.ID=" +
                                        dvTopGroupActivity[i]["TheID"].ToString());
                                    userID = dvG[0]["UserID"].ToString();
                                    dvUser = dat.GetDataDV("SELECT * FROM UserPreferences UP, Users U " +
                                        "WHERE UP.UserID=U.User_ID AND UP.UserID=" + userID);

                                    theLit.Text += "<div style=\"float: left; padding-right: 10px; padding-left: " +
                                        "10px; padding-bottom: 5px; padding-top: 5px;\">" + getUserProfile(userID) + "</div>";

                                    content = dat.stripHTML(dvG[0]["TheContent"].ToString());
                                    if (content.Length > 170)
                                        content = content.Substring(0, 170) + "...";

                                    theLit.Text += "<div style=\"padding-top: 5px;font-family: Arial; font-size: 12px; color: " +
                                        "#cccccc; font-style: italic;\">" + content + "&nbsp;<a style=\"text-decoration: none;\" href=\"" +
                                        dat.MakeNiceName(dvG[0]["Header"].ToString()) + "_" +
                                        dvG[0]["GID"].ToString() +
                                        "_Group\"><span class=\"AddPurpleLink\">Read More</span></a></div>";
                                    theLit.Text += postedText;
                                    theLit.Text += "<span style=\"font-size: 12px; font-family: arial; color: #cccccc;\">message by <a href=\"" + dvUser[0]["UserName"].ToString() +
                                        "_Friend\" class=\"AddLink\">" + dvUser[0]["UserName"].ToString() +
                                        "</a></span> <br/>";
                                    theLit.Text += "<a href=\"" + dat.MakeNiceName(dvG[0]["Header"].ToString()) +
                                        "_" + dvG[0]["GID"].ToString() + "_Group\" class=\"AddPurpleLink\">" +
                                        dvG[0]["Header"].ToString() + " Group </a></div><div style=\"float: right;\"><img src=\"images/QuoteBottom.png\" /></div></div>";
                                    break;
                                default: break;
                            }

                            theLit.Text += "</div></div>";
                        }
                        GroupsPanel.Controls.Add(theLit);
                    }
                    else
                    {
                        Label lab = new Label();
                        lab.Text = "There are no groups in your area. To post some <a class=\"AddLink\" href=\"EnterGroup.aspx\">go here</a>";
                        GroupsLabel.Controls.Add(lab);
                    }
                }

                #endregion

                DataSet ds;

                if (!IsPostBack)
                {
                    LocationLabel.Text = "";
                    if (country != "")
                        country = " AND E.Country = " + country;

                    int c = 0;

                    if (state != "")
                    {

                        c++;
                    }

                    if (city != "")
                    {

                        c++;
                    }

                    SqlDbType[] types = new SqlDbType[c];
                    object[] data = new object[c];

                    if (state != "")
                    {
                        types[0] = SqlDbType.NVarChar;
                        data[0] = state;
                        state = " AND E.State=@p0 ";
                        if (city != "")
                        {
                            types[1] = SqlDbType.NVarChar;
                            data[1] = city;
                            city = " AND E.City=@p1 ";
                        }
                    }
                    else
                    {
                        if (city != "")
                        {
                            types[0] = SqlDbType.NVarChar;
                            data[0] = city;
                            city = " AND E.City=@p0 ";
                        }
                    }

                    ds = dat.GetDataWithParemeters("SELECT DISTINCT TOP 10 EO.DateTimeStart, E.Header, E.Content, EO.EventID FROM Events E, Event_Occurance EO WHERE E.LIVE='True' AND E.ID=EO.EventID " + country + state + city + " AND EO.DateTimeStart > '" + DateTime.Parse(cookie.Value.ToString().Replace("%20", " ").Replace("%3A", ":")).Date + "' ORDER BY EO.DateTimeStart", types, data);

                    Session["HomeEvents"] = ds;
                    LocationLabel.Text = "";
                    if (country == "" && state == "" && city == "")
                    {
                        LocationLabel.Text = " The World ";
                    }
                    else
                    {
                        if (city != "")
                        {
                            LocationLabel.Text += cityID;
                            if (state != "")
                                LocationLabel.Text += ", " + stateID;
                        }
                        else
                        {
                            if (state != "")
                                LocationLabel.Text += stateID;
                        }
                    }

                    if (LocationLabel.Text == "")
                    {
                        DataSet dsCountry = dat.GetData("SELECT * FROM Countries WHERE country_id=" + countryID);
                        LocationLabel.Text = dsCountry.Tables[0].Rows[0]["country_name"].ToString();
                    }
                }
                else
                {
                    EventPanel.Controls.Clear();
                    LocationLabel.Text = "";
                    ds = (DataSet)Session["HomeEvents"];

                    if (countryID == "" && stateID == "" && cityID == "")
                    {
                        LocationLabel.Text = " The World ";
                    }
                    else
                    {
                        if (cityID != "")
                        {
                            LocationLabel.Text += cityID;
                            if (state != "")
                                LocationLabel.Text += ", " + stateID;
                        }
                        else
                        {
                            if (state != "")
                                LocationLabel.Text += stateID;
                        }
                    }

                    //if (RadCalendar1.SelectedDate.ToShortDateString() != "1/1/0001")
                    //    LocationLabel.Text += " on " + RadCalendar1.SelectedDate.ToShortDateString();

                }

                ds = (DataSet)Session["HomeEvents"];

                if (ds != null)
                {

                    if (ds.Tables.Count > 0)
                        if (ds.Tables[0].Rows.Count > 0)
                        {
                            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                            {
                                DateTime date = DateTime.Parse(ds.Tables[0].Rows[i]["DateTimeStart"].ToString());
                                ASP.controls_homeevent_ascx eventH = new ASP.controls_homeevent_ascx();
                                eventH.DAY = date.DayOfWeek.ToString().Substring(0, 3);
                                eventH.DAY_NUMBER = date.Day.ToString();
                                eventH.MONTH = dat.GetMonth(date.Month.ToString()).Substring(0, 3);
                                eventH.EVENT_NAME = ds.Tables[0].Rows[i]["Header"].ToString();
                                if (ds.Tables[0].Rows[i]["Content"].ToString().Length > 150)
                                    eventH.SUMMARY = dat.BreakUpString(ds.Tables[0].Rows[i]["Content"].ToString().Substring(0, 150).Replace("<br/>", " "), 67) + "...";
                                else
                                    eventH.SUMMARY = dat.BreakUpString(ds.Tables[0].Rows[i]["Content"].ToString().Replace("<br/>", " "), 67) + "...";
                                eventH.EVENT_ID = int.Parse(ds.Tables[0].Rows[i]["EventID"].ToString());
                                EventPanel.Controls.Add(eventH);
                            }

                        }
                        else
                        {

                            Label label = new Label();
                            label.CssClass = "EventBody";
                            label.Text = "No events are listed for this date. Sorry. But perhaps you could enter one... <a class=\"AddLink\" href=\"BlogEvent.aspx\">Enter Events</a>.";
                            EventPanel.Controls.Add(label);
                        }
                    else
                    {

                        Label label = new Label();
                        label.CssClass = "EventBody";
                        label.Text = "No events are listed for this date. Sorry. But perhaps you could enter one... <a class=\"AddLink\" href=\"BlogEvent.aspx\">Enter Events</a>.";
                        EventPanel.Controls.Add(label);
                    }
                }
                else
                {

                    Label label = new Label();
                    label.CssClass = "EventBody";
                    label.Text = "No events are listed for this date. Sorry. But perhaps you could enter one... <a class=\"AddLink\" href=\"BlogEvent.aspx\">Enter Events</a>.";
                    EventPanel.Controls.Add(label);
                }

                #region Original Home page code
                //if (ds.Tables.Count > 0)
                //{
                //    if (ds.Tables[0].Rows.Count > 0)
                //    {

                //        ASP.controls_footer_ascx thefooter = (ASP.controls_footer_ascx)dat.FindControlRecursive(this, "TheFooter");
                //        thefooter.EVENT_ID = int.Parse(ds.Tables[0].Rows[0]["ID"].ToString());

                //        string ID = ds.Tables[0].Rows[0]["ID"].ToString();
                //        DataSet dsDate = dat.GetData("SELECT * FROM Event_Occurance WHERE EventID=" + ID);
                //        DataSet dsVenue = dat.GetData("SELECT * FROM Venues WHERE ID=" + ds.Tables[0].Rows[0]["Venue"]);
                //        TagCloud.THE_ID = int.Parse(ID);

                //        DataSet dsComments = dat.GetData("SELECT C.BlogDate AS theDate, * FROM Comments C, Users U WHERE U.User_ID=C.UserID AND C.BlogID=" + ID +" ORDER BY C.BlogDate");
                //        TheComments.DATA_SET = dsComments;
                //        TheComments.DataBind2(true);

                //        if (bool.Parse(ds.Tables[0].Rows[0]["hasSongs"].ToString()))
                //        {
                //            DataSet dsSongs = dat.GetData("SELECT * FROM Event_Song_Mapping WHERE EventID=" + ID);
                //            ASP.controls_songplayer_ascx songs = new ASP.controls_songplayer_ascx();
                //            int songCount = dsSongs.Tables[0].Rows.Count;

                //            if (songCount > 2)
                //            {
                //                songs.SONG1 = dsSongs.Tables[0].Rows[0]["SongName"].ToString();
                //                songs.SONG2 = dsSongs.Tables[0].Rows[1]["SongName"].ToString();
                //                songs.SONG3 = dsSongs.Tables[0].Rows[2]["SongName"].ToString();
                //            }
                //            else if (songCount > 1)
                //            {
                //                songs.SONG1 = dsSongs.Tables[0].Rows[0]["SongName"].ToString();
                //                songs.SONG2 = dsSongs.Tables[0].Rows[1]["SongName"].ToString();
                //            }
                //            else
                //                songs.SONG1 = dsSongs.Tables[0].Rows[0]["SongName"].ToString();

                //            songs.USER_NAME = ds.Tables[0].Rows[0]["UserName"].ToString();

                //            SongPanel.Controls.Add(songs);
                //        }

                //        EventName.Text = ds.Tables[0].Rows[0]["Header"].ToString();
                //        Session["Subject"] = "Re: "+ds.Tables[0].Rows[0]["Header"].ToString();
                //        Session["CommentSubject"] = "Re: " + ds.Tables[0].Rows[0]["Header"].ToString();
                //        EventName.NavigateUrl = "~/Event.aspx?EventID=" + ID;
                //        Session["EventID"] = ID;
                //        VenueName.Text = dsVenue.Tables[0].Rows[0]["Name"].ToString();
                //        VenueName.NavigateUrl = "Venue.aspx?ID="+dsVenue.Tables[0].Rows[0]["ID"].ToString();
                //        DateTime date = (DateTime)dsDate.Tables[0].Rows[0]["DateTimeStart"];
                //        DateAndTimeLabel.Text = date.DayOfWeek.ToString() + ", " + GetMonth(date.Month.ToString()) + " " + date.Day + " " + date.Hour + ":" + date.Minute;
                //        string content = ds.Tables[0].Rows[0]["Content"].ToString();
                //        SendTxtID.MESSAGE = EventName.Text + " occurs at " + VenueName.Text + " on " + DateAndTimeLabel.Text;

                //        string href = Request.Url.AbsoluteUri;
                //        SendEmailID.MESSAGE = "EventName: <a class=\"AddLink\" href=\"" + href +
                //            "\">" + EventName.Text + "</a> \n\r Venue: " + VenueName.Text +
                //            " \n\r Date: " + DateAndTimeLabel.Text + " \n\r " + content;

                //        //if (fillUserData)
                //        //{
                //        //    DataSet ds2 = dat.GetData("SELECT EEL.ExcitmentLevel AS Level FROM User_Calendar UC, Event_ExcitmentLevel EEL WHERE UC.UserID="
                //        //        + Session["User"].ToString() + " AND UC.EventID = " + ID + " AND UC.ExcitmentID=EEL.ID ");

                //        //    bool addEvent = false;

                //        //    if (ds2.Tables.Count > 0)
                //        //        if (ds2.Tables[0].Rows.Count > 0)
                //        //        {
                //        //            Label label = new Label();
                //        //            label.CssClass = "AddLinkGoing";
                //        //            label.Text = "Guess What?!: you're going to this event and you are " + ds2.Tables[0].Rows[0]["Level"].ToString();
                //        //            CalendarPanel.Controls.Add(label);
                //        //        }
                //        //        else
                //        //            addEvent = true;
                //        //    else
                //        //        addEvent = true;

                //        //    if (addEvent)
                //        //    {
                //        //        ASP.controls_addtocalendar_ascx AddTo1 = new ASP.controls_addtocalendar_ascx();
                //        //        AddTo1.ID = "AddTo1";
                //        //        AddTo1.TEXT = "Add this event to calendar";
                //        //        AddTo1.EVENT_ID = int.Parse(ID);
                //        //        CalendarPanel.Controls.Add(AddTo1);
                //        //    }

                //        //}

                //        if (content.Length > 500)
                //        {
                //            ShowDescriptionBegining.Text = content.Substring(0, 500);
                //            int j = 500;
                //            if (content[500] != ' ')
                //            {

                //                while (content[j] != ' ')
                //                {
                //                    ShowDescriptionBegining.Text += content[j];
                //                    j++;
                //                }
                //            }
                //            ShowDescriptionBegining.Text = dat.BreakUpString(ShowDescriptionBegining.Text, 65);
                //            ShowRestOfDescription.Text = dat.BreakUpString(content.Substring(j), 65);
                //        }
                //        else
                //        {
                //            ShowDescriptionBegining.Text = dat.BreakUpString(content, 65);
                //            ShowRestOfDescription.Text = "";
                //        }

                //        //Media Categories: NONE: 0, Picture: 1, Video: 2, YouTubeVideo: 3, Slider: 4
                //        int mediaCategory = int.Parse(ds.Tables[0].Rows[0]["mediaCategory"].ToString());

                //        switch (mediaCategory)
                //        {
                //            case 0:
                //                break;
                //            case 1:
                //                ShowVideoPictureLiteral.Text = "<img style=\"float: left; padding-right: 10px; padding-top: 9px;\" height=\"250px\" width=\"440px\" src=\"UserFiles/" + ds.Tables[0].Rows[0]["Picture"].ToString() + "\" />";
                //                break;
                //            case 2:
                //                ShowVideoPictureLiteral.Text = "<div style=\"float:left; padding-top: 9px; padding-right: 10px;\"><embed  height=\"250px\" width=\"440px\" src=\"UserFiles/" + ds.Tables[0].Rows[0]["Video"].ToString() + "\" /></div>";
                //                break;
                //            case 3:
                //                ShowVideoPictureLiteral.Text = "<div style=\"float:left; padding-top: 9px; padding-right: 10px;\"><object width=\"440\" height=\"250\"><param name=\"movie\" value=\"http://www.youtube.com/v/" + ds.Tables[0].Rows[0]["YouTubeVideo"].ToString() + "\"></param><param name=\"allowFullScreen\" value=\"true\"></param><embed src=\"http://www.youtube.com/v/" + ds.Tables[0].Rows[0]["YouTubeVideo"].ToString() + "\" type=\"application/x-shockwave-flash\" allowfullscreen=\"true\" width=\"440\" height=\"250\"></embed></object></div>";
                //                break;
                //            case 4:
                //                ShowVideoPictureLiteral.Text = "";
                //                DataSet dsSlider = dat.GetData("SELECT * FROM Event_Slider_Mapping WHERE EventID=" + ID);
                //                if (dsSlider.Tables.Count > 0)
                //                    if (dsSlider.Tables[0].Rows.Count > 0)
                //                    {
                //                        char[] delim = { '\\' };
                //                        string[] fileArray = System.IO.Directory.GetFiles(MapPath(".") + "\\UserFiles\\" + Session["UserName"].ToString() + "\\Slider\\");

                //                        string[] finalFileArray = new string[fileArray.Length];

                //                        for (int i = 0; i < fileArray.Length; i++)
                //                        {
                //                            int length = fileArray[i].Split(delim).Length;
                //                            finalFileArray[i] = "http://" + Request.Url.Authority + "/HippoHappenings/UserFiles/" + Session["UserName"].ToString() + "/Slider/" + fileArray[i].Split(delim)[length - 1];
                //                        }
                //                        Rotator1.DataSource = finalFileArray;
                //                        Rotator1.DataBind();
                //                        RotatorPanel.Visible = true;
                //                    }
                //                break;
                //            default: break;
                //        }

                //        this.Title = EventName.Text;
                //    }
                //}
                #endregion
            }
            catch (Exception ex)
            {
                ErrorLabel.Text = ex.ToString();
            }
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        //2/23/2010%2020%3A54%3A38
        HttpCookie cookie = Request.Cookies["BrowserDate"];
        if (cookie == null)
        {
            cookie = new HttpCookie("BrowserDate");
            cookie.Value = DateTime.Now.ToString();
            cookie.Expires = DateTime.Now.AddDays(22);
            Response.Cookies.Add(cookie);
        }
        Data dat = new Data(DateTime.Parse(cookie.Value.ToString().Replace("%20", " ").Replace("%3A", ":")));

        bool isPageNew = bool.Parse(ConfigurationSettings.AppSettings["isPageNew"].ToString());
        if (isPageNew)
            ConfigurationSettings.AppSettings["isPageNew"] = "false";

        if ((Session["User"] == null && Session["UserName"] != null) ||
            (Session["UserName"] == null && Session["User"] != null))
        {
            dat.Execute("DELETE FROM Events_Seen_By_User WHERE userID=" + Session["User"].ToString());
            string save1 = "";
            if (Session["AnonymousUser"] != null)
                save1 = Session["AnonymousUser"].ToString();

            string save2 = "";
            if (Session["BigAnonymousUser"] != null)
                save2 = Session["BigAnonymousUser"].ToString();

            Session.Remove("User");
            Session.Remove("UserName");
            FormsAuthentication.SignOut();

            if (save1 != "")
                Session["AnonymousUser"] = save1;

            if (save2 != "")
                Session["BigAnonymousUser"] = save2;

            Response.Redirect("UserLogin.aspx");
        }

        //if (!IsPostBack)
        //{
            try
            {
                HttpCookie cookieZone = Request.Cookies["TimeZone"];

                if (!IsPostBack)
                {
                    if (Session["User"] == null)
                    {
                        dat.Execute("INSERT INTO IP_User_Traffic (IP, PageName, DateAndTime) " +
                            "VALUES ('" + dat.GetIP() + "', '" + Request.Url.AbsolutePath.ToLower() +
                            "', GETDATE())");
                    }
                    else
                    {
                        dat.Execute("INSERT INTO IP_User_Traffic (IP, UserID, PageName, DateAndTime) " +
                            "VALUES ('" + dat.GetIP() + "', " + Session["User"].ToString() +
                            ",'" + Request.Url.AbsolutePath.ToLower() + "', GETDATE())");
                    }
                }

                if (Session["Searching"] != null)
                {
                    RadWindow3.Title = "Your " + Session["Searching"].ToString().Replace("s", "") + " Search Results";
                }

                if (Session["SearchDS"] != null)
                {
                    if (Session["Searching"].ToString() == "Events" &&
                        Request.Url.AbsolutePath.ToLower() == "/eventsearch.aspx" ||
                        Session["Searching"].ToString() == "Venues" &&
                        Request.Url.AbsolutePath.ToLower() == "/venuesearch.aspx")
                    {
                        RadWindow3.Width = 910;
                        RadWindow3.Height = 550;
                        RadWindow3.Top = 100;
                        RadWindow3.Left = 178;
                    }
                    else
                    {
                        RadWindow3.Top = 10;
                        RadWindow3.Left = 765;
                        RadWindow3.Width = 480;
                        RadWindow3.Height = 620;
                        RadWindow3.VisibleOnPageLoad = true;
                    }

                    RadWindow3.VisibleOnPageLoad = true;
                }
                else
                {
                    RadWindow3.VisibleOnPageLoad = false;
                }

            }
            catch (Exception ex)
            {

            }
        //}
    }
    protected void ImageGoTo(object sender, EventArgs e)
    {
        HttpCookie cookie = Request.Cookies["BrowserDate"];
        string arg = ((ImageButton)sender).CommandArgument.ToString();
        Data d = new Data(DateTime.Parse(cookie.Value.ToString().Replace("%20", " ").Replace("%3A", ":")));
        switch (arg)
        {
            case "A1":
                Response.Redirect("~/About.aspx");
                break;
            case "A2":
                Response.Redirect("~/Feedback.aspx");
                break;
            case "A3":
                Response.Redirect("~/Vote.aspx");
                break;
            case "G":
                SearchTextBox.Text = d.stripHTML(SearchTextBox.Text);
                if (SearchTextBox.Text != "")
                {
                    char[] delim = { ' ' };
                    string[] tokens;

                    tokens = SearchTextBox.Text.Split(delim);
                    string temp = "";
                    for (int i = 0; i < tokens.Length; i++)
                    {
                        temp += " E.Header LIKE @search" + i.ToString();

                        if (i + 1 != tokens.Length)
                            temp += " AND ";
                    }
                    string searchStr = "SELECT DISTINCT E.ID AS EID, V.ID AS VID, * FROM Events E, Venues V, Event_Occurance EO WHERE E.ID=EO.EventID AND E.Venue=V.ID AND "+temp;
                    SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ToString());
                    if (conn.State != ConnectionState.Open)
                        conn.Open();
                    SqlCommand cmd = new SqlCommand();

                    //Check if signed in, get address
                    string country = "";
                    string state = "";
                    string stateParam = "";
                    string city = "";
                    string cityParam = "";

                    DataSet dsAddress = new DataSet();
                    if (Session["User"] != null)
                    {
                        dsAddress = d.GetData("SELECT * FROM UserPreferences WHERE UserID=" +
                            Session["User"].ToString());

                        //Get search on address
                        if (dsAddress.Tables.Count > 0)
                            if (dsAddress.Tables[0].Rows.Count > 0)
                            {
                                country = " AND E.Country=" + dsAddress.Tables[0].Rows[0]["CatCountry"].ToString();

                                if (dsAddress.Tables[0].Rows[0]["CatState"].ToString() != "")
                                {
                                    state = " AND E.State=@state ";
                                    stateParam = dsAddress.Tables[0].Rows[0]["CatState"].ToString();

                                    if (dsAddress.Tables[0].Rows[0]["CatCity"].ToString() != "")
                                    {
                                        city = " AND E.City=@city ";
                                        cityParam = dsAddress.Tables[0].Rows[0]["CatCity"].ToString();
                                    }
                                }
                            }
                    }
                    else
                    {
                        //Check if IP in User table, get address
                        DataSet dsCheck = d.GetData("SELECT * FROM Users WHERE IPs LIKE '%" + d.GetIP() + "%'");

                        bool getSearchIP = false;
                        if (dsCheck.Tables.Count > 0)
                        {
                            if (dsCheck.Tables[0].Rows.Count > 0)
                            {
                                dsAddress = d.GetData("SELECT * FROM UserPreferences WHERE UserID=" +
                            dsCheck.Tables[0].Rows[0]["User_ID"].ToString());

                                //Get search on address
                                if (dsAddress.Tables.Count > 0)
                                    if (dsAddress.Tables[0].Rows.Count > 0)
                                    {
                                        country = " AND E.Country=" + dsAddress.Tables[0].Rows[0]["CatCountry"].ToString();

                                        if (dsAddress.Tables[0].Rows[0]["CatState"].ToString() != "")
                                        {
                                            state = " AND E.State=@state ";
                                            stateParam = dsAddress.Tables[0].Rows[0]["CatState"].ToString();

                                            if (dsAddress.Tables[0].Rows[0]["CatCity"].ToString() != "")
                                            {
                                                city = " AND E.City=@city ";
                                                cityParam = dsAddress.Tables[0].Rows[0]["CatCity"].ToString();
                                            }
                                        }
                                    }
                            }
                            else
                            {
                                getSearchIP = true;
                            }
                        }
                        else
                            getSearchIP = true;

                        if (getSearchIP)
                        {
                            //Get search on address
                            dsAddress = d.GetData("SELECT * FROM SearchIPs WHERE IP='" + d.GetIP()+"'");
                            if (dsAddress.Tables.Count > 0)
                                if (dsAddress.Tables[0].Rows.Count > 0)
                                {
                                    country = " AND E.Country=" + dsAddress.Tables[0].Rows[0]["Country"].ToString();

                                    if (dsAddress.Tables[0].Rows[0]["State"].ToString() != "")
                                    {
                                        state = " AND E.State=@state ";
                                        stateParam = dsAddress.Tables[0].Rows[0]["State"].ToString();

                                        if (dsAddress.Tables[0].Rows[0]["City"].ToString() != "")
                                        {
                                            city = " AND E.City=@city ";
                                            cityParam = dsAddress.Tables[0].Rows[0]["City"].ToString();
                                        }
                                    }
                                }
                        }
                    }

                    if (country != "")
                    {
                        searchStr += country;

                        if (state != "")
                        {
                            searchStr += state;
                            cmd.Parameters.Add("@state", SqlDbType.NVarChar).Value = stateParam;

                            if (city != "")
                            {
                                searchStr += city;
                                cmd.Parameters.Add("@city", SqlDbType.NVarChar).Value = city;
                            }
                        }

                    }

                    Session["searchstring"] = searchStr;

                    cmd.Connection = conn;
                    cmd.CommandText = searchStr;
                    for (int i = 0; i < tokens.Length; i++)
                    {
                        cmd.Parameters.Add("@search" + i.ToString(), SqlDbType.NVarChar).Value = "%" + tokens[i] + "%";
                    }
                    DataSet ds = new DataSet();
                    SqlDataAdapter da = new SqlDataAdapter(cmd);
                    da.Fill(ds);
                    conn.Close();

                    Session["EventSearchDS"] = ds;
                }
                Response.Redirect("EventSearch.aspx");
                break;
            case "M":
                Response.Redirect("User.aspx?ID=" + Session["User"].ToString());
                break;
            case "P":
                Response.Redirect("PrizesToWin.aspx");
                break;
            case "L":
                Response.Redirect("UserLogin.aspx");
                break;
            case "R":
                Response.Redirect("Register.aspx");
                break;
            case "W":
                Response.Redirect("PostAndWin.aspx");
                break;
            case "O":
                d.Execute("DELETE FROM Events_Seen_By_User WHERE userID=" + Session["User"].ToString());
                string save1 = "";
                if (Session["AnonymousUser"] != null)
                    save1 = Session["AnonymousUser"].ToString();

                string save2 = "";
                if (Session["BigAnonymousUser"] != null)
                    save2 = Session["BigAnonymousUser"].ToString();

                Session.Remove("User");
                Session.Remove("UserName");
                FormsAuthentication.SignOut();

                if (save1 != "")
                    Session["AnonymousUser"] = save1;

                if (save2 != "")
                    Session["BigAnonymousUser"] = save2;

                Response.Redirect("Home.aspx");
                break;
            default: break;
        }
    }
    private void GetMainEvents()
    {
        HttpCookie cookie = Request.Cookies["BrowserDate"];
        Data d = new Data(DateTime.Parse(cookie.Value.ToString().Replace("%20", " ").Replace("%3A", ":")));
        int rowCount = 0;

        try
        {

            if (Session["User"] != null)
            {
                EventsPanel.Controls.Clear();

                DataSet ds = d.GetEventsInLocation(true);

                if (ds.Tables.Count > 0)
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        rowCount = ds.Tables[0].Rows.Count;
                        if (rowCount > cutOff)
                            rowCount = cutOff;
                        for (int i = 0; i < rowCount; i++)
                        {
                            ASP.controls_otherevent_ascx anEvent = new ASP.controls_otherevent_ascx();
                            anEvent.EVENT_ID = ds.Tables[0].Rows[i]["ID"].ToString();
                            anEvent.TITLE = ds.Tables[0].Rows[i]["Header"].ToString();
                            anEvent.SUMMARY = ds.Tables[0].Rows[i]["ShortDescription"].ToString();
                            anEvent.PRESENTED_BY = d.GetDataDV("SELECT DateTimeStart FROM Event_Occurance WHERE EventID=" +
                                ds.Tables[0].Rows[i]["ID"].ToString())[0]["DateTimeStart"].ToString();
                            EventsPanel.Controls.Add(anEvent);
                            //goto NotMuchElse;

                            d.Execute("INSERT INTO Events_Seen_By_User (eventID, userID, Date, SessionID) " +
                                " VALUES(" + ds.Tables[0].Rows[i]["ID"].ToString() + ", " + Session["User"].ToString() + ", " +
                                " '" + DateTime.Parse(cookie.Value.ToString().Replace("%20", " ").Replace("%3A", ":")).ToString() +
                                "', '" + Session["UserSession" + Session["User"].ToString()].ToString() + "')");
                        }

                    }
            }
            else
            {
                DataView dvLocation = d.GetDataDV("SELECT * FROM Users WHERE IPs LIKE '&;" + d.GetIP() + ";%'");

                if(dvLocation.Count == 0)
                    dvLocation =  d.GetDataDV("SELECT * FROM SearchIPs WHERE IP = '" + d.GetIP() + "'");
                DataSet ds = new DataSet();
                bool getUS = false;
                if (Session["GenericEventSession"] == null)
                {
                    Random rand = new Random(DateTime.Parse(cookie.Value.ToString().Replace("%20", " ").Replace("%3A", ":")).ToUniversalTime().Millisecond);
                    Session["GenericEventSession"] = rand.Next();
                }

                if (dvLocation.Count > 0)
                {
                    string country = "";
                    string state = "";
                    string city = "";
                    if (dvLocation[0]["Country"].ToString() != "")
                        country = " AND E.Country = " + dvLocation[0]["Country"].ToString();
                    if (dvLocation[0]["State"].ToString() != "")
                        state = " AND E.State = @p0 ";
                    if (dvLocation[0]["City"].ToString() != "")
                        city = " AND E.City = @p1 ";

                    DataSet dsSeenAds = d.GetData("SELECT * FROM Events_Seen_Generic WHERE IP='" +
                        d.GetIP() + "' AND SessionID='" +
                        Session["GenericEventSession"].ToString() + "'");
                    string notTheseAds = "";

                    if (dsSeenAds.Tables.Count > 0)
                        if (dsSeenAds.Tables[0].Rows.Count > 0)
                        {
                            for (int j = 0; j < dsSeenAds.Tables[0].Rows.Count; j++)
                            {
                                if (notTheseAds != "")
                                    notTheseAds += " AND ";
                                notTheseAds += " E.ID <> " + dsSeenAds.Tables[0].Rows[j]["eventID"].ToString();

                            }
                        }
                    if (notTheseAds != "")
                        notTheseAds = " AND ( " + notTheseAds + " ) ";

                    bool couldGetMore = false;

                    if (state != "")
                    {
                        if (city != "")
                        {
                            SqlDbType[] types = { SqlDbType.NVarChar, SqlDbType.NVarChar };
                            object[] data = { dvLocation[0]["State"].ToString(), dvLocation[0]["City"].ToString() };
                            ds = d.GetDataWithParemeters("SELECT  DISTINCT EO.EventID, E.Header, E.Content, E.SponsorPresenter, EO.DateTimeStart FROM Events E, Event_Occurance EO WHERE EO.DateTimeStart >= GETDATE() AND  E.ID=EO.EventID " + notTheseAds + country + state + city, types, data);
                        }
                        else
                        {
                            SqlDbType[] types = { SqlDbType.NVarChar };
                            object[] data = { dvLocation[0]["State"].ToString() };
                            ds = d.GetDataWithParemeters("SELECT  DISTINCT EO.EventID, E.Header, E.Content, E.SponsorPresenter, EO.DateTimeStart FROM Events E, Event_Occurance EO WHERE EO.DateTimeStart >= GETDATE() AND  E.ID=EO.EventID " + notTheseAds + country + state, types, data);
                        }
                    }
                    else
                        ds = d.GetData("SELECT  DISTINCT EO.EventID, E.Header, E.Content, E.SponsorPresenter, EO.DateTimeStart FROM Events E, Event_Occurance EO WHERE EO.DateTimeStart >= GETDATE() AND  E.ID=EO.EventID " + notTheseAds + country);

                    EventsPanel.Controls.Clear();
                    if (ds.Tables.Count > 0)
                        if (ds.Tables[0].Rows.Count > 0)
                        {

                        }
                        else
                        {
                            couldGetMore = true;
                        }
                    else
                    {
                        couldGetMore = true;
                    }

                    if (couldGetMore)
                    {
                        Random rand = new Random(DateTime.Parse(cookie.Value.ToString().Replace("%20", " ").Replace("%3A", ":")).ToUniversalTime().Millisecond);
                        d.Execute("DELETE FROM Events_Seen_Generic WHERE SessionID='" +
                            Session["GenericEventSession"].ToString() + "' AND IP='" + d.GetIP() + "'");

                        Session["GenericEventSession"] = rand.Next();
                        if (state != "")
                        {
                            if (city != "")
                            {
                                SqlDbType[] types = { SqlDbType.NVarChar, SqlDbType.NVarChar };
                                object[] data = { dvLocation[0]["State"].ToString(), dvLocation[0]["City"].ToString() };
                                ds = d.GetDataWithParemeters("SELECT  DISTINCT EO.EventID, E.Header, E.Content, E.SponsorPresenter, EO.DateTimeStart FROM Events E, Event_Occurance EO WHERE EO.DateTimeStart >= GETDATE() AND  E.ID=EO.EventID " + country + state + city, types, data);
                            }
                            else
                            {
                                SqlDbType[] types = { SqlDbType.NVarChar };
                                object[] data = { dvLocation[0]["State"].ToString() };
                                ds = d.GetDataWithParemeters("SELECT  DISTINCT EO.EventID, E.Header, E.Content, E.SponsorPresenter, EO.DateTimeStart FROM Events E, Event_Occurance EO WHERE EO.DateTimeStart >= GETDATE() AND  E.ID=EO.EventID " + country + state, types, data);
                            }
                        }
                        else
                            ds = d.GetData("SELECT  DISTINCT EO.EventID, E.Header, E.Content, E.SponsorPresenter, EO.DateTimeStart FROM Events E, Event_Occurance EO WHERE EO.DateTimeStart >= GETDATE() AND  E.ID=EO.EventID " + country);

                        if (ds.Tables.Count > 0)
                            if (ds.Tables[0].Rows.Count > 0)
                            {
                            }
                            else
                                getUS = true;
                        else
                            getUS = true;
                    }
                }
                else
                {
                    getUS = true;
                }

                if (getUS)
                {
                    ds = d.GetData("SELECT DISTINCT EO.EventID, E.Header, E.Content, E.SponsorPresenter, EO.DateTimeStart FROM Events E, Event_Occurance EO  WHERE EO.DateTimeStart >= GETDATE() AND  E.ID=EO.EventID AND E.Country=223");
                }

                if (ds.Tables.Count > 0)
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        rowCount = ds.Tables[0].Rows.Count;
                        if (rowCount > cutOff)
                            rowCount = cutOff;
                        for (int i = 0; i < rowCount; i++)
                        {
                            ASP.controls_otherevent_ascx anEvent = new ASP.controls_otherevent_ascx();
                            anEvent.EVENT_ID = ds.Tables[0].Rows[i]["EventID"].ToString();
                            anEvent.TITLE = ds.Tables[0].Rows[i]["Header"].ToString();
                            anEvent.SUMMARY = ds.Tables[0].Rows[i]["Content"].ToString();
                            anEvent.PRESENTED_BY = ds.Tables[0].Rows[i]["DateTimeStart"].ToString();
                            EventsPanel.Controls.Add(anEvent);
                            //goto NotMuchElse;

                            d.Execute("INSERT INTO Events_Seen_Generic (eventID, IP, Date, SessionID) " +
                                                                " VALUES(" + ds.Tables[0].Rows[i]["EventID"].ToString() + ", '" + d.GetIP() + "', " +
                                                                " '" + DateTime.Parse(cookie.Value.ToString().Replace("%20", " ").Replace("%3A", ":")).Date.ToString() + "', '" + Session["GenericEventSession"].ToString() + "')");
                        }

                    }

            }
        }
        catch (Exception ex)
        {

        }
    }
    private void GetMainEvents()
    {
        HttpCookie cookie = Request.Cookies["BrowserDate"];
        Data d = new Data(DateTime.Parse(cookie.Value.ToString().Replace("%20", " ").Replace("%3A", ":")));
        int rowCount = 0;

        try
        {

            if (Session["User"] != null)
            {
                EventsPanel.Controls.Clear();

                if (Session["UserSessionEvents"] == null)
                {
                    DataSet dsT = d.GetEventsInLocation(true);
                    Session["UserSessionEvents"] = dsT;
                }

                DataSet ds = (DataSet)Session["UserSessionEvents"];

                if (Session["UserSessionLastSeenEvent"] == null)
                    Session["UserSessionLastSeenEvent"] = "-1";

                if (ds.Tables.Count > 0)
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        rowCount = ds.Tables[0].Rows.Count;
                        if (rowCount > cutOff)
                            rowCount = cutOff;

                        int startIndex = 0;
                        if (Session["UserSessionLastSeenEvent"].ToString() != "-1")
                            startIndex = int.Parse(Session["UserSessionLastSeenEvent"].ToString());

                        int endIndex = startIndex + cutOff;

                        Session["UserSessionLastSeenEvent"] = endIndex - 1;

                        if (endIndex > ds.Tables[0].Rows.Count)
                        {
                            endIndex = ds.Tables[0].Rows.Count;
                            Session["UserSessionLastSeenEvent"] = "-1";
                        }

                        for (int i = startIndex; i < endIndex; i++)
                        {
                            ASP.controls_otherevent_ascx anEvent = new ASP.controls_otherevent_ascx();
                            anEvent.EVENT_ID = ds.Tables[0].Rows[i]["ID"].ToString();
                            anEvent.TITLE = ds.Tables[0].Rows[i]["Header"].ToString();
                            anEvent.SUMMARY = ds.Tables[0].Rows[i]["Content"].ToString();
                            anEvent.PRESENTED_BY = d.GetDataDV("SELECT DateTimeStart FROM Event_Occurance WHERE EventID=" +
                                ds.Tables[0].Rows[i]["ID"].ToString())[0]["DateTimeStart"].ToString();
                            EventsPanel.Controls.Add(anEvent);
                        }
                    }
            }
            else
            {

                if (Session["GenericEventSession"] == null)
                {
                    DataView dvLocation = d.GetDataDV("SELECT * FROM Users WHERE IPs LIKE '&;" + d.GetIP() + ";%'");

                    if (dvLocation.Count == 0)
                        dvLocation = d.GetDataDV("SELECT * FROM SearchIPs WHERE IP = '" + d.GetIP() + "'");
                    DataSet ds = new DataSet();
                    bool getUS = false;

                    if (dvLocation.Count > 0)
                    {
                        string country = "";
                        string state = "";
                        string city = "";
                        if (dvLocation[0]["Country"].ToString() != "")
                            country = " AND E.Country = " + dvLocation[0]["Country"].ToString();
                        if (dvLocation[0]["State"].ToString() != "")
                            state = " AND E.State = @p0 ";
                        if (dvLocation[0]["City"].ToString() != "")
                            city = " AND E.City = @p1 ";

                        bool couldGetMore = false;

                        if (state != "")
                        {
                            if (city != "")
                            {
                                SqlDbType[] types = { SqlDbType.NVarChar, SqlDbType.NVarChar };
                                object[] data = { dvLocation[0]["State"].ToString(), dvLocation[0]["City"].ToString() };
                                ds = d.GetDataWithParemeters("SELECT  DISTINCT EO.EventID, E.Header, E.Content, E.SponsorPresenter, EO.DateTimeStart FROM Events E, Event_Occurance EO WHERE EO.DateTimeStart >= GETDATE() AND  E.ID=EO.EventID " + country + state + city, types, data);
                            }
                            else
                            {
                                SqlDbType[] types = { SqlDbType.NVarChar };
                                object[] data = { dvLocation[0]["State"].ToString() };
                                ds = d.GetDataWithParemeters("SELECT  DISTINCT EO.EventID, E.Header, E.Content, E.SponsorPresenter, EO.DateTimeStart FROM Events E, Event_Occurance EO WHERE EO.DateTimeStart >= GETDATE() AND  E.ID=EO.EventID " + country + state, types, data);
                            }
                        }
                        else
                            ds = d.GetData("SELECT  DISTINCT EO.EventID, E.Header, E.Content, E.SponsorPresenter, EO.DateTimeStart FROM Events E, Event_Occurance EO WHERE EO.DateTimeStart >= GETDATE() AND  E.ID=EO.EventID " + country);

                        EventsPanel.Controls.Clear();
                        if (ds.Tables.Count > 0)
                            if (ds.Tables[0].Rows.Count > 0)
                            {

                            }
                            else
                            {
                                getUS = true;
                            }
                        else
                        {
                            getUS = true;
                        }
                    }
                    else
                    {
                        getUS = true;
                    }

                    if (getUS)
                    {
                        ds = d.GetData("SELECT DISTINCT EO.EventID, E.Header, E.Content, E.SponsorPresenter, EO.DateTimeStart FROM Events E, Event_Occurance EO  WHERE EO.DateTimeStart >= GETDATE() AND  E.ID=EO.EventID AND E.Country=223");
                    }

                    Session["GenericEventSession"] = ds;
                    Session["GenericLastSeenEvent"] = "-1";
                }

                if (Session["GenericLastSeenEvent"] == null)
                    Session["GenericLastSeenEvent"] = "-1";

                DataSet dsTotal = (DataSet)Session["GenericEventSession"];

                if (dsTotal.Tables.Count > 0)
                    if (dsTotal.Tables[0].Rows.Count > 0)
                    {
                        rowCount = dsTotal.Tables[0].Rows.Count;
                        if (rowCount > cutOff)
                            rowCount = cutOff;

                        int startIndex = 0;
                        if (Session["GenericLastSeenEvent"].ToString() != "-1")
                            startIndex = int.Parse(Session["GenericLastSeenEvent"].ToString());

                        int endIndex = startIndex + cutOff;

                        Session["GenericLastSeenEvent"] = endIndex - 1;

                        if (endIndex > dsTotal.Tables[0].Rows.Count)
                        {
                            endIndex = dsTotal.Tables[0].Rows.Count;
                            Session["GenericLastSeenEvent"] = "-1";
                        }

                        for (int i = startIndex; i < endIndex; i++)
                        {
                            ASP.controls_otherevent_ascx anEvent = new ASP.controls_otherevent_ascx();
                            anEvent.EVENT_ID = dsTotal.Tables[0].Rows[i]["EventID"].ToString();
                            anEvent.TITLE = dsTotal.Tables[0].Rows[i]["Header"].ToString();
                            anEvent.SUMMARY = dsTotal.Tables[0].Rows[i]["Content"].ToString();
                            anEvent.PRESENTED_BY = dsTotal.Tables[0].Rows[i]["DateTimeStart"].ToString();
                            EventsPanel.Controls.Add(anEvent);
                        }
                    }

            }
        }
        catch (Exception ex)
        {
            Label l = new Label();
            l.Text = ex.ToString();
            EventsPanel.Controls.Add(l);
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        //2/23/2010%2020%3A54%3A38
        HttpCookie cookie = Request.Cookies["BrowserDate"];
        if (cookie == null)
        {
            cookie = new HttpCookie("BrowserDate");
            cookie.Value = DateTime.Now.ToString();
            cookie.Expires = DateTime.Now.AddDays(22);
            Response.Cookies.Add(cookie);
        }

        DateTime isn = DateTime.Now;

        if (!DateTime.TryParse(cookie.Value.ToString().Replace("%20", " ").Replace("%3A", ":"), out isn))
            isn = DateTime.Now;
        DateTime isNow = isn;
        Data dat = new Data(isn);

        if ((Session["User"] == null && Session["UserName"] != null) ||
            (Session["UserName"] == null && Session["User"] != null))
        {
            Response.Redirect("login");
        }

        //if (!IsPostBack)
        //{
        try
        {
            if (!IsPostBack)
            {
                //TextWriter tw = new StreamWriter(Server.MapPath("~/js/TotalJS.js"), false);
                //string str = "function timedout(){var today=new Date();var month=today.getMonth()+1;" +
                //    "var day=today.getDate();var year=today.getFullYear();var hours=today." +
                //    "getHours();var mins=today.getMinutes();var seconds=today.getSeconds();" +
                //    "var todayDate=month+'/'+day+'/'+year+' '+hours+':'+mins+':'+seconds;" +
                //    "setCookie(\"TimeZone\",today.getTimezoneOffset(),1);setCookie(\"BrowserDate\"," +
                //        "todayDate,1);}function setCookie(c_name,value,expiredays){var exdate=new " +
                //        "Date();exdate.setDate(exdate.getDate()+expiredays);document.cookie=" +
                //        "c_name+\"=\"+escape(value)+((expiredays==null)?\"\":\";expires=\"+exdate" +
                //        ".toGMTString())}function getCookie(c_name){if(document.cookie.length>0)" +
                //        "{c_start=document.cookie.indexOf(c_name+\"=\");if(c_start!=-1){c_start" +
                //        "=c_start+c_name.length+1;c_end=document.cookie.indexOf(\";\",c_start);" +
                //                        "if(c_end==-1)c_end=document.cookie.length;return unescape(document.cookie." +
                //                        "substring(c_start,c_end))}}return\"\"}" +
                //        "function setWidth(randNum)" +
                //        "{" +
                //           " var theWidthDiv = document.getElementById('widthDiv'+randNum);" +
                //         "   var theWrapDiv = document.getElementById('WrapDiv'+randNum);" +
                //         "   theWrapDiv.style.width = theWidthDiv.childNodes[3].offsetWidth + 14 + 'px';" +
                //         "   var somtinhere = 0;" +
                //        "}" +
                //        "function setWidthGreen(randNum)" +
                //        "{" +
                //         "   var theWidthDiv = document.getElementById('widthDiv'+randNum);" +
                //         "   var theWrapDiv = document.getElementById('WrapDiv'+randNum);" +
                //         "   theWrapDiv.style.width = theWidthDiv.childNodes[3].offsetWidth + 16 + 'px';" +
                //         "   var somtinhere = 0;" +
                //        "}" +
                //        "function setWait(event)" +
                //        "{" +
                //            "var thisGuy = document.getElementById(event.target.id);" +
                //            "if(thisGuy != null && thisGuy != undefined)" +
                //           "     thisGuy.style.cursor = 'wait';" +
                //            "return true;" +
                //        "}";
                //// write a line of text to the file
                //tw.WriteLine(str);

                //// close the stream
                //tw.Close();

                bool isPageNew = bool.Parse(ConfigurationSettings.AppSettings["isPageNew"].ToString());
                if (!isPageNew)
                    ConfigurationSettings.AppSettings["isPageNew"] = "true";

                if (Session["User"] == null)
                {
                    dat.Execute("INSERT INTO IP_User_Traffic (IP, PageName, DateAndTime) " +
                        "VALUES ('" + dat.GetIP() + "', '" + Request.Url.AbsolutePath.ToLower() +
                        "', GETDATE())");
                }
                else
                {
                    dat.Execute("INSERT INTO IP_User_Traffic (IP, UserID, PageName, DateAndTime) " +
                        "VALUES ('" + dat.GetIP() + "', " + Session["User"].ToString() +
                        ",'" + Request.Url.AbsolutePath.ToLower() + "', GETDATE())");
                }
            }
        }
        catch (Exception ex)
        {

        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        HttpCookie cookie = Request.Cookies["BrowserDate"];
        if (cookie == null)
        {
            cookie = new HttpCookie("BrowserDate");
            cookie.Value = DateTime.Now.ToString();
            cookie.Expires = DateTime.Now.AddDays(22);
            Response.Cookies.Add(cookie);
        }
        DateTime today = DateTime.Parse(cookie.Value.ToString().Replace("%20", " ").Replace("%3A", ":"));
        Data dat = new Data(today);
        DataSet ds;

        if (Request.QueryString["ID"] != null)
        {
            string catID = Request.QueryString["ID"].ToString();
            string location = "";

            //Get the location
            if (Session["User"] != null)
            {
                DataView dvPrefs = dat.GetDataDV("SELECT * FROM UserPreferences WHERE UserID=" + Session["User"].ToString());
                location = " AND A.CatState='" + dvPrefs[0]["CatState"].ToString() + "' AND A.CatCity='" + dvPrefs[0]["CatCity"].ToString() + "'";
            }
            else
            {
                DataView dvIP = dat.GetDataDV("SELECT * FROM Users U, UserPreferences UP WHERE UP.UserID=U.User_ID AND U.IPs LIKE '%;" + dat.GetIP() + ";%'");

                //If one or multiple found, look up ads on city and state of the first record
                if (dvIP.Count > 0)
                {
                    location = " AND A.CatState='" + dvIP[0]["CatState"].ToString() +
                        "' AND A.CatCity='" + dvIP[0]["CatCity"].ToString() + "'";
                }
                //If not found look in searches table, get the city and state
                else
                {
                    DataView dvSearch = dat.GetDataDV("SELECT * FROM SearchIPs WHERE IP='" + dat.GetIP() + "'");
                    location = " AND A.CatState='" + dvSearch[0]["State"].ToString() +
                        "' AND A.CatCity='" + dvSearch[0]["City"].ToString() + "'";
                }
            }

            string sqlToday = "CONVERT(DATETIME, '" + today.Month.ToString() + "/" +
                today.Day.ToString() + "/" + today.Year.ToString() + "')";
            string timeline = " AND AC.DateTimeStart <= " + sqlToday + " AND ((A.Featured = 'True' " +
                "AND A.NumCurrentViews < A.NumViews) OR (A.Featured='False' AND AC.DateTimeEnd >= " +
                sqlToday + "))";

            ds = dat.GetData("SELECT ACM.AdID AS Ad_ID, C.ID, A.Header, C.Name AS CategoryName, " +
                "ACM.tagSize FROM Ad_Category_Mapping ACM, AdCategories C, Ads A, Ad_Calendar AC WHERE " +
                "ACM.AdID=A.Ad_ID AND AC.AdID=A.Ad_ID AND ACM.CategoryID=C.ID AND ACM.CategoryID=" +
                catID + location + timeline);
            SearchElements.AD_DS = ds;
            SearchElements.DataBind2();

            NumResultsLabel.Text = "(" + ds.Tables[0].Rows.Count + " Records Found)";

            HtmlHead head = (HtmlHead)Page.Header;

            string theLink = "";

            if (ds.Tables[0].Rows.Count > 0)
            {
                theLink = "http://" + Request.Url.Authority + "/" +
                dat.MakeNiceName(ds.Tables[0].Rows[0]["CategoryName"].ToString()) + "_Ad_Category";
            }
            else
            {
                theLink = "http://" + Request.Url.Authority + "/AdCategorySearch.aspx?ID=" + catID;
            }

            HtmlLink lk = new HtmlLink();
            lk.Href = theLink;
            lk.Attributes.Add("rel", "bookmark");
            head.Controls.AddAt(0, lk);

            HtmlMeta hm = new HtmlMeta();
            HtmlMeta kw = new HtmlMeta();
            HtmlMeta dc = new HtmlMeta();

            kw.Name = "keywords";

            if (ds.Tables[0].Rows.Count > 0)
            {
                kw.Content = ds.Tables[0].Rows[0]["CategoryName"].ToString() + " Ad Category";
            }
            else
            {
                kw.Content = "No Ad Category";
            }

            head.Controls.AddAt(0, kw);

            dc.Name = "description";
            if (ds.Tables[0].Rows.Count > 0)
            {
                dc.Content = "Results for ad category: " + ds.Tables[0].Rows[0]["CategoryName"].ToString();
            }
            else
            {
                dc.Content = "Results for ad category: None";
            }

            head.Controls.AddAt(0, dc);

            if(ds.Tables.Count > 0)
                if (ds.Tables[0].Rows.Count > 0)
                {
                    SearchResultsTitleLabel.Text = "<a href=\"" + theLink + "\" style=\"text-decoration: none; color: white;\" >Ads in '" +
                        ds.Tables[0].Rows[0]["CategoryName"].ToString() + "' Category</a>";
                }
                else
                {
                    SearchResultsTitleLabel.Text = "No Ads Found";
                }
            else
            {
                SearchResultsTitleLabel.Text = "No Ads Found";
            }
        }else
        {
            Response.Redirect("Home.aspx");
        }

        string cookieName = FormsAuthentication.FormsCookieName;
        HttpCookie authCookie = Context.Request.Cookies[cookieName];

        FormsAuthenticationTicket authTicket = null;
        try
        {
            string group = "";
            if (authCookie != null)
            {
                authTicket = FormsAuthentication.Decrypt(authCookie.Value);
                group = authTicket.UserData.ToString();
            }

            if (group.Contains("User"))
            {
                Session["User"] = authTicket.Name;
                DataSet ds1 = dat.GetData("SELECT UserName FROM Users WHERE User_ID=" + authTicket.Name);
                Session["UserName"] = ds1.Tables[0].Rows[0]["UserName"].ToString();

            }
            else
            {
            }
        }
        catch (Exception ex)
        {
        }
    }